diff --git "a/2426.jsonl" "b/2426.jsonl" new file mode 100644--- /dev/null +++ "b/2426.jsonl" @@ -0,0 +1,338 @@ +{"seq_id":"24593027552","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 15 00:20:33 2019\r\n\r\n@author: Owner\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom numpy import loadtxt\r\n\r\nPx = loadtxt('Px_2.dat', unpack=True)\r\nPy = loadtxt('Py_2.dat', unpack=True)\r\n\r\nNa = []\r\nfor N in range(1, 10000+1, 1):\r\n Na.append(N)\r\nprint(len(Na))\r\n \r\nNb = loadtxt('Nb.dat', unpack=True)\r\n\r\nplt.plot(Na, Px, label='$P(\\mu_x > \\mu_y)$')\r\nplt.plot(Na, Py, label='$P(\\mu_y > \\mu_x)$')\r\nplt.plot([0, 2000], [1, 1], linestyle='--', color='k') #Asymptotic probability\r\nplt.plot([0, 2000], [0, 0], linestyle='--', color='k') #Asymptotic probability\r\nplt.ylim(-0.05, 1.05)\r\nplt.xlim(0, 2000)\r\nplt.xlabel('N')\r\nplt.ylabel('Probability')\r\nplt.legend(loc='lower right', bbox_to_anchor=(0.85, 0.4), prop={'size':12})\r\nplt.savefig('Mean_discrepancy_plot.pdf')\r\n\r\nprint(min(Nb))","repo_name":"ladosamushia/PHYS707","sub_path":"Joe_Ryan/Mean_plotter.py","file_name":"Mean_plotter.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"7932152180","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import annotations\n\nimport csv\nimport os\nimport re\nimport time\nfrom typing import Tuple, List, Optional, Generator\n\nimport pandas as pd\nimport networkx as nx\n\nfrom sciutils.partial import ProperPartial\nfrom .data_specific import RAW_CHIAPET_FILE_COLUMNS, RAW_BED_FILE_COLUMNS, RAW_DATA_FILES, CHROMOSOMES, ChromosomeDtype\nfrom .points_in_regions import points_in_disjoint_regions\n\n\ndef load_raw_chiapet_text_file(file_path: str) -> pd.DataFrame:\n df = pd.read_csv(\n file_path,\n sep='\\t',\n header=None,\n index_col=False,\n usecols=range(7),\n names=[name for name, _ in RAW_CHIAPET_FILE_COLUMNS],\n dtype={name: dtype for name, dtype in RAW_CHIAPET_FILE_COLUMNS},\n engine='c',\n quoting=csv.QUOTE_NONE\n )\n return df\n\n\ndef load_raw_bed_file(file_path: str) -> pd.DataFrame:\n df = pd.read_csv(\n file_path,\n sep='\\t',\n header=None,\n index_col=False,\n usecols=range(3),\n names=[name for name, _ in RAW_BED_FILE_COLUMNS],\n dtype={name: dtype for name, dtype in RAW_BED_FILE_COLUMNS},\n engine='c',\n quoting=csv.QUOTE_NONE,\n )\n return df\n\n\ndef save_raw_bed_file(df: pd.DataFrame, file_path: str):\n df.to_csv(file_path, sep='\\t', header=False, index=False)\n\n\ndef write_pandas_to_raw_chiapet_text_file(df: pd.DataFrame, file_path: str) -> None:\n df.to_csv(file_path, sep='\\t', header=False, index=False, quoting=csv.QUOTE_NONE)\n\n\nclass ChiapetData(object):\n STORED_MIN_PETCOUNTS = (1, 2, 4)\n\n def __init__(\n self, data_dir,\n data_filename_pattern=r'(?P[A-Za-z0-9]+)_(?P[A-Za-z0-9]+)_(?Pchrom(?:X|Y|M|\\d\\d?))_PET(?P\\d+)\\+.txt',\n data_filename_format='{celline}_{protein}_{chromosome}_PET{min_petcount}+.txt'\n ):\n assert os.path.exists(data_dir)\n assert os.access(data_dir, os.R_OK)\n self._data_dir = data_dir\n self._data_filename_pattern = re.compile(data_filename_pattern)\n self._data_filename_format = data_filename_format\n\n @property\n def data_dir(self) -> str:\n return self._data_dir\n\n def _chiapet_filename(self, celline: str, protein: str, chromosome: str, stored_min_petcount: int) -> str:\n return self._data_filename_format.format(\n celline=celline, protein=protein, chromosome=chromosome, min_petcount=stored_min_petcount\n )\n\n def get_data_files(self) -> List[str]:\n files = []\n for filename in os.listdir(self.data_dir):\n m = self._data_filename_pattern.match(filename)\n if m is not None:\n files.append(m.group(0))\n return files\n\n def organize_data(self, input_dir: str) -> None:\n for filename in self.get_data_files():\n os.remove(filename)\n for celline, celline_data in RAW_DATA_FILES.items():\n for target_protein, data_files in celline_data.items():\n t0 = time.time()\n print(f'Starting processing {celline}-{target_protein}')\n group_df = self._read_group_data(input_dir, data_files)\n print(f'Read data files for {celline}-{target_protein} in {time.time() - t0:.2f}s.')\n self._organize_group(self.data_dir, group_df, celline, target_protein)\n print(f'Done processing {celline}-{target_protein} in {time.time() - t0:.2f}s.')\n\n @staticmethod\n def _read_group_data(input_dir: str, data_files: List[str]) -> pd.DataFrame:\n group_df = pd.concat([\n load_raw_chiapet_text_file(os.path.join(input_dir, filename))\n for filename in data_files\n ], ignore_index=True)\n return group_df\n\n def _organize_group(self, output_dir: str, group_df: pd.DataFrame, celline: str, protein: str) -> None:\n positional_cols = list(name for name, _ in RAW_CHIAPET_FILE_COLUMNS)[:6]\n group_df.sort_values(by=positional_cols, ascending=True, inplace=True)\n group_df.drop_duplicates(positional_cols, inplace=True)\n\n same_chrom = group_df.A_chrom == group_df.B_chrom\n intra_df = group_df[same_chrom]\n inter_df = group_df[~same_chrom]\n\n def _filter_and_save(df, _min_petcount, _chromosome):\n filtered_df = df[df.petcount >= min_petcount]\n filename = self._chiapet_filename(celline, protein, _chromosome, _min_petcount)\n write_pandas_to_raw_chiapet_text_file(filtered_df, os.path.join(output_dir, filename))\n print(f'Wrote {filename}')\n\n for min_petcount in self.STORED_MIN_PETCOUNTS:\n _filter_and_save(inter_df, min_petcount, 'inter')\n for chromosome in CHROMOSOMES:\n _filter_and_save(intra_df[intra_df.A_chrom == chromosome], min_petcount, chromosome)\n\n def load_data(\n self,\n celline: str, target_protein: str, kind: str, regions: List[str], min_petcount: int\n ) -> pd.DataFrame:\n assert kind in ['intra', 'inter', 'all']\n\n if regions == 'all':\n regions = list(CHROMOSOMES)\n else:\n if isinstance(regions, str):\n regions = [regions]\n for region in regions:\n assert region in CHROMOSOMES # TODO: region filtering\n\n dfs = []\n if kind == 'intra' or kind == 'all':\n dfs.extend(self._load_intra(celline, target_protein, regions, min_petcount))\n if kind == 'inter' or kind == 'all':\n dfs.extend(self._load_inter(celline, target_protein, regions, min_petcount))\n df = pd.concat(dfs)\n return df\n\n def _load_intra(\n self,\n celline: str, target_protein: str, regions: List[str], min_petcount: int\n ) -> List[pd.DataFrame]:\n stored_min_petcount = self._get_stored_min_petcount(min_petcount)\n dfs = []\n for chromosome in regions:\n df = load_raw_chiapet_text_file(os.path.join(\n self._data_dir,\n self._chiapet_filename(celline, target_protein, chromosome, stored_min_petcount)\n ))\n df = df[df.petcount >= min_petcount]\n dfs.append(df)\n return dfs\n\n def _load_inter(\n self,\n celline: str, target_protein: str, regions: List[str], min_petcount: int\n ) -> List[pd.DataFrame]:\n stored_min_petcount = self._get_stored_min_petcount(min_petcount)\n df = load_raw_chiapet_text_file(os.path.join(\n self._data_dir,\n self._chiapet_filename(celline, target_protein, 'inter', stored_min_petcount)\n ))\n chromosomes = set(regions)\n df = df[df.A_chrom.isin(chromosomes) & df.B_chrom.isin(chromosomes) & (df.petcount >= min_petcount)]\n return [df]\n\n def _get_stored_min_petcount(self, petcount: int) -> int:\n for k in self.STORED_MIN_PETCOUNTS[::-1]:\n if k < petcount:\n return k\n return 1\n\n def loader(self, *args, **kwargs) -> ChiapetLoader:\n return ChiapetLoader(self, *args, **kwargs)\n\n def load_regions(self, path: str, regions: Optional[List[str]] = None):\n df = load_raw_bed_file(path)\n if regions is not None:\n chromosomes = set(regions)\n df = df[df.chrom.isin(chromosomes)]\n df.index.names = ['region_id']\n return df\n\n\nclass ChiapetLoader(object):\n def __init__(self, chiapet_data: ChiapetData, *args, **kwargs):\n self._chiapet_data = chiapet_data\n load_partial = ProperPartial(self.load_impl, *args, **kwargs)\n self.load = load_partial\n\n def load_impl(\n self,\n celline: str, target_protein: str, kind: str,\n regions: List[str], min_petcount: int\n ) -> pd.DataFrame:\n return self._chiapet_data.load_data(celline, target_protein, kind, regions, min_petcount)\n\n def load_regions(self, path: str, regions: Optional[List[str]] = None):\n if regions is None and 'regions' in self.load:\n regions = self.load['regions']\n return self._chiapet_data.load_regions(path, regions)\n\n\n_ANCHOR_ID_PARTS = ['chrom', 'start', 'end']\n_ANCHOR_ID_A = ['A_' + s for s in _ANCHOR_ID_PARTS]\n_ANCHOR_ID_B = ['B_' + s for s in _ANCHOR_ID_PARTS]\n\n\ndef _select_contacts_by_anchors(anchors: pd.DataFrame, contacts: pd.DataFrame) -> pd.DataFrame:\n contacts = pd.merge(\n contacts, anchors.reset_index().rename(\n columns=dict(zip(_ANCHOR_ID_PARTS, _ANCHOR_ID_A))\n ),\n on=_ANCHOR_ID_A\n )\n contacts = pd.merge(\n contacts, anchors.reset_index().rename(\n columns=dict(zip(_ANCHOR_ID_PARTS, _ANCHOR_ID_B))\n ),\n on=_ANCHOR_ID_B,\n suffixes=['_A', '_B']\n )\n contacts.index.names = ['contact_id']\n return contacts\n\n\ndef as_normalized_tables(df, use_midpoints=True):\n an1 = df[_ANCHOR_ID_A]\n an1.columns = _ANCHOR_ID_PARTS\n an2 = df[_ANCHOR_ID_B]\n an2.columns = _ANCHOR_ID_PARTS\n anchors = pd.concat([an1, an2], axis=0, ignore_index=True, sort=False)\n anchors.columns = _ANCHOR_ID_PARTS\n anchors = anchors.drop_duplicates(subset=_ANCHOR_ID_PARTS, keep='first')\n if use_midpoints:\n anchors['mid'] = (anchors.start + anchors.end) // 2\n sort_cols = ['chrom', 'mid']\n else:\n sort_cols = _ANCHOR_ID_PARTS\n anchors.sort_values(by=sort_cols, inplace=True)\n anchors = anchors.reset_index(drop=True)\n anchors.index.names = ['anchor_id']\n\n contacts = _select_contacts_by_anchors(anchors, df)\n\n # reorder columns & get rid of coords\n contacts = contacts[['anchor_id_A', 'anchor_id_B', 'petcount']]\n return anchors, contacts # TODO: copy to prevent set-on-view issues?\n\n\ndef anchor_midpoints_in_regions(anchors: pd.DataFrame, regions: pd.DataFrame, add_chrom_col: bool = False) -> pd.DataFrame:\n chromosomes = sorted(regions.chrom.unique())\n\n results = []\n for chrom in chromosomes:\n chrom_anchors = anchors[anchors.chrom == chrom]\n chrom_regions = regions[regions.chrom == chrom]\n id_pairs = points_in_disjoint_regions(\n chrom_anchors.anchor_id.values,\n chrom_anchors.mid.values,\n chrom_regions.region_id.values,\n chrom_regions.start.values,\n chrom_regions.end.values\n )\n chrom_df = pd.DataFrame(id_pairs, copy=False)\n chrom_df.columns = ['anchor_id', 'region_id']\n results.append(chrom_df)\n\n if add_chrom_col:\n df = pd.concat(results, keys=chromosomes, sort=False, names=['chrom']).reset_index('chrom')\n df['chrom'] = df.chrom.astype(ChromosomeDtype)\n df = df.reset_index(drop=True)\n else:\n df = pd.concat(results, sort=False, ignore_index=True)\n return df\n\n\ndef split_by_regions(anchors: pd.DataFrame, contacts: pd.DataFrame, regions: pd.DataFrame, midpoints=False) -> Generator[Tuple[int, Tuple[str, int, int], pd.DataFrame]]:\n pairings = anchor_midpoints_in_regions(anchors.reset_index(), regions.reset_index())\n for reg_id, reg_pairing in pairings.groupby('region_id'):\n reg_anchors_set = set(reg_pairing.anchor_id)\n reg_contacts = contacts[contacts.anchor_id_A.isin(reg_anchors_set) & contacts.anchor_id_B.isin(reg_anchors_set)]\n if midpoints:\n reg_anchors = anchors[anchors.index.isin(reg_anchors_set)].reset_index()\n reg_mid = reg_contacts\n reg_mid = pd.merge(reg_mid, reg_anchors[['anchor_id', 'mid']].rename(\n columns={'anchor_id': 'anchor_id_A', 'mid': 'mid_A'}\n ), on='anchor_id_A')\n reg_mid = pd.merge(reg_mid, reg_anchors[['anchor_id', 'mid']].rename(\n columns={'anchor_id': 'anchor_id_B', 'mid': 'mid_B'}\n ), on='anchor_id_B')\n res = reg_mid.sort_values(['mid_A', 'mid_B'])\n else:\n res = reg_contacts.sort_values(['anchor_id_A', 'anchor_id_B'])\n yield reg_id, tuple(regions.loc[reg_id]), res\n\n\ndef as_nx_graph(anchors, contacts, petcounts='petcount', drop_isolated_nodes=True):\n g = nx.Graph()\n if petcounts:\n g.add_weighted_edges_from(\n (\n (u, v, w) if u < v else (v, u, w)\n for _, (u, v, w) in contacts[['anchor_id_A', 'anchor_id_B', 'petcount']].iterrows()\n ),\n petcounts\n )\n else:\n g.add_edges_from(\n (\n (u, v) if u < v else (v, u)\n for _, (u, v) in contacts[['anchor_id_A', 'anchor_id_B']].iterrows()\n )\n )\n\n if not drop_isolated_nodes:\n g.add_nodes_from(anchors.index)\n\n return g","repo_name":"michade/sciutils","sub_path":"chiapet/chiapet.py","file_name":"chiapet.py","file_ext":"py","file_size_in_byte":12647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"11485152513","text":"import argparse\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nfrom torchvision import models\nimport time\nimport string\nimport random\nfrom fvcore.nn import FlopCountAnalysis, parameter_count\n\n\nbasic_model_dict = {\n \"AlexNet\": models.alexnet,\n \"VGG11\": models.vgg11,\n \"VGG13\": models.vgg13,\n \"VGG16\": models.vgg16,\n \"VGG19\": models.vgg19,\n \"VGG11BN\": models.vgg11_bn,\n \"VGG13BN\": models.vgg13_bn,\n \"VGG16BN\": models.vgg16_bn,\n \"VGG19BN\": models.vgg19_bn,\n \"ResNet18\": models.resnet18,\n \"ResNet34\": models.resnet34,\n \"ResNet50\": models.resnet50,\n \"ResNet101\": models.resnet101,\n \"ResNet152\": models.resnet152,\n \"SqueezeNet1_0\": models.squeezenet1_0,\n \"SqueezeNet1_1\": models.squeezenet1_1,\n \"DenseNet121\": models.densenet121,\n \"DenseNet161\": models.densenet161,\n \"DenseNet169\": models.densenet169,\n \"DenseNet201\": models.densenet201,\n \"InceptionV3\": models.inception_v3,\n \"GoogleNet\": models.googlenet,\n \"ShuffleNetV2\": models.shufflenet_v2_x1_0,\n \"MobileNetV2\": models.mobilenet_v2,\n \"ResNeXt50\": models.resnext50_32x4d,\n \"ResNeXt101_32\": models.resnext101_32x8d,\n \"WideResNet50\": models.wide_resnet50_2,\n \"WideResNet101\": models.wide_resnet101_2,\n \"MNASNet\": models.mnasnet1_0\n}\n\nversion_str_list = torchvision.__version__.split(\".\")[:2]\nversion_str = \".\".join(version_str_list)\n\nif version_str_list[0] == \"0\":\n min_version = eval(version_str_list[1])\n model_dict = basic_model_dict\n if min_version < 8:\n raise ValueError(f\"This version is not supported: {torchvision.__version__}\")\n elif min_version == 8:\n pass\n else:\n append_model_dict = {\n \"MobileNetV3_l\": models.mobilenet_v3_large,\n \"MobileNetV3_s\": models.mobilenet_v3_small\n }\n if min_version > 10:\n # TODO regnet\n extend_dict = {\n \"EfficientNet_B0\": models.efficientnet_b0,\n \"EfficientNet_B1\": models.efficientnet_b1,\n \"EfficientNet_B2\": models.efficientnet_b2,\n \"EfficientNet_B3\": models.efficientnet_b3,\n \"EfficientNet_B4\": models.efficientnet_b4,\n \"EfficientNet_B5\": models.efficientnet_b5,\n \"EfficientNet_B6\": models.efficientnet_b6,\n \"EfficientNet_B7\": models.efficientnet_b7,\n }\n for key, value in extend_dict.items():\n append_model_dict[key] = value\n\n if min_version > 11:\n extend_dict = {\n \"VIT_b_32\": models.vit_b_32,\n \"VIT_b_16\": models.vit_b_16,\n \"VIT_l_16\": models.vit_l_16,\n \"VIT_l_32\": models.vit_l_32,\n \"ConvNeXt_t\": models.convnext_tiny,\n \"ConvNeXt_s\": models.convnext_small,\n \"ConvNeXt_b\": models.convnext_base,\n \"ConvNeXt_l\": models.convnext_large\n }\n for key, value in extend_dict.items():\n append_model_dict[key] = value\n\n if min_version > 12:\n extend_dict = {\n \"EfficientNetV2_s\": models.efficientnet_v2_s,\n \"EfficientNetV2_m\": models.efficientnet_v2_m,\n \"EfficientNetV2_l\": models.efficientnet_v2_l,\n \"ResNeXt101_64\": models.resnext101_64x4d,\n \"Swin_s\": models.swin_s,\n \"Swin_b\": models.swin_b,\n \"Swin_t\": models.swin_t,\n \"VIT_h_14\": models.vit_h_14\n }\n for key, value in extend_dict.items():\n append_model_dict[key] = value\n\n if min_version > 13:\n extend_dict = {\n \"MaxVIT_t\": models.maxvit_t,\n \"SwinV2_s\": models.swin_v2_s,\n \"SwinV2_b\": models.swin_v2_b,\n \"SwinV2_t\": models.swin_v2_t,\n }\n for key, value in extend_dict.items():\n append_model_dict[key] = value\n\n for key, value in append_model_dict.items():\n model_dict[key] = value\nelse:\n raise ValueError(f\"This version is not supported: {torchvision.__version__}\")\n\nparser = argparse.ArgumentParser(description='Params of Benchmark')\n\nparser.add_argument(\"-m\", \"--model_type\", type=str, default=\"AlexNet\", choices=model_dict.keys())\nparser.add_argument(\"-b\", \"--batch_size\", type=int, default=64)\nparser.add_argument(\"-s\", \"--input_size\", type=int, default=32)\nparser.add_argument(\"--max_step\", type=int, default=800)\n\n\ndef generate_random_str(length=30):\n # string.ascii_letters 大小写字母, string.digits 为数字\n characters_long = list(string.ascii_letters + string.digits)\n\n # 打乱字符串序列\n random.shuffle(characters_long)\n\n # picking random characters from the list\n password = []\n # 生成密码个数\n for b in range(length):\n password.append(random.choice(characters_long))\n\n # 打乱密码顺序\n random.shuffle(password)\n\n # 将列表转换为字符串并打印\n return \"\".join(password)\n\n\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n\n net = model_dict[args.model_type](num_classes=10)\n print(args.model_type)\n\n # select device\n num_classes = 10\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n net = net.to(device)\n\n device_name_str = \"\"\n for _id in range(torch.cuda.device_count()):\n p = torch.cuda.get_device_properties(_id)\n device_name_str += f\"_{p.name}\"\n random_str = generate_random_str()\n log_file_name = \"./log/{}_{}{}_{}_{}.txt\".format(args.model_type, args.input_size, device_name_str, args.batch_size, random_str)\n with open(log_file_name, \"w\") as f:\n f.write(str(time.time()) + \"\\n\")\n f.write(version_str + \"\\n\")\n\n # optimizing\n criterion = nn.CrossEntropyLoss()\n optimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)\n\n begin_time = time.time()\n time_step_list = list()\n images = torch.rand([args.batch_size, 3, args.input_size, args.input_size]).to(device)\n labels = torch.randint(0, 10, [args.batch_size, ]).to(device)\n\n net.train()\n for i in range(args.max_step):\n step_begin_time = time.time()\n\n optimizer.zero_grad()\n outputs = net(images)\n loss = criterion(outputs, labels)\n loss.backward()\n optimizer.step()\n\n step_end_time = time.time()\n with open(log_file_name, \"a\") as f:\n time_step_list.append(step_end_time - step_begin_time)\n log_str = \"Step: [{}/{}], Avg time for each step {:.4f}s\" \\\n .format(i + 1, args.max_step, np.mean(time_step_list))\n print(log_str)\n f.write(log_str + \"\\n\")\n\n print(\"-------------------------\\n--- PARAMs & FLOPs --- \\n-------------------------\")\n test_tensor = torch.rand([1, 3, 224, 224]).to(device)\n flops = FlopCountAnalysis(net, test_tensor).total()\n params = parameter_count(net)[\"\"]\n with open(log_file_name, \"a\") as f:\n log_str = \"PARAMS: {:.4f}MB, FLOPS: {:.4f}MB\\n\".format(params / (1024 ** 2), flops / (1024 ** 2))\n print(log_str)\n f.write(log_str)\n\n print(\"-------------------------\\n----- DEVICE ----- \\n-------------------------\")\n device_name = None\n for _id in range(torch.cuda.device_count()):\n p = torch.cuda.get_device_properties(_id)\n info = f\"CUDA:{_id} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\\n\"\n if _id == 0:\n device_name = p.name\n print(info)\n with open(log_file_name, \"a\") as f:\n f.write(info)\n\n print(\"-------------------------\\n----- EACH STEP ----- \\n-------------------------\")\n with open(log_file_name, \"a\") as f:\n avg_step_str = \"Avg time for each step {:.4f}s\".format(np.mean(time_step_list))\n print(avg_step_str)\n f.write(avg_step_str + \"\\n\")\n\n with open(\"./README.md\", \"a\") as f:\n str_1 = f\"\\n|{args.model_type}|{device_name}|{params / (1024 ** 2):.4f}|{args.input_size}\"\n str_2 = f\"|{flops / (1024 ** 2):.4f}|{args.batch_size}|{np.mean(time_step_list):.4f}|{version_str}|\"\n f.write(str_1 + str_2)\n","repo_name":"USTB-ML/PytorchTrainingSpeedBenchmark","sub_path":"TrainingBenchmark.py","file_name":"TrainingBenchmark.py","file_ext":"py","file_size_in_byte":8499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"46"} +{"seq_id":"4965730471","text":"def solution():\n n = int(input())\n for _ in range(n):\n target = int(input())\n add = 0\n while True:\n if is_prime(target + add):\n print(target + add)\n break\n add += 1\n\n\ndef is_prime(n):\n if n <= 1:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n\n # 3부터 시작해서 2씩 증가하며 확인 (짝수는 이미 위에서 걸렀으므로 홀수만 확인)\n for d in range(3, int(n ** 0.5) + 1, 2):\n if n % d == 0:\n return False\n return True\n\n\nsolution()\n","repo_name":"lerrybe/PS","sub_path":"baekjoon/python/4134_다음소수.py","file_name":"4134_다음소수.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"12190045434","text":"import os\nimport sys\nimport ray\nimport copy\nimport numpy as np\n\nfrom ray.tune import TuneConfig\nfrom ray.tune.logger import pretty_print\n\nparent_directory = os.path.join(os.environ[\"BLACK_BOX\"])\nsys.path.append(parent_directory)\n\nfrom experiments.utils import validation_utils\nfrom experiments.agents.main_agent import MainAgent\nfrom experiments.agents.searcher import SearchAgent\n\n\nclass AdapSeqMCOptimizer:\n\n def __init__(self, algorithm_config: dict) -> None:\n self.algorithm_config = algorithm_config\n \n self.noise_level = self.algorithm_config[\"noise_level\"]\n self.metric = self.algorithm_config[\"metric\"]\n \n self.J = self.algorithm_config[\"J\"]\n self.Ne = self.algorithm_config[\"Ne\"]\n self.K = int(0.2 * self.Ne)\n\n search_space = self.algorithm_config[\"search_space\"]\n\n counter = 0\n self.trial_counter = 0\n self.Fj_counter = 0\n self.result_buffer = []\n self.current_trials = []\n self.update_ongoing = False\n\n if self.algorithm_config[\"space_type\"] == \"log\":\n self.Lj = np.logspace(\n start=np.log10(self.algorithm_config[\"eps_init\"]),\n stop=np.log10(self.algorithm_config[\"eps_final\"]),\n num=self.J\n )\n elif self.algorithm_config[\"space_type\"] == \"lin\":\n self.Lj = np.linspace(\n start=self.algorithm_config[\"eps_init\"],\n stop=self.algorithm_config[\"eps_final\"],\n num=self.J\n )\n else:\n raise ValueError(\"[ERROR]-> Invalid Space Type (must be 'log' or 'lin')\")\n \n print(\"\\n[INFO]-> Search Space:\\t\", self.Lj)\n\n self.min_point = [\n search_space[\"velocity\"][\"min\"], # ego vehicle initial speed\n search_space[\"velocity\"][\"min\"], # mio vehicle initial speed\n search_space[\"velocity\"][\"min\"], # mio vehicle final speed\n search_space[\"distance\"][\"min\"] # distance between ego and mio\n ]\n self.max_point = [\n search_space[\"velocity\"][\"max\"], # ego vehicle initial speed\n search_space[\"velocity\"][\"max\"], # mio vehicle initial speed\n search_space[\"velocity\"][\"max\"], # mio vehicle final speed\n search_space[\"distance\"][\"max\"] # distance between ego and mio\n ]\n\n # check and do not include impossible configurations\n while counter < self.Ne:\n # loop until 'possible to avoid collision' configuration is found\n for _ in range(self.algorithm_config[\"check_impossible_count\"]):\n parameters = self.uniformly_sample()\n \n # TODO: initial ego vehicle acceleration could be added to parameter space\n ego_acceleration = 0.0\n front_acceleration = np.clip(self.algorithm_config[\"desired_comfort_accel\"] * \\\n (1 - np.power(max(parameters[\"front_v1\"], 0) / parameters[\"front_v2\"], self.algorithm_config[\"velocity_exponent\"])), \\\n self.algorithm_config[\"front_accel_range\"][0], self.algorithm_config[\"front_accel_range\"][1])\n \n if validation_utils.is_impossible_2_stop(\n initial_distance = parameters[\"delta_dist\"],\n ego_velocity = parameters[\"ego_v1\"],\n front_velocity = parameters[\"front_v1\"],\n ego_acceleration = ego_acceleration, \n front_acceleration = front_acceleration\n ):\n continue\n else:\n break\n \n counter += 1\n self.current_trials.append(copy.deepcopy(parameters))\n \n self.Fj = [self.current_trials]\n\n # iterate, run, or sample and return dict\n def query(self) -> dict:\n if self.Fj_counter != self.J:\n \n if len(self.result_buffer) < self.Ne and self.trial_counter < self.Ne:\n \n search_configs = validation_utils.make_float(self.current_trials[self.trial_counter])\n print(\"\\n[INFO]-> Search Space:\\t\", pretty_print(search_configs))\n\n self.trial_counter += 1\n \n return search_configs\n else:\n return None\n \n else:\n print(\"[INFO]-> FINISHED!\")\n return None\n \n # get uniformly sampled initial conditions\n def uniformly_sample(self) -> dict:\n return {\n \"ego_v1\" : np.random.uniform(low=self.min_point[0], high=self.max_point[0]),\n \"front_v1\" : np.random.uniform(low=self.min_point[1], high=self.max_point[1]),\n \"front_v2\" : np.random.uniform(low=self.min_point[2], high=self.max_point[2]),\n \"delta_dist\" : np.random.uniform(low=self.min_point[3], high=self.max_point[3])\n }\n \n # add uniform noise to samples to be selected\n def apply_noise(self, params: dict, noise_level: float = 0.5) -> dict:\n for _, feature in enumerate(params):\n\n noise = np.random.uniform(low=(-1) * noise_level, high=noise_level)\n params[feature] += noise\n \n if feature == \"ego_v1\":\n params[feature] = np.clip(a=params[feature], a_min=self.min_point[0], a_max=self.max_point[0])\n elif feature == \"front_v1\":\n params[feature] = np.clip(a=params[feature], a_min=self.min_point[1], a_max=self.max_point[1])\n elif feature == \"front_v2\":\n params[feature] = np.clip(a=params[feature], a_min=self.min_point[2], a_max=self.max_point[2])\n elif feature == \"delta_dist\":\n params[feature] = np.clip(a=params[feature], a_min=self.min_point[3], a_max=self.max_point[3])\n else:\n raise ValueError(\"[ERROR]-> Invalid Sample Feature Name\")\n \n return params\n\n # run optimizer code with result\n def update(self, config: dict, result: dict) -> None:\n\n if self.update_ongoing is False and self.Fj_counter < self.J:\n self.result_buffer.append([config, result])\n \n if len(self.result_buffer) >= self.Ne:\n self.update_ongoing = True\n \n sampling_buffer, new_trials, results = [], [], []\n\n for trial_config, trial_result in self.result_buffer:\n results.append(trial_result[self.metric])\n sorted_results_indices = np.argsort(results)\n \n for k in range(self.K):\n sampling_buffer.append(self.result_buffer[sorted_results_indices[k]][0])\n \n while sampling_buffer == []:\n if self.Fj_counter <= 0:\n self.Fj_counter = self.J\n return \n \n self.Fj_counter -= 1\n \n for trial_config, trial_result in self.result_buffer:\n if trial_result[self.metric] <= self.Lj[self.Fj_counter]:\n sampling_buffer.append(trial_config)\n \n # check and do not include impossible configurations\n for _ in range(self.Ne):\n # loop until 'possible to avoid collision' configuration is found\n for _ in range(self.algorithm_config[\"check_impossible_count\"]):\n sampled_config = np.random.choice(a=sampling_buffer)\n \n parameters = self.apply_noise(\n params=copy.deepcopy(sampled_config),\n noise_level=self.noise_level\n )\n\n # TODO: initial ego vehicle acceleration could be added to parameter space\n ego_acceleration = 0.0\n front_acceleration = np.clip(self.algorithm_config[\"desired_comfort_accel\"] * \\\n (1 - np.power(max(parameters[\"front_v1\"], 0) / parameters[\"front_v2\"], self.algorithm_config[\"velocity_exponent\"])), \\\n self.algorithm_config[\"front_accel_range\"][0], self.algorithm_config[\"front_accel_range\"][1])\n \n if validation_utils.is_impossible_2_stop(\n initial_distance = parameters[\"delta_dist\"],\n ego_velocity = parameters[\"ego_v1\"],\n front_velocity = parameters[\"front_v1\"],\n ego_acceleration = ego_acceleration, \n front_acceleration = front_acceleration\n ):\n continue\n else:\n break\n \n new_trials.append(parameters)\n \n self.trial_counter = 0\n self.result_buffer = []\n self.current_trials = copy.deepcopy(new_trials)\n\n self.Fj_counter += 1\n self.Fj.append(copy.deepcopy(self.current_trials))\n\n self.update_ongoing = False\n\n\nif __name__ == \"__main__\":\n\n # get arguments\n args = validation_utils.argument_parser()\n args.algo_config_file = \"ams_search.yaml\"\n\n # config for specified algorithm\n algorithm_config = validation_utils.get_algorithm_config(args=args)\n print(\"\\n[CONFIG]-> Algorithm Configuration:\\t\", pretty_print(algorithm_config))\n\n # initialize main agent class\n agent = MainAgent(\n algorithm_config = algorithm_config\n )\n print(\"\\n[INFO]-> Agent Class:\\t\", agent)\n\n # construct adaptive sequential monte carlo optimizer class\n optimizer = AdapSeqMCOptimizer(\n algorithm_config = algorithm_config\n )\n print(\"\\n[INFO]-> Optimizer:\\t\", optimizer)\n\n # custom searcher class for keeping track of a metric to optimize\n searcher = SearchAgent(\n optimizer = optimizer,\n metric = algorithm_config[\"metric\"],\n mode = algorithm_config[\"mode\"]\n )\n print(\"\\n[INFO]-> Searcher:\\t\", searcher)\n\n # tuning configurations class -> new from ray v2.0.0\n tune_config = TuneConfig(\n search_alg = searcher,\n num_samples = algorithm_config[\"num_samples\"]\n )\n print(\"\\n[INFO]-> TuneConfig:\\t\", tune_config)\n\n # set project directory for all ray workers\n runtime_env = {\n \"working_dir\" : parent_directory,\n # exclude error and output files (relative path from \"parent_directory\")\n \"excludes\" : [\"*.err\", \"*.out\", \"*.mp4\", \"*.gif\", \"*.png\", \"*.pdf\", \"*.pptx\"]\n }\n ray.init(\n runtime_env = runtime_env\n )\n\n # execute validation search algorithm and save results to csv\n validation_utils.run_search_algorithm(\n agent = agent,\n validation_config = algorithm_config,\n tune_config = tune_config,\n param_space = None\n )","repo_name":"resuldagdanov/self-improving-RL","sub_path":"experiments/algorithms/ams_search.py","file_name":"ams_search.py","file_ext":"py","file_size_in_byte":11305,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"46"} +{"seq_id":"71385312141","text":"import abc\nimport copy\nimport inspect\nfrom typing import Any, Generic, Type, TypeVar\n\nimport pyspark.sql.functions as F\nimport pyspark.sql.types as T\nimport quinn\nfrom py4j import java_gateway\nfrom pyspark.ml import Transformer\nfrom pyspark.sql import DataFrame\nfrom typing_extensions import Self\n\nfrom funkea.core import data\nfrom funkea.core import method as method_\nfrom funkea.core import params as params_\nfrom funkea.core import pipeline as pipeline_\nfrom funkea.core.utils import partition\n\nPipeline = TypeVar(\"Pipeline\", bound=pipeline_.DataPipeline)\nMethod = TypeVar(\"Method\", bound=method_.EnrichmentMethod)\nParams = TypeVar(\"Params\", bound=params_.Params)\n\nComponent = TypeVar(\"Component\", bound=Transformer | data.DataComponent)\n\n\ndef _has_component(workflow: \"Workflow\", component: Type[Component]) -> bool:\n try:\n # JAX has a lot of issues being installed on various architectures, so we only import it\n # here if we actually need it.\n # Moreover, this feature is not _super_ important, so we can just skip it if JAX is not\n # installed.\n import jax\n import jax.tree_util\n except (ImportError, ModuleNotFoundError):\n return False\n\n def _f(obj: Any) -> bool | dict[str, bool]:\n if isinstance(obj, component):\n return True\n # `py4j.java_gateway` objects can have any attributes on them, even if they do not actually\n # exist. This can lead to infinite recursions.\n if not hasattr(obj, \"__dict__\") or inspect.getmodule(obj) is java_gateway:\n return False\n return jax.tree_map(_f, vars(obj))\n\n return any(jax.tree_util.tree_flatten(jax.tree_map(_f, vars(workflow)))[0])\n\n\nclass Workflow(\n Transformer,\n Generic[Pipeline, Method, Params],\n partition.PartitionByMixin,\n metaclass=abc.ABCMeta,\n):\n \"\"\"Base class for workflows.\n\n Args:\n pipeline: The data pipeline, which prepares the sumstats and annotation data for enrichment.\n method: The enrichment method, which uses the annotated loci to calculate enrichment for the\n :math:`K` partitions and compute the corresponding :math:`p`-value.\n \"\"\"\n\n pipeline: Pipeline\n method: Method\n\n _expected_input_schema: T.StructType = data.Sumstats.spark_schema()\n\n def __init__(self, pipeline: Pipeline, method: Method):\n super(Workflow, self).__init__()\n self.pipeline = pipeline\n self.method = method\n self._expected_input_schema = self._get_expected_schema()\n\n def _get_expected_schema(self) -> T.StructType:\n # in the future we should delegate the required schema to each component and then just\n # collect these here.\n schema = copy.deepcopy(self._expected_input_schema)\n if _has_component(self, data.LDComponent):\n # if we are using LD components in the workflow, we should make sure to have an ancestry\n # column\n schema = schema.add(T.StructField(data.ANCESTRY_COL, T.StringType()))\n return schema\n\n def _init_workflow(self, dataset: DataFrame) -> DataFrame:\n for column in self.partition_cols:\n if column not in dataset.columns:\n # create dummy partitions for missing partition columns\n # this allows for generality, for example, when we only pass a single study\n # we add an artificial column for study ID, and then the same Spark code can work\n # for one or more studies\n # equally, we can then partition by any arbitrary set of columns\n dataset = dataset.withColumn(column, F.lit(\"dummy\"))\n return dataset\n\n def _transform(self, dataset: DataFrame) -> DataFrame:\n if len(self.partition_cols) == 0:\n raise ValueError(\n \"Do not set empty partitioning, as this will break the workflow. Any missing \"\n \"partitioning columns will be added as dummies automatically. Hence, if no \"\n \"partitioning is necessary (i.e. only one study being run), it is recommended to \"\n \"just set a single (arbitrary) partitioning column (the default).\"\n )\n quinn.validate_schema(dataset, self._expected_input_schema, ignore_nullable=True)\n\n # missing partition columns are added with `dummy` values, such that all partitioning parts\n # still pass\n # however, we need to make sure to remove these after completing the workflow\n missing_partition_cols: set[str] = set(self.partition_cols).difference(dataset.columns)\n return (\n self._init_workflow(dataset)\n .transform(self.pipeline.transform)\n .transform(self.method.transform)\n .sort(*self.partition_cols, \"p_value\")\n .drop(*missing_partition_cols)\n )\n\n @classmethod\n @abc.abstractmethod\n def default(\n cls,\n annotation: data.AnnotationComponent | None = None,\n params: Params = params_.Params(), # type: ignore[assignment]\n ) -> Self:\n pass\n","repo_name":"BenevolentAI/funkea","sub_path":"funkea/core/workflow.py","file_name":"workflow.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"44028127000","text":"class Student(object):\n def __init__(self, name, score):\n self.name = name\n self.score = score\n\n def print_score(self):\n print(\"{}: {}\".format(self.name, self.score))\n\n def get_grade(self):\n if self.score >= 90:\n return 'A'\n elif self.score >= 60:\n return 'B'\n else:\n return 'C'\n\n\nrandy = Student('Randy Li', 90)\nlisa = Student('Lisa Simpson', 87)\nrandy.print_score()\nlisa.print_score()\nprint(randy.name, randy.get_grade())\nprint(lisa.name, lisa.get_grade())","repo_name":"Jeetendranani/yaamnotes","sub_path":"python/class_and_instance.py","file_name":"class_and_instance.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"70373208781","text":"import sys\n\nimport pytest\nfrom setuptools.dist import Distribution\n\nimport jupyter_packaging.setupbase as pkg\nfrom jupyter_packaging.setupbase import __file__ as path\n\nfrom .utils import run_command\n\n\ndef test_get_version():\n version = pkg.get_version(path)\n assert version == pkg.__version__\n\n\ndef test_combine_commands():\n class MockCommand(pkg.BaseCommand):\n called = 0\n\n def run(self):\n MockCommand.called += 1\n\n combined_klass = pkg.combine_commands(MockCommand, MockCommand)\n combined = combined_klass(Distribution())\n combined.initialize_options()\n combined.finalize_options()\n combined.run()\n assert MockCommand.called == 2\n\n\ndef test_run():\n assert pkg.run(sys.executable + \" --version\") == 0\n\n with pytest.raises(ValueError):\n pkg.run(\"foobarbaz\")\n\n\ndef test_ensure_existing_targets(destination_dir):\n local_targets = [\"file1.rtf\", \"sub/subfile1.rtf\"]\n targets = [str(destination_dir.join(t)) for t in local_targets]\n cmd = pkg.ensure_targets(targets)\n run_command(cmd)\n\n\ndef test_ensure_missing_targets(source_dir):\n local_targets = [\"file1.rtf\", \"sub/subfile1.rtf\"]\n targets = [str(source_dir.join(t)) for t in local_targets]\n cmd = pkg.ensure_targets(targets)\n with pytest.raises(ValueError):\n run_command(cmd)\n\n\ndef test_ensure_with_skip_npm(source_dir, mocker):\n mocker.patch(\"jupyter_packaging.setupbase.skip_npm\", True)\n local_targets = [\"file1.rtf\", \"sub/subfile1.rtf\"]\n targets = [str(source_dir.join(t)) for t in local_targets]\n cmd = pkg.ensure_targets(targets)\n run_command(cmd)\n\n\nclass TestCommand(pkg.BaseCommand):\n def run(self):\n raise RuntimeError()\n\n\n# Prevent pytest from trying to collect TestCommand as a test:\nTestCommand.__test__ = False\n\n\ndef test_skip_existing(destination_dir):\n local_targets = [\"file1.rtf\", \"sub/subfile1.rtf\"]\n targets = [str(destination_dir.join(t)) for t in local_targets]\n cmd = pkg.skip_if_exists(targets, TestCommand)\n run_command(cmd)\n\n\ndef test_no_skip_missing(source_dir):\n local_targets = [\"file1.rtf\", \"sub/subfile1.rtf\"]\n targets = [str(source_dir.join(t)) for t in local_targets]\n cmd = pkg.skip_if_exists(targets, TestCommand)\n with pytest.raises(RuntimeError):\n run_command(cmd)\n","repo_name":"jupyter/jupyter-packaging","sub_path":"tests/test_utility_functions.py","file_name":"test_utility_functions.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","stars":62,"dataset":"github-code","pt":"46"} +{"seq_id":"9242109468","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import Warning\n\n# Ahmed Salama Code Start ---->\nPARTNER_TYPE = [('customer_rank', 'Customer'), ('supplier_rank', 'Vendor'),\n ('employee', 'Employee'), ('no_partner', 'No Partner')]\nRECIPT_TYPE = [('in', 'IN'), ('out', 'Out')]\n\n\nclass MoneyReceipt(models.Model):\n _name = 'money.receipt'\n _description = \"Accounting Money Receipts In/Out\"\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _check_company_auto = True\n\n name = fields.Char(\"Money Receipt\")\n active = fields.Boolean(default=True)\n receipt_type = fields.Selection(RECIPT_TYPE, \"Receipt Type\", required=True, tracking=True)\n journal_id = fields.Many2one('account.journal', \"Journal\", check_company=True, readonly=True, required=True,\n states={'draft': [('readonly', False)]}, tracking=True, domain=[('type', '=', 'cash')])\n account_id = fields.Many2one(related='journal_id.default_account_id', readonly=True)\n company_id = fields.Many2one('res.company', readonly=True, default=lambda self: self.env.company)\n currency_id = fields.Many2one('res.currency', 'Currency', readonly=True, states={'draft': [('readonly', False)]},\n help='Utility field to express amount currency', required=True, tracking=True,\n default=lambda self: self.env.company.currency_id)\n item_ids = fields.One2many('money.receipt.item', 'money_receipt_id', \"Items\", readonly=True,\n states={'draft': [('readonly', False)]})\n amount_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_compute_amount')\n state = fields.Selection(selection=[\n ('draft', 'Draft'),\n ('posted', 'Posted'),\n ('cancel', 'Cancelled'),\n ], string='Status', required=True, readonly=True, copy=False, tracking=True, default='draft')\n date = fields.Date(string='Date', required=True, index=True, readonly=True, tracking=True,\n states={'draft': [('readonly', False)]}, copy=False, default=fields.Date.context_today)\n move_id = fields.Many2one('account.move', \"Journal Entry\")\n label = fields.Char('Label', readonly=True, states={'draft': [('readonly', False)]})\n\n # --------------------------------------------------\n # CRUD\n # --------------------------------------------------\n\n @api.model\n def create(self, vals):\n \"\"\"\n Add Seq for Request\n :param vals: create vals\n :return: SUPER\n \"\"\"\n vals['name'] = \"MRECP/%s/%s\" % (dict(self._fields['receipt_type'].selection).get(vals.get('receipt_type'))\n , self.env['ir.sequence'].sudo().next_by_code('money.receipt.code'))\n attend = super(MoneyReceipt, self).create(vals)\n return attend\n\n # --------------------------------------------------\n # actions\n # --------------------------------------------------\n\n def action_post(self):\n move_obj = self.env['account.move']\n for money_receipt in self:\n move_vals = self._prepare_move_values()\n move = move_obj.sudo().create(move_vals)\n if move:\n move.post()\n money_receipt.move_id = move.id\n money_receipt.state = 'posted'\n else:\n raise Warning(_(\"Something went wrong while creating move!!!\"))\n\n def action_cancel(self):\n \"\"\"\n - Cancel Request\n \"\"\"\n for rec in self:\n rec.state = 'cancel'\n\n def action_draft(self):\n \"\"\"\n - reset state to draft\n \"\"\"\n for rec in self:\n rec.state = 'draft'\n\n # --------------------------------------------------\n # main methods\n # --------------------------------------------------\n\n def _prepare_move_values(self):\n \"\"\"\n This function prepares move values related to an expense\n \"\"\"\n self.ensure_one()\n\n total_amount = sum(item.amount for item in self.item_ids)\n if self.label:\n name = self.label\n else:\n name = self.name\n move_line_src = {\n 'name': name,\n 'quantity': 1,\n 'debit': total_amount if self.receipt_type == 'in' else 0,\n 'credit': total_amount if self.receipt_type == 'out' else 0,\n 'account_id': self.account_id.id,\n 'money_receipt_id': self.id,\n 'currency_id': self.currency_id.id,\n }\n move_lines = self.item_ids._get_account_move_line_values()\n move_lines.append((0, 0, move_line_src))\n print(\"MOVE VALS:: \", move_lines)\n move_values = {\n 'journal_id': self.journal_id.id,\n 'company_id': self.company_id.id,\n 'date': self.date,\n 'ref': self.label,\n 'money_receipt_id': self.id,\n 'name': '/',\n 'line_ids': move_lines\n }\n return move_values\n\n @api.onchange('item_ids')\n @api.depends('item_ids.amount')\n def _compute_amount(self):\n for receipt in self:\n receipt.amount_total = sum(item.amount for item in receipt.item_ids)\n\n\nclass MoneyReceiptItem(models.Model):\n _name = 'money.receipt.type'\n _description = \"Accounting Money Receipts Item In/Out\"\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _check_company_auto = True\n\n @api.onchange('receipt_type', 'account_optional')\n def account_domain(self):\n account_domain = []\n if self.account_optional:\n if self.receipt_type == 'out':\n account_domain = []\n elif self.receipt_type == 'in':\n account_domain = []\n # return {'domain': {'account_id': account_domain}}\n return account_domain\n\n name = fields.Char(\"Type\", required=True)\n active = fields.Boolean(default=True)\n receipt_type = fields.Selection(RECIPT_TYPE, \"Receipt Type\", required=True, tracking=True)\n company_id = fields.Many2one('res.company', readonly=True, default=lambda self: self.env.company)\n account_optional = fields.Boolean(\"Account Optional\",\n help=\"If selected account field will be optional, to be selected from receipt itself\")\n account_id = fields.Many2one('account.account', string='Account', index=True, ondelete=\"cascade\",\n tracking=True, check_company=True, domain=account_domain)\n partner_type = fields.Selection(PARTNER_TYPE, \"Partner Type\", required=True, default='no_partner')\n\n\nclass MoneyReceiptLine(models.Model):\n _name = 'money.receipt.item'\n _description = \"Accounting Money Receipts Line In/Out\"\n\n @api.onchange('money_receipt_type_id')\n @api.depends('money_receipt_type_id.partner_type')\n def partner_domain(self):\n partner_domain = []\n type_id = self.money_receipt_type_id\n if type_id and type_id.partner_type:\n if type_id.partner_type in ['customer_rank', 'supplier_rank']:\n partner_domain = [(type_id.partner_type, '!=', 0)]\n elif type_id.partner_type == 'employee':\n employee_partners = self.env['res.partner'].search([('employee_id', '!=', False)])\n partner_domain = [('id', 'in', list(set(employee_partners.ids)))]\n return {'domain': {'partner_id': partner_domain}}\n # return partner_domain\n\n @api.onchange('money_receipt_type_id')\n @api.depends('money_receipt_type_id.partner_type')\n def account_domain(self):\n account_domain = []\n type_id = self.money_receipt_type_id\n if type_id and type_id.account_optional:\n if type_id.receipt_type == 'out':\n account_domain = [('user_type_id', '=', 15)]\n elif type_id.receipt_type == 'in':\n account_domain = [('user_type_id', 'in', [3, 14])]\n return {'domain': {'account_id': account_domain}}\n # return account_domain\n\n @api.onchange('money_receipt_type_id')\n def _onchange_money_receipt_type_id(self):\n for item in self:\n account_id = False\n if item.money_receipt_type_id and item.money_receipt_type_id.account_id:\n account_id = item.money_receipt_type_id.account_id.id\n item.account_id = account_id\n item.label = item.money_receipt_id.label\n\n money_receipt_id = fields.Many2one('money.receipt', \"Money Receipt\")\n receipt_type = fields.Selection(related='money_receipt_id.receipt_type')\n money_receipt_type_id = fields.Many2one('money.receipt.type', \"Item\", required=True, tracking=True)\n partner_type = fields.Selection(related='money_receipt_type_id.partner_type')\n account_optional = fields.Boolean(related='money_receipt_type_id.account_optional')\n account_id = fields.Many2one('account.account', string='Account', index=True, ondelete=\"cascade\",\n required=True, tracking=True, check_company=True, )\n company_id = fields.Many2one('res.company', readonly=True, default=lambda self: self.env.company)\n partner_id = fields.Many2one('res.partner', \"Partner\")\n currency_id = fields.Many2one(related='money_receipt_id.currency_id', string='Currency',\n readonly=True, store=True,\n help='Utility field to express amount currency')\n amount = fields.Monetary(string='Amount', default=0.0, currency_field='currency_id')\n label = fields.Char('Label')\n\n def _get_account_move_line_values(self):\n move_line_values = []\n for item in self:\n move_line_name = \"\"\n if item.label:\n move_line_name = item.label\n else:\n if item.partner_id:\n move_line_name += item.partner_id.name + ': '\n if item.money_receipt_id:\n move_line_name += item.money_receipt_id.name\n account_dst = item.account_id\n account_date = item.money_receipt_id.date or fields.Date.context_today()\n\n # destination move line\n move_line_dst = (0, 0, {\n 'name': move_line_name,\n 'debit': item.amount if item.receipt_type == 'out' else 0,\n 'credit': item.amount if item.receipt_type == 'in' else 0,\n 'account_id': account_dst.id,\n 'date_maturity': account_date,\n 'currency_id': item.currency_id.id,\n 'money_receipt_id': item.money_receipt_id.id,\n 'money_receipt_item_id': item.id,\n 'partner_id': item.partner_id.id,\n })\n move_line_values.append(move_line_dst)\n\n return move_line_values\n\n# Ahmed Salama Code End.\n","repo_name":"g6982/Sahil-Dublicate","sub_path":"telenoc_accounting_money_receipt/models/money_receipt.py","file_name":"money_receipt.py","file_ext":"py","file_size_in_byte":10819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"16361143439","text":"from myproject import app,db\nfrom flask import render_template, redirect, request, url_for, flash,abort\nfrom flask_login import login_user,login_required,logout_user\nfrom myproject.models import User, Stock\nfrom myproject.forms import LoginForm, RegistrationForm, StockForm, EditStockForm\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom wtforms import ValidationError\nfrom flask_table import Table, Col, LinkCol\nfrom myproject.tables import Results, ResultsEdit, ResultsDelete\n\n@app.route('/')\ndef home():\n return render_template('home.html')\n\n\n@app.route('/welcome')\n@login_required\ndef welcome_user():\n return render_template('welcome_user.html')\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('You logged out!')\n return redirect(url_for('home'))\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\n form = LoginForm()\n error = None\n if form.validate_on_submit():\n print('validate_on_submit ')\n # Grab the user from our User Models table\n user = User.query.filter_by(email=form.email.data).first()\n print('User ' )\n # Check that the user was supplied and the password is right\n # The verify_password method comes from the User object\n # https://stackoverflow.com/questions/2209755/python-operation-vs-is-not\n if user is None:\n #raise ValidationError('Your email is not registered')\n flash('Your email is not registered')\n\n if user is not None and user.check_password(form.password.data) :\n #Log in the user\n\n login_user(user)\n\n flash('Logged in successfully.')\n\n # If a user was trying to visit a page that requires a login\n # flask saves that URL as 'next'.\n next = request.args.get('next')\n\n # So let's now check if that next exists, otherwise we'll go to\n # the welcome page.\n if next == None or not next[0]=='/':\n next = url_for('welcome_user')\n\n return redirect(next)\n else :\n # password mismatch\n flash('Your email id and or password is not matching.')\n error = 'Invalid credentials'\n\n return render_template('login.html', form=form, error=error)\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n error_state = False\n form = RegistrationForm()\n\n if form.validate_on_submit():\n user = User(email=form.email.data,\n username=form.username.data,\n password=form.password.data)\n\n\n db.session.add(user)\n db.session.commit()\n flash('Thanks for registering! Now you can login!')\n return redirect(url_for('login'))\n return render_template('register.html', form=form)\n\n\n@app.route('/stocks')\n@login_required\ndef stocks():\n #form = StockForm()\n\n '''form.validate_on_submit():\n return redirect(url_for('stocks'))\n '''\n stocks = Stock.query.all()\n table = Results(stocks)\n table.border = True\n\n\n #return render_template('stocks.html', form=form)\n return render_template('stocks.html', table=table)\n\n\n@app.route('/add',methods=['GET', 'POST'])\n@login_required\ndef add():\n form = StockForm()\n if form.validate_on_submit():\n stock = Stock(name=form.name.data,\n code=form.code.data,\n fair_price=form.fair_price.data)\n\n\n db.session.add(stock)\n db.session.commit()\n flash('Stock \"' + stock.name + '\" is added!')\n return redirect(url_for('stocks'))\n return render_template('add.html', form=form)\n\n@app.route('/edit',methods=['GET', 'POST'])\n@login_required\ndef edit_stock():\n\n stocks = Stock.query.all()\n table = ResultsEdit(stocks)\n table.border = True\n\n\n return render_template('edit.html', table=table)\n\n\n@app.route('/item/', methods=['GET', 'POST'])\n@login_required\ndef edit(id):\n\n stock = Stock.query.filter_by(id=id).first()\n if stock:\n #form = EditStockForm(formdata=request.form, obj=stock)\n form = EditStockForm(formdata=request.form)\n if request.method == 'POST' and form.validate():\n # save edits\n save_changes(stock, form,new=False)\n flash('Stock updated successfully!')\n return redirect(url_for('stocks'))\n return render_template('edit_stock.html', form=form)\n else:\n return 'Error loading #{id}'.format(id=id)\n\n\ndef save_changes(stock_prev, form, new=False):\n \"\"\"\n Save the changes to the database\n \"\"\"\n\n\n onldname = stock_prev.name\n oldstock = Stock.query.filter_by(name=onldname).first()\n oldstock.name = form.name.data\n oldstock.code = form.code.data\n oldstock.fair_price = form.fair_price.data\n db.session.commit()\n\n\n@app.route('/delete',methods=['GET', 'POST'])\n@login_required\ndef delete_stock():\n\n stocks = Stock.query.all()\n table = ResultsDelete(stocks)\n table.border = True\n\n return render_template('delete.html', table=table)\n\n\n@app.route('/item/', methods=['GET', 'POST'])\n@login_required\ndef delete(name):\n\n stock = Stock.query.filter_by(name=name).first()\n\n if stock:\n db.session.delete(stock)\n db.session.commit()\n flash('Stock \"' + name + '\" is deleted!')\n return redirect(url_for('stocks'))\n\n else:\n return 'Error loading #{id}'.format(id=id)\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"kpgdsc/eq_tracker","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"34427473809","text":"from __future__ import print_function\r\nimport datetime\r\nimport pickle\r\nimport os.path\r\nfrom googleapiclient.discovery import build\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\n\r\n# If modifying these scopes, delete the file token.pickle.\r\n# SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] # read.only\r\nSCOPES = ['https://www.googleapis.com/auth/calendar']\r\n\r\nclass EventBuilder:\r\n\r\n def __init__(self):\r\n self.output = {}\r\n self.timezone = \"Asia/Singapore\"\r\n\r\n def add_event(self, subject_code, subject_name):\r\n self.output['summary'] = f\"{subject_code} - {subject_name}\"\r\n return self\r\n\r\n def add_location(self, location):\r\n self.output['location'] = f\"{location}\"\r\n return self\r\n\r\n def add_description(self, description):\r\n self.output['description'] = f\"{description}\"\r\n return self\r\n\r\n def add_startTime(self, date, start_time, timezone=\"Asia/Singapore\"):\r\n self.output['start'] = {'dateTime':f\"{date}T{start_time}\",\r\n 'timeZone':timezone}\r\n return self\r\n\r\n def add_endTime(self, date, end_time, timezone=\"Asia/Singapore\"):\r\n self.output['end'] = {'dateTime':f\"{date}T{end_time}\",\r\n 'timeZone':timezone}\r\n return self\r\n\r\n def build(self):\r\n return self.output\r\n \r\nclass Gcal:\r\n\r\n def __init__(self, calendar_id='primary'):\r\n self.creds_file = 'credentials.json'\r\n self.creds = None\r\n self.calendar_id = calendar_id\r\n self._set_creds()\r\n self.service = build('calendar', 'v3', credentials=self.creds)\r\n \r\n def _set_creds(self):\r\n creds = None\r\n if os.path.exists('token.pickle'):\r\n with open('token.pickle', 'rb') as token:\r\n self.creds = pickle.load(token)\r\n # If there are no (valid) credentials available, let the user log in.\r\n if not self.creds or not self.creds.valid:\r\n if self.creds and self.creds.expired and self.creds.refresh_token:\r\n self.creds.refresh(Request())\r\n else:\r\n flow = InstalledAppFlow.from_client_secrets_file(\r\n self.creds_file, SCOPES)\r\n self.creds = flow.run_local_server()\r\n # Save the credentials for the next run\r\n with open('token.pickle', 'wb') as token:\r\n pickle.dump(self.creds, token)\r\n\r\n def _create_event(self, event, calendar_id=\"\"):\r\n if calendar_id == \"\":\r\n calendar_id = self.calendar_id\r\n event = self.service.events().insert(calendarId=calendar_id, body=event).execute()\r\n print ('Event created: %s' % (event.get('htmlLink')))\r\n\r\n def create_events(self,event_list):\r\n for event in event_list:\r\n self._create_event(event)\r\n print(\"All Events Created\")\r\n\r\n def view_events(self,calendar_id=\"\"):\r\n if calendar_id == \"\":\r\n calendar_id = self.calendar_id\r\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\r\n print('Getting the upcoming 10 events')\r\n events_result = self.service.events().list(calendarId=calendar_id, timeMin=now,\r\n maxResults=10, singleEvents=True,\r\n orderBy='startTime').execute()\r\n events = events_result.get('items', [])\r\n\r\n if not events:\r\n print('No upcoming events found.')\r\n for event in events:\r\n start = event['start'].get('dateTime', event['start'].get('date'))\r\n print(start, event['summary'])\r\n \r\ndef main():\r\n gcal = Gcal()\r\n gcal.view_events('primary')\r\n event = (EventBuilder()\r\n .add_event(\"50.001\",\"Introduction to Information Systems\")\r\n .add_location(\"CC13\")\r\n .add_startTime(\"2019-04-23\",\"12:00:00\")\r\n .add_endTime(\"2019-04-23\",\"15:00:00\")\r\n .build())\r\n events = []\r\n events.append(event)\r\n gcal.create_events(events)\r\n \r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"jenyangg/sutd-scheduler","sub_path":"schedule/gcal_quickstart.py","file_name":"gcal_quickstart.py","file_ext":"py","file_size_in_byte":4131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"4506477380","text":"tamanho = int(input())\nwhile tamanho != 0:\n for i in range(0, tamanho):\n for j in range(0, tamanho):\n menorDistanciaHorizontal = 1\n menorDistanciaVertical = 1\n menorDistancia = 1\n\n if i < (tamanho -i -1):\n menorDistanciaHorizontal = i\n else:\n menorDistanciaHorizontal = tamanho-i-1\n\n if j < (tamanho -j -1):\n menorDistanciaVertical = j\n else:\n menorDistanciaVertical = tamanho-j-1\n\n if menorDistanciaVertical < menorDistanciaHorizontal:\n menorDistancia = menorDistanciaVertical\n else:\n menorDistancia = menorDistanciaHorizontal\n\n if j != tamanho-1:\n print(f'{menorDistancia+1:3} ', end='')\n else:\n print(f'{menorDistancia+1:3}', end='')\n print()\n print()\n \n tamanho = int(input())\n","repo_name":"FelipeFerraz4/Beecrowd","sub_path":"Problemas/Bee 1435 Matriz Quadrada I.py","file_name":"Bee 1435 Matriz Quadrada I.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"70933762380","text":"import logging\n\nfrom django import forms\nfrom django.views.generic.base import RedirectView\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.list import ListView\n\nfrom explorer.models import Collection\nfrom explorer.services import collections, processing\n\n# NOTE: logging could be configured better in django settings (adjust levels and format)\nlogger = logging.getLogger(__name__)\n\n\n# NOTE: this could be also paginated but there is no such requirement for now\nclass CollectionListView(ListView):\n model = Collection\n\n\nclass CollectionDetailView(DetailView):\n model = Collection\n\n PAGE_SIZE = 10\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n limit = int(self.request.GET.get(\"limit\", self.PAGE_SIZE))\n collection_data = collections.load_collection_data(self.object, limit=limit)\n\n context[\"people\"] = collection_data\n context[\"next_limit\"] = limit + self.PAGE_SIZE\n\n return context\n\n\nclass CollectionValueCountView(DetailView):\n model = Collection\n template_name_suffix = \"_value_count\"\n\n def get_form_class(self, table):\n header = table[0]\n choices = [(field, field) for field in header]\n\n class ValueCountForm(forms.Form):\n fields = forms.MultipleChoiceField(\n choices=choices, widget=forms.CheckboxSelectMultiple(), required=False\n )\n\n return ValueCountForm\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n table = collections.load_table(self.object)\n form = self.get_form_class(table)(self.request.GET)\n\n selected_fields = []\n if form.is_valid():\n selected_fields = form.cleaned_data[\"fields\"]\n\n try:\n aggregation = processing.count_selected_fields_combinations_for_table(table, selected_fields)\n except ValueError:\n aggregation = []\n\n context[\"form\"] = form\n context[\"fields\"] = selected_fields\n context[\"aggregation\"] = aggregation\n return context\n\n\nclass CollectionFetchView(RedirectView):\n permanent = False\n pattern_name = \"collection-list\"\n\n def get(self, request, *args, **kwargs):\n logger.info(\"Trigger new fetch request\")\n collection = collections.fetch_and_save_new_collection()\n logger.info(\"Fetched new collection %s to %s\", collection, collection.file.path)\n return super().get(request, *args, **kwargs)\n","repo_name":"cookieranger/starwars_explorer","sub_path":"explorer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"9329050263","text":"##########################################################################\n# File Name: 1218.py\n# Author: Charliegean\n# mail: wht905@gmail.com\n# Created Time: Fri 05 Nov 2021 12:18:46 PM CST\n#########################################################################\n#!/usr/bin/env python3\n# coding=utf-8\nclass Solution:\n def longestSubsequence(self, arr,difference):\n res=0\n dic={}\n for i in range(0,len(arr)):\n if arr[i] in dic:\n dic[arr[i]].append(i)\n else:\n dic[arr[i]]=[i]\n print(dic)\n for i in range(0,len(arr)):\n tempL=1\n tempi=i \n flag=False\n while True:\n if (arr[tempi] + difference) in dic:\n for j in dic[arr[tempi]+difference]:\n print(j)\n if j>tempi:\n tempi=j\n tempL+=1\n flag=True \n break\n # if tempL==1 or tempi != i:\n # break \n if flag:\n break \n else:\n break\n print(\"===\",tempL,res)\n if res None:\n \"\"\"\n\n \"\"\"\n cls.logger = module_logger.getChild(cls.__class__.__name__)\n cls._buffer: List[AbstractMovie] = []\n cls._cursor: int = -1\n\n @classmethod\n def append(cls, movie: AbstractMovie) -> None:\n \"\"\"\n\n :param movie:\n :return:\n \"\"\"\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n cls.logger.enter(f'Adding movie: {movie.get_title()} '\n f'len: '\n f'{len(cls._buffer)} cursor: {cls._cursor}')\n duplicate = False\n a_movie: AbstractMovie\n for a_movie in cls._buffer:\n if ((a_movie.get_title() == movie.get_title())\n and (a_movie.get_year() == movie.get_year())):\n duplicate = True\n break\n\n if duplicate:\n # Most likely a duplicate is sent by back-end when it is starving.\n # We fetch one trailer ahead so normally we can afford to wait a\n # bit for the back-end to recover. But, if the user is choosing to\n # play next trailer, then we need to display something instead of\n # a black screen. Starving is used to indicate that the back-end\n # has no trailer to play yet.\n\n if cls._previous_trailer_was_duplicate:\n cls._previous_trailer_was_duplicate = False\n\n # Starving is when two duplicates in a row are returned\n # Waiting for two duplicates just seemed like a good idea\n # at the time. It can be handled any way that seems appropriate.\n\n # Starving will change get_next_trailer's behavior on next\n # request.\n\n # cls._starving = True\n else:\n cls._previous_trailer_was_duplicate = True\n cls._starving = False\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n cls.logger.debug_extra_verbose(f'Not adding duplicate movie to history: '\n f'{movie.get_title()}')\n cls.dump_history()\n return\n else:\n # Normal trailer, no duplicate\n\n cls._starving = False\n cls._previous_trailer_was_duplicate = False\n\n cls._buffer.append(movie)\n\n # If buffer is over-full, correct\n if len(cls._buffer) > HistoryList.MAX_HISTORY:\n # Delete oldest entry\n del cls._buffer[0]\n # Adjust cursor index\n # Note that even if other events have altered cursor before we\n # have chance to adjust, it will still point to whatever trailer\n # was or is being played. In the worst case, where we somehow\n # managed to back up to play MAX_HISTORY times before playing the next\n # trailer, the cursor will go negative, but get_next_trailer accounts\n # for this and will set it to 0.\n\n cls._cursor -= 1\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n cls.dump_history()\n\n @classmethod\n def dump_history(cls) -> None:\n if cls.logger.isEnabledFor(LazyLogger.DEBUG):\n i: int = 0\n for a_movie in cls._buffer:\n cls.logger.debug_extra_verbose(f'index: {i} movie: {a_movie.get_title()}')\n i += 1\n\n cls.logger.debug_extra_verbose(f'len: {len(cls._buffer)} '\n f'cursor: {cls._cursor}')\n\n\n @classmethod\n def has_previous_trailer(cls) -> bool:\n has_previous = True\n if cls._cursor < 1:\n has_previous = False\n return has_previous\n\n @classmethod\n def get_previous_trailer(cls) -> AbstractMovie:\n \"\"\"\n\n :return:\n \"\"\"\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n cls.logger.enter(f'len: {len(cls._buffer)} cursor: {cls._cursor}')\n\n movie: AbstractMovie = None\n\n try:\n # cursor points to currently playing movie or -1\n cls._cursor -= 1\n if cls._cursor < 0:\n cls._cursor = -1\n raise HistoryEmpty()\n\n # Check should not be needed\n if cls._cursor > len(cls._buffer) - 1:\n cls._cursor = len(cls._buffer) - 1\n\n movie = cls._buffer[cls._cursor]\n except HistoryEmpty:\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n cls.logger.debug_extra_verbose(f'HistoryEmpty')\n reraise(*sys.exc_info())\n\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n title: str = 'None'\n if movie is not None:\n title = movie.get_title()\n cls.logger.exit(f'movie: {title} len: '\n f'{len(cls._buffer)} cursor: {cls._cursor}')\n return movie\n\n @classmethod\n def get_next_trailer(cls) -> AbstractMovie:\n \"\"\"\n Play the next trailer in the history buffer.\n\n :return: movie is next trailer to play or None if not starving and\n there is no next trailer to play.\n \"\"\"\n # When NOT starving, cursor points to currently playing\n # movie or -1. When starving, cursor is ignored.\n\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n cls.logger.enter(f'len: {len(cls._buffer)} cursor: {cls._cursor}')\n\n movie: AbstractMovie = None\n if len(cls._buffer) == 0:\n cls._cursor = -1\n # return movie # None\n\n elif (cls._cursor + 1) > len(cls._buffer) - 1:\n # return movie # None\n pass\n\n else:\n cls._cursor += 1 # Advance only when we know it will work!\n movie = cls._buffer[cls._cursor]\n\n if cls._starving:\n if movie is None and len(cls._buffer) > 0:\n movie = random.choice(cls._buffer)\n movie.set_starving(True)\n cls._starving = False\n\n if cls.logger.isEnabledFor(LazyLogger.DEBUG_EXTRA_VERBOSE):\n title: str = 'None'\n if movie is not None:\n title = movie.get_title()\n\n cls.logger.exit(f'movie: {title} len: '\n f'{len(cls._buffer)} cursor: {cls._cursor}')\n return movie\n\n @classmethod\n def remove(cls, movie: AbstractMovie) -> None:\n try:\n i = cls._buffer.index(movie)\n del cls._buffer[i]\n if cls._cursor > len(cls._buffer) - 1:\n cls._cursor = len(cls._buffer) - 1\n except Exception as e:\n pass # Does not exist in list\n\n\nHistoryList.class_init()\n","repo_name":"fbacher/script.video.randomtrailers","sub_path":"resources/lib/frontend/history_list.py","file_name":"history_list.py","file_ext":"py","file_size_in_byte":7388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"32549114057","text":"import os\nimport json\nimport asyncio\nimport logging\n\nfrom backend.cache import Cache\nfrom backend.client import Client\nfrom backend.config import Config\nfrom backend.signals import Event\nfrom backend.handler import Handler\nfrom backend.session import Session\nfrom backend.shaire import make_code\nfrom backend.asyncrun import InputIterator, run\nfrom backend.keymanagement import change_info, generate_key, checkpin, decrypt, get_id, get_pub\n\nfrom app.appmain import AppMain\nfrom app.customwidgets import KVNotifications, KVPOPupSearch, KVPOPupShair\n\n\n# The main Program object\nclass Program:\n def __init__(self, debug=False) -> None:\n self.debug = debug # are we debugging\n events = list()\n pageevent = asyncio.Event()\n async def eventloop(self): # handle events in a loop\n while True:\n if len(self.events) == 0:\n await asyncio.sleep(.01)\n continue\n await self.handle_event(*self.events.pop(0))\n # add an event\n async def event(self, etype, data=\"\"):\n self.events.append((etype, data))\n # event handler\n async def handle_event(self, etype, data=\"\"):\n e = {\n Event.LOGIN : self.login,\n Event.ADD_FRIEND : self.empty,\n Event.LOGGED_IN : self.loggedin,\n\n Event.AUTH_ERROR : self.empty,\n Event.NET_ERROR : self.net_error,\n Event.DISCONNECTED : self.empty,\n\n Event.NO_KEY : self.nokey,\n Event.UNLOCK_PIN : self.unlockpin,\n\n Event.SEARCH : self.search,\n Event.USER_PROPERTY : self.propertypage,\n Event.SHAIRE : self.shaire\n }[etype]\n return await e(etype, data)\n # empty handler\n async def empty(self, etype, data):\n return \"\"\n # handle search request\n async def search(self, etype, data):\n await self.app.shownotification(KVPOPupSearch)\n # handle shaire request\n async def shaire(self, etype, data):\n await self.app.shownotification(KVPOPupShair)\n # handle userproperty page request\n async def propertypage(self, etype, data):\n self.app.sm.transition.direction = 'right'\n self.app.sm.current = self.app.UserPropertyPage.name\n\n # handle pinumber unlock request\n async def unlockpin(self, etype, data):\n while True:\n self.app.sm.transition.direction = 'left'\n self.app.sm.current = self.app.PinPage.name\n p1 = await self.app.PinPage.get_pin(\"Enter pin.\")\n\n if checkpin(self.session.data[\"privkey\"], p1): break # we good return\n # error\n await self.app.shownotification(KVNotifications, \"Pin number incorrect\")\n await asyncio.sleep(1)\n\n # decrypt data\n self.session.privkey = self.session.data[\"privkey\"]\n self.session.pin = p1\n self.session.data[\"active\"] = True\n \n # decrypt the client key shit\n cliaccess = json.loads(decrypt(self.session.privkey, get_pub(self.session.privkey), self.session.data[\"login_token\"], p1))\n\n self.client.jid = cliaccess[\"jid\"]\n self.client.password = cliaccess[\"password\"]\n self.client.displayname = cliaccess[\"displayname\"]\n self.client.displaycolour = cliaccess[\"displaycolour\"]\n\n self.app.sm.transition.direction = 'right'\n self.app.sm.current = self.app.UsersPage.name\n\n async def nokey(self, etype, data): return # Depricated\n # get user to generate a pin number\n async def generate_pin(self):\n # transfer page\n self.app.sm.transition.direction = 'left'\n self.app.sm.current = self.app.PinPage.name\n\n # get pin\n while True:\n p1 = await self.app.PinPage.get_pin(\"Create a pin for quick access.\")\n p2 = await self.app.PinPage.get_pin(\"Confirm pin.\")\n\n if p1 == p2: break\n await self.app.shownotification(KVNotifications, \"Pin numbers do not match.\")\n return p1\n\n # logged in event\n async def loggedin(self, etype, data):\n # if we previosuly logged in\n if not self.session.data[\"active\"]:\n self.session.pin = await self.generate_pin()\n self.session.privkey = generate_key(self.client.displayname, self.client.displaycolour, self.session.pin)\n await self.handler.key_change()\n \n # create our cahe\n self.cache = Cache.from_prog(self) # might be innefficent to have one cache per session\n await self.app.UsersPage.update() # TODO: relocate\n\n # Spam user with terms and conditions\n self.app.InfoPage.halign = \"center\"\n with open(Config.TERMS, 'r') as f:\n self.app.InfoPage.data = f.read()\n\n self.app.InfoPage.data += \"\\n\\n\\n\"\n self.app.InfoPage.data += \"[b]Licence Agreement:[/b]\\n\"\n\n with open(Config.LICENCE, 'r') as f:\n self.app.InfoPage.data += f.read()\n self.app.InfoPage.data += \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\"\n\n\n if self.session.data[\"active\"]: return\n self.session.data[\"active\"] = True\n\n self.app.InfoPage.backpage = self.app.UsersPage.name\n self.app.sm.transition.direction = 'left'\n self.app.sm.current = self.app.InfoPage.name\n\n # create the rest of the shit they need\n self.session.contactstring = \"{}://add-{}-{}\".format(Config.APPNAMELINK, self.client.jid, get_id(get_pub(self.session.privkey)))\n im = make_code(self.session.contactstring, userdata_path=Config.USERDATA_DIR)\n im.save(Config.QRCODE_FILE, formats=(\"png\",))\n\n await self.session.maketoken()\n await self.session.save()\n\n # show a network error to the user\n async def net_error(self, etype, data):\n await self.app.shownotification(KVNotifications, \"Network Error: {}\".format(data))\n # go to login\n async def login(self, etype, data):\n self.ignoreevents = True\n await self.app.started.wait()\n self.app.sm.transition.direction = 'left'\n self.app.sm.current = self.app.LoginPage.name\n await asyncio.sleep(0.5)\n self.ignoreevents = False\n\n # asyncio exceptions get handled in the ether\n def handle_exception(self, loop, context): pass\n # make userdata files\n def make_files(self):\n if not os.path.isdir(Config.USERDATA_DIR): os.mkdir(Config.USERDATA_DIR)\n open(Config.SESSION_FILE, \"a\").close()\n open(Config.CACHE_FILE , \"a\").close()\n # terminal debug for testing\n async def terminal(self):\n if not self.debug: return\n async for x in InputIterator(\">>> \"):\n try:\n print(eval(x))\n except Exception as e:\n try:\n exec(x)\n except:\n print(e.__class__.__name__,\":\", e) \n # get all asyncio tasks for the app\n def asyncstart(self):\n loop = asyncio.get_event_loop()\n if self.debug: loop.set_exception_handler(self.handle_exception)\n return asyncio.gather(\n self.session.status(), # check stored sessions\n self.app.async_run(async_lib='asyncio'), # run gui\n self.client.start(), # start client manager\n self.eventloop(),\n self.terminal()\n )\n\n async def save(self): pass # Depricated\n # close the app\n async def close(self):\n logging.warning(\"Exiting program\")\n asyncio.get_event_loop().stop()\n return False\n # close asyncio eventloop so program will exit\n def on_request_close(self, arg):\n run(self.close())\n \n # start the app\n def start(self): # make all the objects\n self.make_files()\n\n self.session = Session.from_prog(self)\n self.client = Client.from_prog(self)\n self.handler = Handler.from_prog(self)\n self.app = AppMain.from_prog(self)\n\n print(\"made all objects\")\n\n asyncio.get_event_loop().run_until_complete(self.asyncstart()) # start mainloop\n\n print(\"We ran into a fatal and detremental eror FUCK\")\n\n def debug(self): # debug function (Depricated)\n return\n\n\n# Start the app if not impoted\nif __name__ == \"__main__\":\n Program(True).start()\n","repo_name":"pauln07org/Kryptos","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"9934472362","text":"#!/usr/bin/env python3\n\"\"\"Function that trains a model using mini-batch gradient descent\nalso analyze validaiton data, learning decay and early stopping\"\"\"\n\nimport tensorflow.keras as K\n\n\ndef train_model(network, data, labels, batch_size, epochs,\n validation_data=None, early_stopping=False,\n patience=0, learning_rate_decay=False, alpha=0.1,\n decay_rate=1, verbose=True, shuffle=False):\n \"\"\"return history\"\"\"\n callback = []\n if validation_data is not None and early_stopping:\n callback = [K.callbacks.EarlyStopping(monitor=\"val_loss\",\n patience=patience)]\n if validation_data is not None and learning_rate_decay:\n def lr_scheduler(epoch):\n return (alpha / (1 + (decay_rate * epoch)))\n learning = K.callbacks.LearningRateScheduler(schedule=lr_scheduler,\n verbose=1)\n callback.append(learning)\n history = network.fit(\n x=data,\n y=labels,\n batch_size=batch_size,\n epochs=epochs,\n verbose=verbose,\n shuffle=shuffle,\n validation_data=validation_data,\n callbacks=callback)\n return history\n","repo_name":"shincap8/holbertonschool-machine_learning","sub_path":"supervised_learning/0x06-keras/7-train.py","file_name":"7-train.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"42976740409","text":"#Weekly task 2 \n#Author: Sarah Hastings\n#The program should prompt the user and read in two money amounts (in cent), \n#Add the two amounts\n#Print out the answer in format with a euro sign and decimal point between the euro and cent of the amount \n#Reference: https://www.w3schools.com/python/python_numbers.asp \n #https://www.w3schools.com/python/python_howto_add_two_numbers.asp \n #https://stackabuse.com/format-number-as-currency-string-in-python/ \n\n\n\nnum1 = int(input(\"Enter amount1(in cent):\")) #Prompt the user to enter integer amounts, which will be stored in a variable called num1, num2 \nnum2 = int(input(\"Enter amount2(in cent):\"))\nsum= num1 + num2 #Calculate the sum of the values entered\nformat_sum = format(sum/100) #Format the value, stored in a variable to be used below\n\nprint (f\"The sum of these is €{format_sum}\") #The sum result is printed out in the specified format\n\n\n\n","repo_name":"Sarahlouhast/pands-problems-sheet","sub_path":"bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"27131090912","text":"from abc import ABCMeta, abstractmethod\r\nfrom dataclasses import dataclass, field\r\nfrom typing import List, Optional\r\n\r\n# Use error classes provided by requests\r\n# @dataclass\r\n# class ApiFieldError:\r\n# name: str\r\n# message: str\r\n\r\n# @dataclass\r\n# class ApiError:\r\n# timestamp: str\r\n# statusCode: int\r\n# message: str\r\n# request: str\r\n# fields: List[ApiFieldError]\r\n\r\n# @dataclass\r\n# class ApiErrorResult:\r\n# error: ApiError\r\n\r\n\r\n@dataclass\r\nclass CourseRequestJson:\r\n name: str\r\n studentRole: str\r\n instructorRole: str\r\n awsCredentialId: str\r\n grader: str\r\n fileSystem: str\r\n active: bool\r\n snowTicket: str\r\n quarter: str\r\n subject: str\r\n courseNumber: str\r\n instructor: str\r\n instructorEmail: str\r\n\r\n\r\n@dataclass\r\nclass LaunchProfileRequestJson:\r\n launchProfileName: str\r\n courseName: str\r\n applicationName: str\r\n playerName: str\r\n\r\n\r\n@dataclass\r\nclass AssociateCourseEnvironmentRequestBody:\r\n environment: str\r\n status: str\r\n notes: str\r\n\r\n\r\n@dataclass\r\nclass Args:\r\n course: str\r\n role: str\r\n\r\n\r\n@dataclass\r\nclass ModifyCourseEnvironmentRequestBody:\r\n status: str\r\n notes: str\r\n\r\n\r\n@dataclass\r\nclass UserResultJson:\r\n username: str\r\n firstName: str\r\n lastName: str\r\n uid: int\r\n homeFileSystem: str\r\n enrollments: List[str]\r\n\r\n\r\n@dataclass\r\nclass UserRequestJson:\r\n username: str\r\n firstName: Optional[str]\r\n lastName: Optional[str]\r\n roles: Optional[List[str]]\r\n apiKey: Optional[str]\r\n uid: int\r\n homeFileSystem: Optional[str]\r\n\r\n def __init__(\r\n self,\r\n username=None,\r\n firstName=None,\r\n lastName=None,\r\n roles=None,\r\n apiKey=None,\r\n uid=None,\r\n homeFileSystem=None,\r\n ):\r\n self.username = username\r\n self.firstName = firstName\r\n self.lastName = lastName\r\n self.roles = roles\r\n self.apiKey = apiKey\r\n self.uid = uid\r\n self.homeFileSystem = homeFileSystem\r\n\r\n\r\n@dataclass\r\nclass UserResult:\r\n username: str\r\n firstName: Optional[str]\r\n lastName: Optional[str]\r\n uid: int\r\n role: Optional[str]\r\n\r\n\r\n@dataclass\r\nclass KubernetesEnvironmentVariable:\r\n name: str\r\n value: str\r\n\r\n\r\n@dataclass\r\nclass KubernetesVolume:\r\n name: str\r\n type: str\r\n server: str\r\n path: str\r\n accessMode: str\r\n pvcName: str\r\n nfs: bool\r\n hostPath: bool\r\n\r\n\r\n@dataclass\r\nclass KubernetesVolumeMount:\r\n name: str\r\n mountPath: str\r\n mountPropagation: str\r\n subPath: str\r\n subPathExpr: str\r\n readOnly: bool\r\n\r\n\r\n@dataclass\r\nclass ApplicationJson:\r\n name: str\r\n image: str\r\n description: str\r\n pullPolicy: str\r\n volumeMounts: List[KubernetesVolumeMount]\r\n volumes: List[KubernetesVolume]\r\n command: str\r\n args: List[str]\r\n environment: List[KubernetesEnvironmentVariable]\r\n extraYaml: str\r\n\r\n\r\n@dataclass\r\nclass PlayerJson:\r\n name: str\r\n minCpu: int\r\n maxCpu: int\r\n minMemory: int\r\n maxMemory: int\r\n gpu: int\r\n\r\n\r\n@dataclass\r\nclass UserLaunchProfileJson:\r\n name: str\r\n application: ApplicationJson\r\n player: PlayerJson\r\n course: str\r\n\r\n\r\n@dataclass\r\nclass UserLaunchProfilesResult:\r\n launchProfiles: List[UserLaunchProfileJson]\r\n\r\n\r\n@dataclass\r\nclass FileSystemResult:\r\n identifier: str\r\n server: str\r\n path: str\r\n type: str = \"workspace\"\r\n\r\n\r\n@dataclass\r\nclass ListFileSystemsResultJson:\r\n fileSystems: List[FileSystemResult]\r\n\r\n\r\n@dataclass\r\nclass ImmutablePool:\r\n name: str\r\n poolRootName: str\r\n rule: str\r\n ou: str\r\n courseName: str\r\n mode: str\r\n\r\n\r\n@dataclass\r\nclass CourseResult:\r\n tags: Optional[List[str]]\r\n enrollments: Optional[List[UserResult]]\r\n courseId: str\r\n pool: Optional[ImmutablePool]\r\n active: Optional[bool]\r\n grader: Optional[UserResult]\r\n fileSystem: Optional[FileSystemResult]\r\n snowTicket: Optional[str]\r\n quarter: Optional[str]\r\n subject: Optional[str]\r\n courseNumber: Optional[str]\r\n instructor: Optional[str]\r\n instructorEmail: Optional[str]\r\n courseName: Optional[str]\r\n\r\n\r\n@dataclass\r\nclass CourseJson:\r\n courseId: str\r\n\r\n\r\n@dataclass\r\nclass TeamResult:\r\n teamName: str\r\n sanitizedTeamName: Optional[str]\r\n uniqueName: Optional[str]\r\n gid: int\r\n members: Optional[List[UserResult]]\r\n course: Optional[CourseResult]\r\n\r\n\r\n@dataclass\r\nclass TeamsResult:\r\n teams: List[TeamResult]\r\n\r\n\r\n@dataclass\r\nclass PoolAccountJson:\r\n accountId: str\r\n accountName: str\r\n username: str\r\n teamName: str\r\n\r\n\r\n@dataclass\r\nclass PoolAccountResult:\r\n accounts: List[PoolAccountJson]\r\n\r\n\r\n@dataclass\r\nclass PoolJson:\r\n name: str\r\n root: str\r\n predicate: str\r\n ou: str\r\n courseName: str\r\n mode: str\r\n\r\n\r\n@dataclass\r\nclass PoolsResult:\r\n pools: List[PoolJson]\r\n\r\n\r\n@dataclass\r\nclass Volume:\r\n type: str\r\n name: str\r\n server: str\r\n path: str\r\n accessMode: str\r\n pvcName: str\r\n\r\n\r\n@dataclass\r\nclass EnvironmentJson:\r\n volumes: List[Volume]\r\n\r\n\r\n@dataclass\r\nclass EnrollmentResult:\r\n username: str\r\n firstName: Optional[str]\r\n lastName: Optional[str]\r\n uid: int\r\n token: Optional[str]\r\n\r\n\r\n@dataclass\r\nclass EnvironmentEnrollmentResult:\r\n enrollments: Optional[List[EnrollmentResult]]\r\n\r\n\r\n@dataclass\r\nclass ListEnrollmentsForm:\r\n courseSlugs: List[str]\r\n username: str\r\n courseSlug: List[str]\r\n\r\n\r\n@dataclass\r\nclass ListCoursesResultJson:\r\n courses: List[CourseJson]\r\n\r\n\r\n@dataclass\r\nclass LaunchProfileJson:\r\n name: str\r\n application: ApplicationJson\r\n player: PlayerJson\r\n\r\n\r\n@dataclass\r\nclass ListLaunchProfilesJson:\r\n launchProfiles: List[LaunchProfileJson]\r\n\r\n\r\n@dataclass\r\nclass CourseEnvironmentResult:\r\n name: str\r\n environment: str\r\n status: str\r\n notes: str\r\n\r\n\r\n@dataclass\r\nclass Authentication:\r\n username: str\r\n admin: bool\r\n ta: bool\r\n student: bool\r\n\r\n\r\n@dataclass\r\nclass ListCourseEnvironmentsRequestBody:\r\n status: str\r\n subject: str\r\n term: str\r\n authentication: Authentication\r\n\r\n\r\n@dataclass\r\nclass ListCourseEnvironmentJson:\r\n environment: str\r\n status: str\r\n notes: str\r\n\r\n\r\n@dataclass\r\nclass ListCourseEnvironmentsResultJson:\r\n environments: List[ListCourseEnvironmentJson]\r\n\r\n\r\n@dataclass\r\nclass EnrollmentJson:\r\n username: str\r\n course: str\r\n","repo_name":"ucsd-ets/awsed_python_client","sub_path":"src/awsed/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":6373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"30647017746","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n__date__= 'Jan 11, 2014 '\n__author__= 'rad'\nimport logging\nlog = logging.getLogger(__name__)\n\nfrom petsquarebackend.models import DBSession\nfrom petsquarebackend.models import Base\nfrom petsquarebackend.models import ModelMethod\nfrom petsquarebackend import common\n\nfrom sqlalchemy import Column\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.orm import backref\n\nfrom sqlalchemy.types import (\n BigInteger,\n Integer,\n String,\n Boolean,\n DateTime,\n UnicodeText,\n BLOB,\n )\n\nimport datetime\nimport traceback\nimport Image as PILImage\nimport base64\n\nclass Animal_TB(Base):\n __tablename__ = 'animal'\n __public__ = ('id', 'name', 'type', 'sub_type', 'status', 'description',\n 'createddatetime', 'updateddatetime',\n # foreign key\n 'finder_id', 'owner_id',\n 'find_location_id', 'current_location_id',\n # relationship\n 'finder', 'owner', 'image_assocs')\n\n id = Column(Integer, nullable=False, unique=True,\n primary_key=True, autoincrement=True)\n name = Column(String(255), nullable=False, unique=False,)\n type = Column(String(255), nullable=False, unique=False,)\n sub_type = Column(String(255), nullable=False, unique=False,)\n status = Column(String(255), nullable=False, unique=False,)\n\n description = Column(String(255), nullable=True, unique=False,)\n\n createddatetime = Column(DateTime, nullable=False)\n updateddatetime = Column(DateTime, nullable=False)\n\n finder_id = Column(Integer, ForeignKey('user.id'), nullable=False, unique=False)\n owner_id = Column(Integer, ForeignKey('user.id'), nullable=True, unique=False)\n\n find_location_id = Column(Integer, ForeignKey('location.id'), nullable=True, unique=False)\n current_location_id = Column(Integer, ForeignKey('location.id'), nullable=True, unique=False)\n\n image_assocs = relationship('Animal_Image_TB', backref='animal')\n\n related_missions = relationship('Mission_TB', backref=backref('animal', order_by=id))\n\n def __init__(self, *args, **kwargs):\n self.createddatetime = datetime.datetime.now()\n self.updateddatetime = datetime.datetime.now()\n super(Animal_TB, self).__init__(*args, **kwargs)\n\n @classmethod\n @ModelMethod\n def link_image(cls, id, image_id, desc_dict):\n success, assoc_obj = Animal_Image_TB.get_associate_obj(id, image_id)\n if not success and assoc_obj is common.ERROR_MODEL_OBJECT_NOT_FOUND:\n desc_dict['animal_id'] = id\n desc_dict['image_id'] = image_id\n rtn = Animal_Image_TB.create(**desc_dict)\n elif success:\n rtn = (False, common.ERROR_RESOURCE_EXISTS)\n else:\n rtn = (success, assoc_obj)\n return rtn\n\n @classmethod\n @ModelMethod\n def show_image_meta(cls, id, image_id):\n return Animal_Image_TB.get_associate_obj(id, image_id)\n\n @classmethod\n @ModelMethod\n def update_image_meta(cls, id, image_id, desc_dict):\n success, assoc_obj = Animal_Image_TB.get_associate_obj(id, image_id)\n if success and assoc_obj:\n desc_dict['animal_id'] = id\n desc_dict['image_id'] = image_id\n rtn = Animal_Image_TB.update(assoc_obj.id, **desc_dict)\n else:\n rtn = (success, assoc_obj)\n return rtn\n\n @classmethod\n @ModelMethod\n def unlink_image(cls, id, image_id):\n success, assoc_obj = Animal_Image_TB.get_associate_obj(id, image_id)\n if success and assoc_obj:\n rtn = Animal_Image_TB.delete(assoc_obj.id)\n else:\n rtn = (success, assoc_obj)\n return rtn\n\nclass Animal_Image_TB(Base):\n __tablename__ = 'animal_image'\n __public__ = ('id', 'status', 'description',\n 'createddatetime', 'updateddatetime',\n # foreign key\n 'animal_id', 'image_id',\n # relationship\n 'animal', 'image'\n )\n\n id = Column(Integer, nullable=False, unique=True,\n primary_key=True, autoincrement=True)\n animal_id = Column(Integer, ForeignKey('animal.id'), nullable=False, unique=False)\n image_id = Column(Integer, ForeignKey('image.id'), nullable=False, unique=False)\n\n status = Column(String(255), nullable=True, unique=False,)\n description = Column(String(255), nullable=True, unique=False,)\n\n createddatetime = Column(DateTime, nullable=False)\n updateddatetime = Column(DateTime, nullable=False)\n\n image = relationship('Image_TB', backref=backref('animal_assocs', order_by=id))\n\n def __init__(self, *args, **kwargs):\n self.createddatetime = datetime.datetime.now()\n self.updateddatetime = datetime.datetime.now()\n super(Animal_Image_TB, self).__init__(*args, **kwargs)\n\n @classmethod\n @ModelMethod\n def get_associate_obj(cls, animal_id, image_id):\n success, items = cls.list(filattr=[('animal_id', animal_id),\n ('image_id', image_id)])\n if success and items:\n if len(items) > 1:\n log.error('get_associate_obj: not unique associate'\n ' (animal: %s, image: %s)' % (animal_id, image_id))\n return (True, items[0])\n elif success:\n return (False, common.ERROR_MODEL_OBJECT_NOT_FOUND)\n else:\n return (success, items)\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"radjan/petsfaq","sub_path":"petsadv/petsquare-backend/petsquarebackend/models/animal.py","file_name":"animal.py","file_ext":"py","file_size_in_byte":5731,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"16777999205","text":"from dataset import dataset_full,dataset\nimport os\nimport numpy as np\nimport glob\nfrom utils import *\nfrom scipy import io\nimport torch\nfrom torch.nn import Module\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom skimage.io import imsave\n\n\"\"\"\nNo mask training, no deblocking\n\n\"\"\"\n\nclass Denoiser(Module):\n def __init__(self):\n super().__init__()\n self.D = nn.Sequential(nn.Conv2d(1, 32, 3, padding=1),\n\n nn.ReLU(),\n nn.Conv2d(32, 32, 3, padding=1),\n\n nn.ReLU(),\n nn.Conv2d(32, 32, 3, padding=1),\n\n nn.ReLU(),\n nn.Conv2d(32, 1, 3, padding=1,bias=False))\n\n def forward(self, inputs):\n S = inputs.shape[0]\n inputs = torch.squeeze(inputs,dim=3)\n inputs = torch.reshape(inputs,[inputs.shape[0],inputs.shape[1],33, 33])\n\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=1,dim=1),dim=0)\n\n # inputs = torch.unsqueeze(torch.reshape(inputs,[-1,33,33]),dim=1)\n output = self.D(inputs)\n # output=inputs-output\n output = torch.cat(torch.split(output, split_size_or_sections=S, dim=0), dim=1)\n output = torch.reshape(output,[output.shape[0],output.shape[1],33*33])\n output = torch.unsqueeze(output, dim=3)\n return output\n\nclass Deblocker(Module):\n def __init__(self):\n super().__init__()\n self.D = nn.Sequential(nn.Conv2d(1, 32, 3, padding=1),\n\n nn.ReLU(),\n nn.Conv2d(32, 32, 3, padding=1),\n\n nn.ReLU(),\n nn.Conv2d(32, 32, 3, padding=1),\n\n nn.ReLU(),\n nn.Conv2d(32, 1, 3, padding=1,bias=False))\n\n def forward(self, inputs):\n # inputs = torch.unsqueeze(inputs,dim=1)\n output = self.D(inputs)\n # output = torch.squeeze(output,dim=1)\n return output\n\n\nclass AMP_net_Deblock_RA(Module):\n def __init__(self,layer_num, A):\n super().__init__()\n self.layer_num = layer_num\n self.denoisers = []\n self.deblocks = []\n self.steps = []\n for n in range(layer_num):\n self.denoisers.append(Denoiser())\n self.deblocks.append(Deblocker())\n self.register_parameter(\"step_\" + str(n + 1), nn.Parameter(torch.tensor(1.0),requires_grad=True))\n self.steps.append(eval(\"self.step_\" + str(n + 1)))\n for n,denoiser in enumerate(self.denoisers):\n self.add_module(\"denoiser_\"+str(n+1),denoiser)\n for n,deblock in enumerate(self.deblocks):\n self.add_module(\"deblock_\"+str(n+1),deblock)\n\n for p in self.parameters():\n p.requires_grad=False\n\n self.register_parameter(\"A\", nn.Parameter(torch.from_numpy(A).float(), requires_grad=True))\n self.register_parameter(\"Q\", nn.Parameter(torch.from_numpy(np.transpose(A)).float(), requires_grad=True))\n\n def forward(self, inputs, sampling_matrix_mask, output_layers):\n \"\"\"\n 此处就是前向传播,返回每一层的输出\n :param inputs: 此处的inputs 为图像数据\n :return:\n \"\"\"\n H = int(inputs.shape[2]/33)\n L = int(inputs.shape[3]/33)\n S = inputs.shape[0]\n\n now_mask = self.A*sampling_matrix_mask\n now_Q = torch.transpose(sampling_matrix_mask,0,1)*self.Q\n y = self.sampling(now_mask, inputs) # sampling\n\n now_Q = torch.unsqueeze(torch.unsqueeze(now_Q, dim=0),dim=0)\n X = torch.matmul(now_Q,y) # initialization\n for n in range(output_layers):\n step = self.steps[n]\n denoiser = self.denoisers[n]\n deblocker = self.deblocks[n]\n\n z = self.block1(X, y, now_mask, step)\n\n noise = denoiser(X)\n\n # X = z-self.block2()\n\n matrix_temp = torch.unsqueeze(torch.unsqueeze(\n step * torch.matmul(torch.transpose(now_mask, 0, 1), now_mask) - torch.eye(33 * 33).float().cuda(),\n dim=0), dim=0)\n # matrix_temp = (matrix_temp,dim=1)\n # matrix_temp = matrix_temp.expand(-1,y.shape[1],-1,-1)\n\n X = z - torch.matmul(matrix_temp, noise)\n\n X = self.together(X,S,H,L)\n X = X - deblocker(X)\n\n X = torch.cat(torch.split(X, split_size_or_sections=33, dim=2), dim=1)\n X = torch.cat(torch.split(X, split_size_or_sections=33, dim=3), dim=1)\n # inputs = torch.transpose(torch.reshape(inputs, [-1, 33*33]),0,1)\n X = torch.reshape(X, [S, H * L, 33 * 33])\n X = torch.unsqueeze(X, dim=3)\n\n X = self.together(X, S, H, L)\n return X\n\n\n def sampling(self,A,inputs):\n # inputs = torch.squeeze(inputs)\n # inputs = torch.reshape(inputs,[-1,33*33]) # 矩阵向量hua\n # inputs = torch.squeeze(inputs,dim=1)\n H = int(inputs.shape[2] / 33)\n L = int(inputs.shape[3] / 33)\n S = inputs.shape[0]\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=33, dim=2), dim=1)\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=33, dim=3), dim=1)\n # inputs = torch.transpose(torch.reshape(inputs, [-1, 33*33]),0,1)\n inputs = torch.reshape(inputs, [S, H * L, 33 * 33])\n inputs = torch.unsqueeze(inputs, dim=3)\n A_temp = torch.unsqueeze(torch.unsqueeze(A, dim=0),dim=0)\n # A_temp = A_temp.expand([-1, inputs.shape[1], -1, -1])\n outputs = torch.matmul(A_temp, inputs)\n # inputs = torch.reshape(inputs, [-1, 33 * 33])\n # inputs = torch.unsqueeze(inputs,dim=2)\n # outputs = torch.matmul(sampling_matrix, inputs)\n return outputs\n\n def block1(self,X,y,A,step):\n # X = torch.squeeze(X)\n # X = torch.transpose(torch.reshape(X, [-1, 33 * 33]),0,1) # 矩阵向量hua\n A = torch.unsqueeze(torch.unsqueeze(A,dim=0),dim=0)\n # A = A.expand(-1, y.shape[1], -1, -1)\n outputs = torch.matmul(torch.transpose(A, 2, 3), y-torch.matmul(A, X))\n outputs = step * outputs + X\n # outputs = torch.unsqueeze(torch.reshape(torch.transpose(outputs,0,1),[-1,33,33]),dim=1)\n return outputs\n\n def together(self,inputs,S,H,L):\n inputs = torch.squeeze(inputs,dim=3)\n inputs = torch.reshape(inputs, [S, H * L, 33, 33])\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=H, dim=1), dim=3)\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=1, dim=1), dim=2)\n return inputs\n\n\nclass AMP_net_Deblock(Module):\n def __init__(self,layer_num, A):\n super().__init__()\n self.layer_num = layer_num\n self.denoisers = []\n self.deblocks = []\n self.steps = []\n self.register_parameter(\"A\",nn.Parameter(torch.from_numpy(A).float(),requires_grad=True))\n self.register_parameter(\"Q\", nn.Parameter(torch.from_numpy(np.transpose(A)).float(), requires_grad=True))\n for n in range(layer_num):\n self.denoisers.append(Denoiser())\n self.deblocks.append(Deblocker())\n self.register_parameter(\"step_\" + str(n + 1), nn.Parameter(torch.tensor(1.0),requires_grad=True))\n self.steps.append(eval(\"self.step_\" + str(n + 1)))\n for n,denoiser in enumerate(self.denoisers):\n self.add_module(\"denoiser_\"+str(n+1),denoiser)\n for n,deblock in enumerate(self.deblocks):\n self.add_module(\"deblock_\"+str(n+1),deblock)\n\n def forward(self, inputs, sampling_matrix_mask, output_layers):\n \"\"\"\n 此处就是前向传播,返回每一层的输出\n :param inputs: 此处的inputs 为图像数据\n :return:\n \"\"\"\n H = int(inputs.shape[2]/33)\n L = int(inputs.shape[3]/33)\n S = inputs.shape[0]\n\n now_mask = self.A*sampling_matrix_mask\n now_Q = torch.transpose(sampling_matrix_mask,1,2)*self.Q\n y = self.sampling(now_mask, inputs) # sampling\n\n now_Q = torch.unsqueeze(now_Q, dim=1)\n X = torch.matmul(now_Q,y) # initialization\n for n in range(output_layers):\n step = self.steps[n]\n denoiser = self.denoisers[n]\n deblocker = self.deblocks[n]\n\n z = self.block1(X, y, now_mask, step)\n\n noise = denoiser(X)\n\n # X = z-self.block2()\n\n matrix_temp = torch.unsqueeze(step * torch.matmul(torch.transpose(now_mask,1,2), now_mask) - torch.eye(33 * 33).float().cuda(),dim=1)\n # matrix_temp = (matrix_temp,dim=1)\n # matrix_temp = matrix_temp.expand(-1,y.shape[1],-1,-1)\n\n X = z - torch.matmul(matrix_temp, noise)\n\n X = self.together(X,S,H,L)\n X = X - deblocker(X)\n\n X = torch.cat(torch.split(X, split_size_or_sections=33, dim=2), dim=1)\n X = torch.cat(torch.split(X, split_size_or_sections=33, dim=3), dim=1)\n # inputs = torch.transpose(torch.reshape(inputs, [-1, 33*33]),0,1)\n X = torch.reshape(X, [S, H * L, 33 * 33])\n X = torch.unsqueeze(X, dim=3)\n\n X = self.together(X, S, H, L)\n return X\n\n\n def sampling(self,A,inputs):\n # inputs = torch.squeeze(inputs)\n # inputs = torch.reshape(inputs,[-1,33*33]) # 矩阵向量hua\n # inputs = torch.squeeze(inputs,dim=1)\n H = int(inputs.shape[2] / 33)\n L = int(inputs.shape[3] / 33)\n S = inputs.shape[0]\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=33, dim=2), dim=1)\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=33, dim=3), dim=1)\n # inputs = torch.transpose(torch.reshape(inputs, [-1, 33*33]),0,1)\n inputs = torch.reshape(inputs, [S, H * L, 33 * 33])\n inputs = torch.unsqueeze(inputs, dim=3)\n A_temp = torch.unsqueeze(A, dim=1)\n # A_temp = A_temp.expand([-1, inputs.shape[1], -1, -1])\n outputs = torch.matmul(A_temp, inputs)\n # inputs = torch.reshape(inputs, [-1, 33 * 33])\n # inputs = torch.unsqueeze(inputs,dim=2)\n # outputs = torch.matmul(sampling_matrix, inputs)\n return outputs\n\n def block1(self,X,y,A,step):\n # X = torch.squeeze(X)\n # X = torch.transpose(torch.reshape(X, [-1, 33 * 33]),0,1) # 矩阵向量hua\n A = torch.unsqueeze(A,dim=1)\n # A = A.expand(-1, y.shape[1], -1, -1)\n outputs = torch.matmul(torch.transpose(A, 2, 3), y-torch.matmul(A, X))\n outputs = step * outputs + X\n # outputs = torch.unsqueeze(torch.reshape(torch.transpose(outputs,0,1),[-1,33,33]),dim=1)\n return outputs\n\n def together(self,inputs,S,H,L):\n inputs = torch.squeeze(inputs,dim=3)\n inputs = torch.reshape(inputs, [S, H * L, 33, 33])\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=H, dim=1), dim=3)\n inputs = torch.cat(torch.split(inputs, split_size_or_sections=1, dim=1), dim=2)\n return inputs\n\n\ndef compute_loss(outputs, target):\n loss = []\n for output in outputs:\n loss.append(torch.mean((output - target) ** 2))\n return loss\n\n\ndef get_final_loss(loss_all):\n output = 0\n for loss in loss_all:\n output += loss\n return output\n\n\ndef get_loss(outputs, noise_all, Xs, H, target, sigma=0.01):\n loss1 = torch.mean((outputs[-1] - target) ** 2)\n loss2 = torch.mean(torch.abs(outputs[-1] - target))\n num = 0\n for n in range(len(noise_all)):\n num += 1\n X = Xs[n]\n noise = noise_all[n]\n loss2 += torch.mean((noise - torch.matmul(H, target - X)) ** 2)\n\n return loss1, loss2\n\ndef train(model, opt, train_loader, epoch, batch_size, CS_ratio,PhaseNum):\n model.train()\n n = 0\n for data,_ in train_loader:\n n = n + 1\n opt.zero_grad() # 清空梯度\n data = torch.unsqueeze(data,dim=1)\n data = Variable(data.float().cuda())\n outputs= model(data,PhaseNum)\n\n # loss_all = compute_loss(outputs,data)\n # loss = get_final_loss(loss_all)\n # loss = torch.mean((outputs[-1]-target)**2)\n\n loss = torch.mean((outputs-data)**2)\n loss.backward()\n opt.step()\n if n % 25 == 0:\n output = \"CS_ratio: %d [%02d/%02d] loss: %.4f \" % (\n CS_ratio, epoch, batch_size * n, loss.data.item())\n # output = \"[%02d/%02d] cost: %.4f, cost_sym: %.4f \\n\" % (epoch, batch_size*n,\n # cost.data.item(),cost_sym.data.item())\n print(output)\n\ndef get_mask(data_batch,test=0):\n data = torch.zeros([data_batch,math.ceil(1089*0.5),1089])\n for n in range(data_batch):\n if test==0:\n random_num = math.ceil(1089*(random.randint(1,50)/100))\n else:\n random_num = math.ceil(1089*(test/100))\n data[n,0:random_num,:] = 1\n return data\n\n\ndef get_reconstruction_mask(test=50):\n data = torch.zeros([math.ceil(1089*0.5),1089])\n random_num = math.ceil(1089*(test/100))\n data[0:random_num,:] = 1\n return data\n\n\ndef get_val_result(model,PhaseNum,CS_ratio, is_cuda=True):\n model.eval()\n with torch.no_grad():\n test_set_path = \"../../dataset/Set11\"\n # test_set_path = \"../../dataset/BSR_bsds500/BSR/BSDS500/data/images/test\"\n test_set_path = glob.glob(test_set_path + '/*.tif')\n ImgNum = len(test_set_path) # 测试图像的数量\n PSNR_All = np.zeros([1, ImgNum], dtype=np.float32)\n SSIM_All = np.zeros([1, ImgNum], dtype=np.float32)\n PSNR_CS_ratios = np.zeros([1, 50], dtype=np.float32)\n SSIM_CS_ratios = np.zeros([1, 50], dtype=np.float32)\n model.eval()\n sub_path = \"../../results_c4/AMP_net_deblock/\"+CS_ratio\n\n n = 0\n CS_ratio_temp = [25]\n for CS_ratio in CS_ratio_temp:\n save_path = sub_path + \"/images_generated\"\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n save_path = os.path.join(save_path, str(CS_ratio))\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n print(n+1)\n for img_no in range(ImgNum):\n imgName = test_set_path[img_no] # 当前图像的名字\n\n [Iorg, row, col, Ipad, row_new, col_new] = imread_CS_py(imgName)\n Icol = img2col_py(Ipad, 33) / 255.0 # 返回 行向量化后的图像数据\n Ipad /= 255.0\n # Img_input = np.dot(Icol, Phi_input) # 压缩感知降采样\n # Img_output = Icol\n\n if is_cuda:\n inputs = Variable(torch.from_numpy(Ipad.astype('float32')).cuda())\n else:\n inputs = Variable(torch.from_numpy(Ipad.astype('float32')))\n # if model.network == \"ista_plus\" or model.network == \"ista\":\n # output, _ = model(inputs)\n # else:\n # output = model(inputs)\n inputs = torch.unsqueeze(torch.unsqueeze(inputs,dim=0),dim=0)\n sampling_matrix_mask = get_mask(1, CS_ratio)\n\n # sampling_matrix_mask = get_reconstruction_mask(CS_ratio)\n\n if is_cuda:\n sampling_matrix_mask = Variable(sampling_matrix_mask.float().cuda())\n else:\n sampling_matrix_mask = Variable(sampling_matrix_mask.float())\n\n outputs = model(inputs,sampling_matrix_mask, PhaseNum)\n outputs = torch.squeeze(outputs)\n if is_cuda:\n outputs = outputs.cpu().data.numpy()\n else:\n outputs = outputs.data.numpy()\n\n images_recovered = outputs[0:row, 0:col] * 255\n\n # images_recovered = BM3D_denoise(images_recovered,Iorg,model.detach().A)\n # images_recovered *= 255\n aaa = images_recovered.astype(int)\n bbb = aaa < 0\n aaa[bbb] = 0\n bbb = aaa > 255\n aaa[bbb] = 255\n\n rec_PSNR = psnr(aaa, Iorg) # 计算PSNR的值\n PSNR_All[0, img_no] = rec_PSNR\n rec_SSIM = compute_ssim(aaa, Iorg) # 计算PSNR的值\n SSIM_All[0, img_no] = rec_SSIM\n name_temp = (imgName.split('/')[-1]).split('.')[0]\n imsave(os.path.join(save_path, name_temp + '.jpg'), aaa)\n imsave(os.path.join(save_path, name_temp + '_' + str(rec_PSNR) + '_' + str(rec_SSIM) + '.jpg'), aaa)\n\n PSNR_CS_ratios[0,n] = np.mean(PSNR_All)\n SSIM_CS_ratios[0, n] = np.mean(SSIM_All)\n output_file = open(sub_path + \"/Set11_PSNR_1_to_50.txt\", 'a')\n output_file.write(\"%.4f \" % (np.mean(PSNR_All)))\n output_file.close()\n output_file = open(sub_path + \"/Set11_SSIM_1_to_50.txt\", 'a')\n output_file.write(\"%.4f \" % (np.mean(SSIM_All)))\n output_file.close()\n n+=1\n return PSNR_CS_ratios,SSIM_CS_ratios\n\n\ndef load_sampling_matrix(CS_ratio):\n path = \"../../dataset/sampling_matrix\"\n data = io.loadmat(os.path.join(path, str(CS_ratio) + '.mat'))['sampling_matrix']\n return data\n\n\ndef get_Q(data_set,A):\n A = torch.from_numpy(A)\n n = 0\n data_loader = torch.utils.data.DataLoader(data_set, batch_size=len(data_set),\n shuffle=True, num_workers=2)\n for data, target in data_loader:\n data = torch.transpose(torch.reshape(data, [-1, 33 * 33]), 0, 1)\n target = torch.transpose(torch.reshape(target, [-1, 33 * 33]), 0, 1)\n y = torch.matmul(A.float(),data.float())\n x = target.float()\n if n==0:\n ys = y\n Xs = x\n n = 1\n else:\n ys = torch.cat([ys,y],dim=1)\n Xs = torch.cat([Xs,x],dim=1)\n Q = torch.matmul(torch.matmul(Xs,torch.transpose(ys,0,1)),\n torch.inverse(torch.matmul(ys, torch.transpose(ys, 0, 1))))\n return Q.numpy()\n\n\nif __name__ == \"__main__\":\n model_name = \"AMP_Net_deblock\"\n # model_name = \"AMP_Net_deblock_RA\"\n\n CS_ratios = [0.01,0.1,0.25,0.4]\n max_CS_ratio = 50\n phase = 6\n CS_ratio = 50\n\n\n path = os.path.join(\"../../results_c4\", model_name, str(CS_ratio),str(phase), \"best_model.pkl\")\n\n A = load_sampling_matrix(max_CS_ratio)\n\n model = AMP_net_Deblock(phase,A)\n # model.cuda()\n model.load_state_dict(torch.load(path))\n print(\"Start\")\n psnrs, ssims = get_val_result(model, phase, str(CS_ratio), is_cuda=True) # test AMP_net\n\n print_str = \" %.4f %.4f %.4f %.4f %.4f %.4f %.4f\" % (\n psnrs[0, 0], psnrs[0, 1], psnrs[0, 2],\n psnrs[0, 3], psnrs[0, 4], psnrs[0, 5], psnrs[0, 6])\n print(print_str)\n\n print_str = \" %.4f %.4f %.4f %.4f %.4f %.4f %.4f\" % (\n ssims[0, 0], ssims[0, 1], ssims[0, 2],\n ssims[0, 3], ssims[0, 4], ssims[0, 5], ssims[0, 6])\n print(print_str)\n","repo_name":"yipengliu/Scalable-Deep-Compressive-Sensing","sub_path":"SDCS_codes/test_SDCS_AMP_net.py","file_name":"test_SDCS_AMP_net.py","file_ext":"py","file_size_in_byte":19046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"31627208018","text":"import copy\r\n\r\n# Màn chơi mẫu\r\n# 1: Vị trí hợp lệ\r\n# 0: Vị trí không hợp lệ\r\n# G: Vị trí block không thể đứng thẳng\r\n# X: Đích\r\n# LA: Cần gạt nhẹ cho vị trí A\r\n# HA: Cần gạt nặng cho vị trí A\r\n# 1A, 0A: Vị trí thay đổi khi chạm vào cần gạt\r\nlevel1 = [['1', '1', '1', '0', '0', '0', '0', '0', '0', '0'],\r\n ['1', '1', '1', 'LA', '1', '0A', '0', '0', '0', '0'],\r\n ['1', '1', '1', '1', '1', '1', '1', '1', '1', '0'],\r\n ['1', '1', '1', '1', 'G', '1', '1', '1', '1', '1'],\r\n ['0', '0', '0', '0', 'G', 'G', '1', 'X', '1', '1'],\r\n ['0', '0', '0', '0', '0', '0', '1', '1', '1', '0']]\r\n# level1 = [['0','1','1','1','0','0','0','0','0','0'],\r\n# ['0','1','1','1','1','0','0','0','0','0'],\r\n# ['HK','1','1','1','1','0K','1','X','1','0'],\r\n# ['0','1','1','1','1','1','1','1','1','1'],\r\n# ['0','0','0','0','G','G','1','0','1','1'],\r\n# ['0','0','0','0','0','0','1','1','1','0']]\r\n\r\n# Order: [row col][row, col]\r\nb_input = ((2, 1), (2, 2))\r\n\r\n# Các bước có thể di chuyển được:\r\n# 1: Lên\r\n# 2: Phải\r\n# -1: Xuống\r\n# -2: Trái\r\nlist_direction = [1, 2, -1, -2]\r\nlistMove = []\r\n\r\n\r\ndef init_input(x1, y1, x2, y2):\r\n return (x1, y1), (x2, y2)\r\n\r\n\r\n# 0: đứng, 1: dọc, -1: ngang\r\ndef block_direction(i_input=((0, 0), (0, 0))):\r\n if i_input[0][0] == i_input[1][0] and i_input[0][1] == i_input[1][1]:\r\n return 0\r\n elif i_input[0][0] == i_input[1][0] and abs(i_input[0][1] - i_input[1][1]) == 1:\r\n return 1\r\n elif abs(i_input[0][0] - i_input[1][0]) == 1 and i_input[0][1] == i_input[1][1]:\r\n return -1\r\n else:\r\n return 2\r\n\r\n\r\n# Xử lý input với hướng nhận được\r\ndef move(direction, i_input=((0, 0), (0, 0))):\r\n row = 0\r\n col = 0\r\n is_horizontal = 1\r\n if direction == 1:\r\n row = row - 1\r\n elif direction == -1:\r\n row = row + 1\r\n elif direction == -2:\r\n col = col - 1\r\n is_horizontal = -1\r\n elif direction == 2:\r\n col = col + 1\r\n is_horizontal = -1\r\n else:\r\n return i_input\r\n\r\n orientation = block_direction(i_input) * is_horizontal\r\n if orientation == 0:\r\n if row == -1 or col == -1:\r\n return (i_input[0][0] + row * 2, i_input[0][1] + col * 2), (i_input[1][0] + row, i_input[1][1] + col)\r\n elif row == 1 or col == 1:\r\n return (i_input[0][0] + row, i_input[0][1] + col), (i_input[1][0] + row * 2, i_input[1][1] + col * 2)\r\n elif orientation == 1:\r\n return (i_input[0][0] + row, i_input[0][1] + col), (i_input[1][0] + row, i_input[1][1] + col)\r\n elif orientation == -1:\r\n if row == 1 or col == 1:\r\n return (i_input[0][0] + row * 2, i_input[0][1] + col * 2), (i_input[1][0] + row, i_input[1][1] + col)\r\n elif row == -1 or col == -1:\r\n return (i_input[0][0] + row, i_input[0][1] + col), (i_input[1][0] + row * 2, i_input[1][1] + col * 2)\r\n\r\n\r\n# Tính giá trị từ input\r\ndef execute_move(i_input=((0, 0), (0, 0)), i_board=None):\r\n if i_board is None:\r\n i_board = []\r\n # Khởi tạo giá trị cho bàn cờ hiện tại\r\n height = len(i_board)\r\n width = len(i_board[0])\r\n i_state = 'N'\r\n block_dir = block_direction(i_input)\r\n\r\n if is_not_out_of_range(i_input, height, width):\r\n # Trường hợp thắng\r\n if is_equal(i_input, i_board, 'X'):\r\n i_state = 'W'\r\n\r\n # Trường hợp không thay đổi trạng thái\r\n elif is_equal([i_input[0]], i_board, '0') or is_equal([i_input[1]], i_board, '0') or (block_dir == 0 and is_equal(i_input, i_board, 'G')):\r\n i_state = 'L'\r\n\r\n # Trường hợp thay đổi trạng thái gạt cần\r\n elif (is_equal(i_input, i_board, 'H') and block_dir == 0) or is_equal([i_input[0]], i_board, 'L'):\r\n i_board = toggle_switch(i_board, get_string(i_input[0], i_board, 1))\r\n elif is_equal([i_input[1]], i_board, 'L'):\r\n i_board = toggle_switch(i_board, get_string(i_input[1], i_board, 1))\r\n # Trường hợp teleport\r\n elif is_equal([i_input[0]], i_board, 'T') or is_equal([i_input[0]], i_board, 'T'):\r\n if block_dir != 2:\r\n if block_dir == 0 or is_equal([i_input[0]], i_board, 'T'):\r\n i_input[0] = teleports(i_board, get_string(i_input[0], i_board, 1))\r\n else:\r\n i_input[1] = teleports(i_board, get_string(i_input[0], i_board, 1))\r\n\r\n # Trường hợp không hợp lệ\r\n else:\r\n i_state = 'L'\r\n\r\n # Giá trị trả về bao gồm trạng thái bàn cờ, bàn cờ, giá trị input\r\n return i_state, i_board, i_input\r\n\r\n\r\ndef toggle_switch(i_board, word):\r\n if i_board is None:\r\n i_board = []\r\n for row in range(len(i_board)):\r\n for col in range(len(i_board[row])):\r\n if len(i_board[row][col]) == 2 and i_board[row][col][1] == word:\r\n if i_board[row][col][0] == '0':\r\n i_board[row][col] = '1' + i_board[row][col][1]\r\n elif i_board[row][col][0] == '1':\r\n i_board[row][col] = '0' + i_board[row][col][1]\r\n return i_board\r\n\r\n\r\ndef teleports(i_board, word):\r\n if i_board is None:\r\n i_board = []\r\n for row in range(len(i_board)):\r\n for col in range(len(i_board[row])):\r\n if i_board[row][col][0] == 't' and i_board[row][col][1] == word:\r\n return row, col\r\n\r\n\r\ndef is_not_out_of_range(i_input, height, width):\r\n rs = True\r\n for i in i_input:\r\n rs = rs and i[0] >= 0 and i[1] >= 0 and i[0] < height and i[1] < width\r\n return rs\r\n\r\n\r\ndef is_equal(i_input, i_board, word, pos=0):\r\n rs = True\r\n for i in i_input:\r\n rs = rs and get_string(i, i_board, pos) == word\r\n return rs\r\n\r\n\r\ndef get_string(i_block, i_board, pos=0):\r\n return i_board[i_block[0]][i_block[1]][pos]\r\n\r\n\r\n# In bàn cờ\r\ndef print_board(i_board, i_pos=((0, 0), (0, 0))):\r\n n_board = copy.deepcopy(i_board)\r\n n_board[i_pos[0][0]][i_pos[0][1]] = 'B '\r\n n_board[i_pos[1][0]][i_pos[1][1]] = 'B '\r\n for board in n_board:\r\n for word in board:\r\n if word[0] == '0':\r\n word = ' '\r\n elif word[0] == '1':\r\n word = '1 '\r\n elif word == 'X': \r\n word = 'X '\r\n elif len(word) == 1:\r\n word = word.ljust(2)\r\n print(word + ' ', sep=' ', end='', flush=True)\r\n print('\\n')\r\n\r\n\r\n# So sách 2 bàn cờ\r\ndef compare_board(i_board1, i_board2):\r\n for row in range(len(i_board1)):\r\n for col in range(len(i_board2[row])):\r\n if i_board1[row][col] != i_board2[row][col]: return False\r\n return True\r\n\r\n\r\ndef exist(moves_w_board, i_input, i_board):\r\n for i in moves_w_board:\r\n if i[0] == i_input and compare_board(i[1], i_board):\r\n return True\r\n return False\r\n\r\ndef dfs(moves_w_board, i_board, state, i_input):\r\n\r\n if state == 'L':\r\n return None\r\n elif state == 'N':\r\n if exist(moves_w_board, i_input, i_board):\r\n return None\r\n else:\r\n n_moves_w_board = copy.deepcopy(moves_w_board)\r\n n_moves_w_board.append((i_input, i_board))\r\n for d in list_direction:\r\n n_state, n_board, n_input = execute_move(move(d, i_input), copy.deepcopy(i_board))\r\n\r\n result = dfs(n_moves_w_board, n_board, n_state, n_input)\r\n if result is not None:\r\n return result\r\n else:\r\n moves_w_board.append((i_input, i_board))\r\n return moves_w_board\r\n\r\n\r\ndef bfs():\r\n return 0\r\n\r\n\r\ndef test():\r\n i_input = ((2, 1), (2, 2))\r\n global level1\r\n while True:\r\n direct = input('Insert your your direction: ')\r\n i_input = move(int(direct), i_input)\r\n state, level1, i_input = execute_move(i_input, level1)\r\n print_board(level1, i_input)\r\n print('Block position: ', i_input)\r\n\r\n\r\n# Phương thức chạy giải thuật\r\ndef run(i_inputs):\r\n if i_inputs is not None:\r\n for i in i_inputs:\r\n print('-------------')\r\n # state, i_board, n_input = execute_move(i, i_board)\r\n print_board(i[1], i[0])\r\n print('Block position: ', i[0])\r\n print('The path has been found')\r\n else:\r\n print('Cannot find the path')\r\n\r\n\r\nwhile True:\r\n method = input('Insert your method: ')\r\n if method == 'dfs':\r\n run(dfs([], level1, 'N', b_input))\r\n elif method == 'bfs':\r\n print('BFS')\r\n else:\r\n test()\r\n\r\n","repo_name":"huysolo/ai-2018","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8652,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"13509450227","text":"import random\nimport time\nimport threading\n\nclass Trader:\n def __init__(self, api):\n self.api = api\n self.symbol = 'AAPL'\n self.target_price = 100\n self.running = False\n\n def trade(self):\n self.api.authenticate()\n stock_price = self.api.get_apple_stock_price()\n if stock_price >= 100:\n self.api.place_order(side='buy', symbol=self.symbol, quantity=1, price=stock_price)\n\n def start(self):\n \"\"\"\n Starts the automated trading program.\n \"\"\"\n self.running = True\n thread = threading.Thread(target=self.run)\n thread.start()\n\n def stop(self):\n \"\"\"\n Stops the automated trading program.\n \"\"\"\n self.running = False\n\n def run(self):\n \"\"\"\n Runs the automated trading program.\n \"\"\"\n # Get the initial stock price\n current_price = self.get_stock_price()\n\n # Keep track of the previous price\n previous_price = current_price\n\n # Loop until stopped\n while self.running:\n # Get the current price\n current_price = self.get_stock_price()\n\n # If the price has changed, print the new price\n if current_price != previous_price:\n print(f'Current price: {current_price}')\n\n # Update the previous price\n previous_price = current_price\n\n # Check if the current price is at the target price\n if current_price >= self.target_price:\n # Place a buy order for one share of the stock\n order = self.api.place_order(order_side='buy', symbol=self.symbol, quantity=1, price=current_price)\n\n # Print the order details\n print(f'Buy order placed: {order}')\n\n # Wait for a short time before checking the price again\n time.sleep(1)\n\n def get_stock_price(self):\n \"\"\"\n Returns the current price of the specified stock symbol.\n \"\"\"\n # Replace this with code to retrieve the current price from the API\n # For now, we will return a random price between 90 and 110\n return random.uniform(90, 110)\n","repo_name":"toTheMoon247/roboTrader","sub_path":"backend/trader.py","file_name":"trader.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"70113630219","text":"from __future__ import absolute_import, division, print_function\nfrom six.moves import range\n'''\nAuthor : Uervirojnangkoorn, M.\nCreated : 12/1/2014\nDescription : Genetic algorithm.\n'''\nimport random\n\nclass ga_handler(object):\n '''\n Genetic algorithm class.\n '''\n def __init__(self):\n '''\n Constructor\n '''\n\n\n def initialse(self, pop_size, idv_length, cdf_from_pdf_set, phi_for_hl):\n '''\n generate population from cdf of HL\n '''\n pop=[];\n for i_pop in range(pop_size):\n idv=[0]*idv_length;\n\n for i_idv in range(idv_length):\n tmp_rand=random.random();\n for i_phi in range(len(phi_for_hl)):\n if cdf_from_pdf_set[i_idv][i_phi]>= tmp_rand:\n idv[i_idv]=phi_for_hl[i_phi]\n break\n\n pop.append(idv)\n\n return pop;\n\n\n def crossover(self,parent1,parent2,ratio_cross):\n\n num_point_cross=int(round(ratio_cross*len(parent1)))\n child1=parent1[:]\n child2=parent2[:]\n\n ''' unicross '''\n cross_template=random.sample(range(len(parent1)),num_point_cross)\n\n for i_cross in range(num_point_cross):\n child1[cross_template[i_cross]]=parent2[cross_template[i_cross]]\n child2[cross_template[i_cross]]=parent1[cross_template[i_cross]]\n\n\n ''' normal cross\n max_i=int(round(len(parent1)/(num_point_cross*2)))\n\n for i in range(max_i):\n i_st=num_point_cross*i*2\n i_en=i_st+num_point_cross\n child1[i_st:i_en]=parent2[i_st:i_en]\n child2[i_st:i_en]=parent1[i_st:i_en]\n '''\n\n\n return child1,child2,cross_template\n\n def mutation(self,parent,prob_of_mut,num_point_mut,cdf_from_pdf_set,phi_for_hl):\n\n child=parent[:];\n if random.random() < prob_of_mut:\n mut_template=random.sample(range(len(parent)),num_point_mut);\n\n for i_mut in range(num_point_mut):\n tmp_rand=random.random();\n dif_abs=[0]*len(phi_for_hl);\n for i_phi in range(len(phi_for_hl)):\n dif_abs[i_phi]=abs(cdf_from_pdf_set[mut_template[i_mut]][i_phi]-tmp_rand);\n\n\n child[mut_template[i_mut]]=phi_for_hl[dif_abs.index(min(dif_abs))];\n\n\n return child;\n","repo_name":"cctbx/cctbx_project","sub_path":"mmtbx/sisa/optimize/mod_ga.py","file_name":"mod_ga.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"46"} +{"seq_id":"6493922154","text":"from topology import *\nfrom collections import deque\n\n\nclass Solution:\n # mapping information for all the workflows, tasks <--> nodes\n # I used both terms, 'assign' and 'map' to represent task-to-node assignment\n #\n # Assumption: if n tasks exist in a workflow, these tasks should be allocated to n nodes\n # i.e. multiple tasks can be assigned to a single node, however,\n # 2 tasks cannot be assigned to a node if they belong to a workflow together\n\n id_base = 0\n topology = None\n evaluator = None\n\n def __init__(self, topology=None, evaluator=None):\n Solution.id_base += 1\n self.id = Solution.id_base\n\n # remember previous arguments for parameters 'topology' and 'evaluator'\n # Sorry. this code doesn't work now\n if topology:\n Solution.topology = self.topology = topology\n else:\n self.topology = Solution.topology\n\n if evaluator:\n Solution.evaluator = self.evaluator = evaluator\n else:\n self.evaluator = Solution.evaluator\n\n # CAUTION: these data structures should be synchronized\n # they are different views of a single logical state\n # if you change them, apply the changes to clone() method.\n self.wf_alloc = {wf: False for wf in topology.workflows}\n self.wf_to_nodes = {wf: {} for wf in topology.workflows} # ordered\n self.task_to_node = {} # n to 1\n self.node_to_tasks = {node: set() for node in topology.all_nodes} # 1 to n\n self.routing_paths = {}\n self.available_resources = {node: Resources(node.resources)\n for node in topology.all_nodes}\n\n # value, cost, fitness, or anything comparable scalar value.\n # NOTE: lazy evaluation. not up-to-date\n self.value = 0\n\n # if this variable is False, self.evaluate() will return previously calculated value\n self._require_evaluation = True\n\n def mappable(self, prev_node, task, target_node, multihop=False):\n first_task = not prev_node\n resource_ok = task.required_resources <= self.available_resources[target_node]\n visited = target_node in self.wf_to_nodes[task.workflow]\n if not multihop:\n connected = target_node in prev_node.neighbors if not first_task else True\n else:\n connected = self._is_connected(prev_node, target_node) if not first_task else True\n\n return first_task and resource_ok or \\\n not first_task and not visited and connected and resource_ok\n\n def _is_connected(self, src_node, dst_node):\n visited = {src_node}\n que = deque([src_node])\n while que:\n cur = que.popleft()\n for neighbor in cur.neighbors:\n if neighbor == dst_node:\n return True\n if neighbor not in visited:\n visited.add(neighbor)\n que.append(neighbor)\n\n return False\n\n def map(self, prev_node, task, target_node, multihop=False):\n # 'task' should be a not-assigned-task\n if task in self.task_to_node:\n return False\n\n if not self.mappable(prev_node, task, target_node, multihop):\n return False\n\n if multihop and prev_node is not None:\n path = self._route(prev_node, target_node)\n if path:\n self.routing_paths[(prev_node, target_node)] = path\n else:\n return False\n\n wf = task.workflow\n self.wf_to_nodes[wf][target_node] = True\n if len(self.wf_to_nodes[wf]) == wf.n_task:\n self.wf_alloc[wf] = True\n\n self.task_to_node[task] = target_node\n self.node_to_tasks[target_node].add(task)\n self.available_resources[target_node] -= task.required_resources\n self._require_evaluation = True\n return True\n\n def unmap(self, task):\n # 'task' should be an assigned-task\n if task not in self.task_to_node:\n return False\n\n target_node = self.task_to_node[task]\n wf = task.workflow\n\n # unmap routing path\n mapped_nodes = list(self.wf_to_nodes[wf].keys())\n if mapped_nodes[0] == target_node:\n prev_node = None\n else:\n target_idx = mapped_nodes.index(target_node)\n prev_node = mapped_nodes[target_idx - 1]\n\n if prev_node and (prev_node, target_node) in self.routing_paths:\n del self.routing_paths[(prev_node, target_node)]\n\n del self.wf_to_nodes[wf][target_node]\n self.wf_alloc[wf] = False\n del self.task_to_node[task]\n self.node_to_tasks[target_node].remove(task)\n self.available_resources[target_node] += task.required_resources\n self._require_evaluation = True\n return True\n\n def _route(self, src_node, dst_node):\n # min-hop routing\n paths =deque([[src_node]])\n while paths:\n p = paths.popleft()\n if p[-1] == dst_node:\n return p\n for neighbor in p[-1].neighbors:\n if neighbor not in p:\n paths.append(p[:] + [neighbor])\n\n return None\n\n @property\n def workflow_alloc_cnt(self):\n return sum(self.wf_alloc.values())\n\n def is_allocated(self, wf):\n return self.wf_alloc[wf]\n\n def assigned_nodes(self, workflow):\n return list(self.wf_to_nodes[workflow].keys())\n\n def evaluate(self):\n self.value = self.evaluator.evaluate(self)\n self._require_evaluation = False\n\n return self.value\n\n def clone(self):\n new_solution = Solution(self.topology, self.evaluator)\n new_solution.wf_alloc = dict(self.wf_alloc)\n new_solution.wf_to_nodes = {wf: dict(self.wf_to_nodes[wf])\n for wf in self.wf_to_nodes}\n new_solution.task_to_node = dict(self.task_to_node)\n new_solution.node_to_tasks = {node: set(self.node_to_tasks[node])\n for node in self.node_to_tasks}\n new_solution.available_resources = {node: Resources(self.available_resources[node])\n for node in self.available_resources}\n new_solution.value = self.value\n new_solution._require_evaluation = self._require_evaluation\n new_solution.routing_paths = {key:value[:] for key, value in self.routing_paths.items()}\n\n return new_solution\n\n def __lt__(self, other):\n return self.evaluator.get_best([self, other]) == other\n\n def __gt__(self, other):\n return self.evaluator.get_best([self, other]) == self\n\n def __repr__(self):\n answer = self.evaluate()\n if answer:\n return str(answer)\n else:\n return \"\"\n\n def print_allocation(self):\n print(f\"[DBG] Solution#{self.id}:\", end=' ')\n print(f\"allocated {self.workflow_alloc_cnt} of {global_params.NumOfWorkflows} workflows.\")\n print()\n for wf in self.topology.workflows:\n print(f\" {wf}({wf.n_task} tasks) : \",\n list(self.wf_to_nodes[wf].keys()))\n print()\n\n\n# an alias of 'Solution'\nclass Chromosome(Solution):\n pass\n","repo_name":"experien/DroneTaskAllococation","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":7279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"19597436625","text":"\"\"\"\n@ Author: Pky\n@ Time: 2020/1/31\n@ Software: PyCharm \n\"\"\"\nimport math\nimport numpy as np\n\n\nclass MathUtils(object):\n\n @staticmethod\n def rotate(coordinate: list, angle: float) -> list:\n radians = math.radians(angle)\n x = coordinate[0] * math.cos(radians) - math.sin(radians) * coordinate[1]\n y = coordinate[1] * math.cos(radians) + math.sin(radians) * coordinate[0]\n return [x, y]\n\n @staticmethod\n def get_angle_from_two_points(point1: list, point2: list):\n return math.degrees(math.atan2(point2[1] - point1[1], point2[0] - point1[0]))\n\n @staticmethod\n def len(vector: list):\n return math.hypot(vector[0], vector[1])\n\n @staticmethod\n def normalize(vector: list):\n length = MathUtils.len(vector)\n return [vector[0] / length, vector[1] / length]\n\n @staticmethod\n def get_angle_from_two_vectors(vector1: list, vector2: list):\n x = np.array(MathUtils.normalize(vector1))\n y = np.array(MathUtils.normalize(vector2))\n Lx = np.sqrt(x.dot(x))\n Ly = np.sqrt(y.dot(y))\n frac_up = x.dot(y)\n frac_down = Lx * Ly\n if abs(frac_up - frac_down) < 1e-5:\n return 0\n else:\n return math.degrees(np.arccos(x.dot(y) / (Lx * Ly)))\n\n @staticmethod\n def get_distance(point1: list, point2: list):\n return math.hypot(point1[0] - point2[0], point1[1] - point2[1])\n","repo_name":"HarderThenHarder/ReinforcementLearningSystem","sub_path":"utilis/MathUtils.py","file_name":"MathUtils.py","file_ext":"py","file_size_in_byte":1416,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"46"} +{"seq_id":"30998708351","text":"## Ezmsg Introduction\r\n\r\n# If this is your first time using ezmsg, you're in the right place. \r\n# This script will walk through the basics of creating a very simple \r\n# ezmsg system. ezmsg is ideal for creating modular processing \r\n# pipelines whose steps can be arranged as a directed acyclic graph. \r\n# In this script, we will walk through a very simple graph which \r\n# generates a count of numbers, adds 1 to each number, and prints to \r\n# standard output.\r\n\r\n# We will write an ezmsg Unit for each discrete step of our pipeline, \r\n# and connect them together with a System.\r\n\r\nimport ezmsg.core as ez\r\nfrom typing import AsyncGenerator\r\n\r\n# Create a message type to pass between the Units. The message type \r\n# should inherit from Message.\r\n\r\nclass CountMessage(ez.Message):\r\n value: int\r\n\r\n# We also need a way to tell the Unit how many numbers to generate.\r\n\r\nclass CountSettings(ez.Settings):\r\n iterations: int\r\n\r\n# Next, create a Unit that will generate the count. Every Unit should \r\n# contain inputs and/or outputs and at least one function which \r\n# subscribes to the inputs or publishes to the outputs.\r\n\r\n# For Count, we create an OutputStream and a publishing function which \r\n# will perform the number calculation and yield CountMessages to the \r\n# OutputStream.\r\n\r\nclass Count(ez.Unit):\r\n\r\n SETTINGS: CountSettings # Declare Settings, do not instantiate\r\n\r\n OUTPUT_COUNT = ez.OutputStream(CountMessage)\r\n\r\n @ez.publisher(OUTPUT_COUNT)\r\n async def count(self) -> AsyncGenerator:\r\n count = 0\r\n while count < self.SETTINGS.iterations:\r\n yield (self.OUTPUT_COUNT, CountMessage(\r\n value=count\r\n ))\r\n count = count + 1\r\n\r\n# The next `Unit` in the chain should accept a `CountMessage` from the \r\n# first `Unit`, add 1 to its value, and yield a new CountMessage. To \r\n# do this, we create a new `Unit` which contains a function which both \r\n# subscribes and publishes. We will connect this `Unit` to `Count` \r\n# later on, when we create a `System`.\r\n\r\n# The subscribing function will be called anytime the `Unit` receives \r\n# a message to the `InputStream` that the function subscribes to. In \r\n# this case, `INPUT_COUNT`.\r\n\r\nclass AddOne(ez.Unit):\r\n\r\n INPUT_COUNT = ez.InputStream(CountMessage)\r\n OUTPUT_PLUS_ONE = ez.OutputStream(CountMessage)\r\n\r\n @ez.subscriber(INPUT_COUNT)\r\n @ez.publisher(OUTPUT_PLUS_ONE)\r\n async def on_message(self, message) -> AsyncGenerator:\r\n yield (self.OUTPUT_PLUS_ONE, CountMessage(\r\n value=message.value + 1\r\n ))\r\n\r\n# Finally, the last unit should print the value of any messages it \r\n# receives.\r\n\r\n# Since this unit is the last in the pipeline, it should also\r\n# terminate the system when it receives the last message. We can use\r\n# `ez.NormalTermination` to let the system know that it should\r\n# gracefully shut down.\r\n\r\n# We can use both Settings and State together to count messages and\r\n# raise `ez.NormalTermination` when all have passed through.\r\n\r\nclass PrintSettings(ez.Settings):\r\n iterations: int\r\n\r\nclass PrintState(ez.State):\r\n current_iteration: int = 0\r\n\r\nclass PrintValue(ez.Unit):\r\n\r\n SETTINGS: PrintSettings\r\n STATE: PrintState\r\n\r\n INPUT = ez.InputStream(CountMessage)\r\n\r\n @ez.subscriber(INPUT)\r\n async def on_message(self, message) -> None:\r\n\r\n print(message.value)\r\n\r\n self.STATE.current_iteration = self.STATE.current_iteration + 1\r\n if self.STATE.current_iteration == self.SETTINGS.iterations:\r\n raise ez.NormalTermination\r\n\r\n# The last thing to do before we have a fully functioning ezmsg \r\n# pipeline is to define any Settings that have been declared and to \r\n# connect all of the units together. We do this using a System. The \r\n# configure() and network() functions are special functions that \r\n# define System behavior.\r\n\r\nclass CountSystemSettings(ez.Settings):\r\n iterations: int\r\n\r\nclass CountSystem(ez.System):\r\n\r\n SETTINGS: CountSystemSettings\r\n\r\n # Define member units\r\n COUNT = Count()\r\n ADD_ONE = AddOne()\r\n PRINT = PrintValue()\r\n\r\n # Use the configure function to apply settings to member Units\r\n def configure(self) -> None:\r\n self.COUNT.apply_settings(\r\n CountSettings(iterations=self.SETTINGS.iterations)\r\n )\r\n \r\n self.PRINT.apply_settings(\r\n PrintSettings(iterations=self.SETTINGS.iterations)\r\n )\r\n\r\n # Use the network function to connect inputs and outputs of Units\r\n def network(self) -> ez.NetworkDefinition:\r\n return (\r\n (self.COUNT.OUTPUT_COUNT, self.ADD_ONE.INPUT_COUNT),\r\n (self.ADD_ONE.OUTPUT_PLUS_ONE, self.PRINT.INPUT)\r\n )\r\n\r\n# Finally, instantiate and run the system!\r\n\r\nif __name__ == \"__main__\":\r\n settings = CountSystemSettings(iterations=20)\r\n system = CountSystem(settings)\r\n ez.run_system(system)","repo_name":"hannahgooden/readthedocs-sandbox","sub_path":"examples/ezmsg_intro.py","file_name":"ezmsg_intro.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"22641190455","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport facenet\nimport os\nimport sys\nimport time\nimport h5py\nimport math\nfrom tensorflow.python.platform import gfile\nfrom six import iteritems\n\ndef main(args):\n dataset = facenet.get_dataset(args.dataset_dir)\n \n with tf.Graph().as_default():\n \n # Get a list of image paths and their labels\n image_list, label_list = facenet.get_image_paths_and_labels(dataset)\n nrof_images = len(image_list)\n image_indices = range(nrof_images)\n\n image_batch, label_batch = facenet.read_and_augment_data(image_list,\n image_indices, args.image_size, args.batch_size, None, \n False, False, False, nrof_preprocess_threads=4, shuffle=False)\n \n model_exp = os.path.expanduser(args.model_file)\n with gfile.FastGFile(model_exp,'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n input_map={'input':image_batch, 'phase_train':False}\n tf.import_graph_def(graph_def, input_map=input_map, name='net')\n \n embeddings = tf.get_default_graph().get_tensor_by_name(\"net/embeddings:0\")\n\n with tf.Session() as sess:\n tf.train.start_queue_runners(sess=sess)\n \n embedding_size = int(embeddings.get_shape()[1])\n nrof_batches = int(math.ceil(nrof_images / args.batch_size))\n nrof_classes = len(dataset)\n label_array = np.array(label_list)\n class_names = [cls.name for cls in dataset]\n nrof_examples_per_class = [ len(cls.image_paths) for cls in dataset ]\n class_variance = np.zeros((nrof_classes,))\n class_center = np.zeros((nrof_classes,embedding_size))\n distance_to_center = np.ones((len(label_list),))*np.NaN\n emb_array = np.zeros((0,embedding_size))\n idx_array = np.zeros((0,), dtype=np.int32)\n lab_array = np.zeros((0,), dtype=np.int32)\n index_arr = np.append(0, np.cumsum(nrof_examples_per_class))\n for i in range(nrof_batches):\n t = time.time()\n emb, idx = sess.run([embeddings, label_batch])\n emb_array = np.append(emb_array, emb, axis=0)\n idx_array = np.append(idx_array, idx, axis=0)\n lab_array = np.append(lab_array, label_array[idx], axis=0)\n for cls in set(lab_array):\n cls_idx = np.where(lab_array==cls)[0]\n if cls_idx.shape[0]==nrof_examples_per_class[cls]:\n # We have calculated all the embeddings for this class\n i2 = np.argsort(idx_array[cls_idx])\n emb_class = emb_array[cls_idx,:]\n emb_sort = emb_class[i2,:]\n center = np.mean(emb_sort, axis=0)\n diffs = emb_sort - center\n dists_sqr = np.sum(np.square(diffs), axis=1)\n class_variance[cls] = np.mean(dists_sqr)\n class_center[cls,:] = center\n distance_to_center[index_arr[cls]:index_arr[cls+1]] = np.sqrt(dists_sqr)\n emb_array = np.delete(emb_array, cls_idx, axis=0)\n idx_array = np.delete(idx_array, cls_idx, axis=0)\n lab_array = np.delete(lab_array, cls_idx, axis=0)\n\n \n print('Batch %d in %.3f seconds' % (i, time.time()-t))\n \n print('Writing filtering data to %s' % args.data_file_name)\n mdict = {'class_names':class_names, 'image_list':image_list, 'label_list':label_list, 'distance_to_center':distance_to_center }\n with h5py.File(args.data_file_name, 'w') as f:\n for key, value in iteritems(mdict):\n f.create_dataset(key, data=value)\n \ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n \n parser.add_argument('dataset_dir', type=str,\n help='Path to the directory containing aligned dataset.')\n parser.add_argument('model_file', type=str,\n help='File containing the frozen model in protobuf (.pb) format to use for feature extraction.')\n parser.add_argument('data_file_name', type=str,\n help='The name of the file to store filtering data in.')\n parser.add_argument('--image_size', type=int,\n help='Image size.', default=160)\n parser.add_argument('--batch_size', type=int,\n help='Number of images to process in a batch.', default=90)\n return parser.parse_args(argv)\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))\n","repo_name":"davidsandberg/facenet","sub_path":"src/calculate_filtering_metrics.py","file_name":"calculate_filtering_metrics.py","file_ext":"py","file_size_in_byte":4835,"program_lang":"python","lang":"en","doc_type":"code","stars":13291,"dataset":"github-code","pt":"46"} +{"seq_id":"74967180618","text":"import time\r\nfrom machine import Pin\r\nimport sys\r\nfrom mfrc522 import MFRC522\r\n\r\nled_red = Pin(14, machine.Pin.OUT)\r\nled_green = Pin(13, machine.Pin.OUT)\r\nled_blue= Pin(12, machine.Pin.OUT)\r\nled_green.value(0)\r\nled_red.value(0)\r\nled_blue.value(0)\r\nreader = MFRC522(spi_id=0,sck=2,mosi=3,miso=4,cs=5,rst=0)\r\ncard_db=['2236835850','3111483307','2798319075']\r\n#2798319075\r\ndef toggle(obj):\r\n obj.value(1)\r\n time.sleep(0.5)\r\n obj.value(0)\r\nprint(\"OK\")\r\n\r\nwhile True:\r\n toggle(led_blue) \r\n reader.init()\r\n (stat, tag_type) = reader.request(reader.REQIDL)\r\n if stat == reader.OK:\r\n (stat, uid) = reader.SelectTagSN()\r\n if stat == reader.OK:\r\n card = int.from_bytes(bytes(uid),\"little\",False)\r\n if str(card) in card_db:\r\n toggle(led_green)\r\n else:\r\n toggle(led_red)\r\n print(str(card))\r\n \r\n \r\n v = sys.stdin.readline().strip()\r\n if v.lower() == \"..on\":\r\n print(\"...ok\")\r\n elif v.lower() == \".\":\r\n continue\r\n","repo_name":"e-manuele/badger","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"32288765100","text":"\"\"\"\nНаписать функцию, которая принимает список чисел и целое число.\nФункция должна возвращать индексы двух чисел, сумма которых равна двум.\nПредпологается, что существует только одно решение.\n\"\"\"\n\nfunc_name = \"sum_of_two\"\n\nuser_code_example = \"\"\"\ndef sum_of_two(nums, target):\n numToIndex = {}\n for i in range(len(nums)):\n if target - nums[i] in numToIndex:\n return [numToIndex[target - nums[i]], i]\n numToIndex[nums[i]] = i\n return []\n\"\"\"\n\n\ndef sum_of_two(nums, target):\n numToIndex = {}\n for i in range(len(nums)):\n if target - nums[i] in numToIndex:\n return [numToIndex[target - nums[i]], i]\n numToIndex[nums[i]] = i\n return []\n\n\ntest_cases = [\n (([2, 7, 11, 15], 9), [0, 1]),\n (([3, 2, 4], 6), [1, 2]),\n (([3, 3], 6), [3, 3])\n]\n","repo_name":"Samogonn/tasks_for_compilator","sub_path":"testing/sum_of_two.py","file_name":"sum_of_two.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"23109958010","text":"#! /usr/bin/env python3\n\"\"\"\nIn this module, we implemented the class Equation which represents '1/x - 1/(x + 1) = 1/(x * (x + 1))'.\nEach instance of this class is initalized with a fixed mantissa length to evaluate both side of this\nequation in order to observe the effect of decimal rounding in the floating point arithmetic.\n\nFurtheremore, we provided a function which approximates machine epsilon for a given floating type such as\nnp.float16.\n\nforged by:\n Christian Parpart\n Kei Thoma (574 613)\n\nThis file is part of the \"The Lost World between Zero and Machine Epsilon\" project.\n(c) 2019 Christian Parpart \n(c) 2019 Kei Thoma \nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the\nLicense. You may obtain a copy of the License at: http://opensource.org/licenses/MIT\n\"\"\"\n\nimport decimal\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.use('TkAgg')\n\n\n# for ease of use\nD = decimal.Decimal\n\n\n# ----------------------------------------------------------------------------------------------------------\n# EXERCISE 3\n# ----------------------------------------------------------------------------------------------------------\n\n\nclass Equation:\n \"\"\"\n This is more of an auxiliary class to store the given equation '1/x - 1/(x + 1) = 1/(x * (x + 1))', and\n the two formulas which returns the absolute and the relative error. He can also draw graphs for both of\n the errors.\n\n Attributes:\n precision_ (int): the precision set for the whole Equation object; every term inside of an Equation\n object adheres to this precision; note that this attribute should be private and must not be changed\n unless 'change_precision(self, _precision)' is called\n\n equation_context_ (Context): this is the Context object from the decimal library with its 'prec'\n attribute to 'precision_' (see above); again this attribute should be private\n\n Methods:\n change_precision(self, _precision): changes the precision for the Equation object\n\n left_side(self, _x): the left side of the equation, '1/x - 1/(x + 1)'\n\n right_side(self, _x): the right side of the equation, '1/(x * (x + 1))'\n\n absolute_error(self, _x): the absolute difference of 'left_side(self, _x)' and 'right_side(self,\n _x)'\n\n relative_error(self, _x): the relative difference of 'left_side(self, _x)' and 'right_side(self,\n _x)'\n\n draw_absolute_error(self, _x): draws an two dimensional graph of 'absolute_error(self, _x)' for a\n fixed x using matplotlib\n\n draw_relative_error(self, _x): draws an two dimensional graph of 'relative_error(self, _x)' for a\n fixed x using matplotlib\n \"\"\"\n def __init__(self, _precision=28):\n \"\"\"\n She constructs an equation object with respect to the desired precision.\n\n Arguments:\n _precision (int): the precision for the decimal.Decimal object; must not be zero or negative; is\n directly stored under 'precision_'; the default value is 28, the same as the default value in\n the decimal library\n\n Returns:\n nothing\n\n Raises:\n ValueError: if zero or negative values are passed as '_precision'\n \"\"\"\n if _precision < 1:\n raise ValueError(\"Class Equation: The precision must not be 0 or negative.\")\n\n # set precision for the equation object locally\n self.precision_ = _precision\n self.equation_context_ = decimal.Context(_precision)\n\n\n def change_precision(self, _precision):\n \"\"\"\n Since merely changing the 'precision_' attribute from the outside won't do anything, this methods\n allows the user to change the precision for a given object by correctly changing the 'prec'\n attribute of the Context object\n\n Arguments:\n _precision (int): the precision for the decimal.Decimal object; must not be zero or negative; is\n directly stored under 'precision_'\n\n Returns:\n nothing\n\n Raises:\n ValueError: if zero or negative values are passed as '_precision'\n \"\"\"\n if _precision < 1:\n raise ValueError(\"Class Equation: The precision must not be 0 or negative.\")\n\n self.precision_ = _precision\n self.equation_context_.prec = _precision\n\n\n def left_side(self, _x):\n \"\"\"\n She represents the left side of the equation '1/x - 1/(x + 1)'.\n\n Arguments:\n _x (int): the value for x; 0 and -1 are not allowed and this function will naturally raise a\n ZeroDivisionError\n\n Returns:\n (Decimal): the solution for the left side of the equation\n \"\"\"\n with decimal.localcontext(self.equation_context_):\n return (D('1') / D(str(_x))) - D('1') / (D(str(_x)) + D('1'))\n\n\n def right_side(self, _x):\n \"\"\"\n She represents the left side of the equation '1/x - 1/(x + 1)'.\n\n Arguments:\n _x (int): the value for x; 0 and -1 are not allowed and this function will naturally raise a\n ZeroDivisionError\n\n Returns:\n (Decimal): the solution for the right side of the equation\n \"\"\"\n with decimal.localcontext(self.equation_context_):\n return D('1') / (D(str(_x)) * (D(str(_x)) + D('1')))\n\n\n def absolute_error(self, _x):\n \"\"\"\n This methods computes the absolute difference between 'left_side(self, _x)' and 'right_side(self,\n _x)'.\n\n Arguments:\n _x (int): the value for x for the equation\n\n Returns:\n (Decimal): the absolute difference between both side of the equation\n \"\"\"\n with decimal.localcontext(self.equation_context_):\n return abs(self.left_side(_x) - self.right_side(_x))\n\n\n def relative_error(self, _x):\n \"\"\"\n This methods computes the relative difference between 'left_side(self, _x)' and\n 'right_side(self, _x)'.\n\n Arguments:\n _x (int): the value for x for the equation\n\n Returns:\n (Decimal): the relative difference between both side of the equation\n \"\"\"\n with decimal.localcontext(self.equation_context_):\n return abs((self.left_side(_x) - self.right_side(_x)) / self.right_side(_x))\n\n\n\n def draw_absolute_error(self, _x):\n \"\"\"\n She draws a two dimensional graph of the absolute error of the equation for a fixed x depending on\n the mantissa length.\n\n Arguments:\n _x (int): the fixed x for which the graph is drawn\n\n Returns:\n nothing\n \"\"\"\n # values for the x-axis (mantissa length)\n x_axis = np.arange(1, 28, 1)\n\n # values for the y-axis (absolute error)\n y_axis = []\n for significand in x_axis:\n self.change_precision(int(significand))\n y_axis.append(self.absolute_error(_x))\n\n # draw\n fig = plt.figure()\n axe = fig.add_subplot(1, 1, 1)\n\n axe.set_title(\"absolute error for x = \" + str(_x))\n axe.set_xlabel(\"mantissa length\")\n axe.set_ylabel(\"absolute error\")\n\n plt.semilogy(x_axis, y_axis)\n plt.show()\n\n\n def draw_relative_error(self, _x):\n \"\"\"\n She draws a two dimensional graph of the relative error of the equation for a fixed x depending on\n the mantissa length.\n\n Arguments:\n _x (int): the fixed x for which the graph is drawn\n\n Returns:\n nothing\n \"\"\"\n # values for the x-axis (mantissa length)\n x_axis = np.arange(1, 28, 1)\n\n # values for the y-axis (relative error)\n y_axis = []\n for significand in x_axis:\n self.change_precision(int(significand))\n y_axis.append(self.relative_error(_x))\n\n # draw\n fig = plt.figure()\n axe = fig.add_subplot(1, 1, 1)\n\n axe.set_title(\"relative error for x = \" + str(_x))\n axe.set_xlabel(\"mantissa length\")\n axe.set_ylabel(\"relative error\")\n\n plt.semilogy(x_axis, y_axis)\n plt.show()\n\n\n def draw_errors_together(self, _x):\n \"\"\"\n She draws a two dimensional graph of both errors togehter.\n\n Arguments:\n _x (int): the fixed x for which the graph is drawn\n\n Returns:\n nothing\n \"\"\"\n # values for the x-axis (mantissa length)\n x_axis = np.arange(1, 28, 1)\n\n # values for the y-axis\n absolute_error_axis = []\n relative_error_axis = []\n for significand in x_axis:\n self.change_precision(int(significand))\n absolute_error_axis.append(self.absolute_error(_x))\n relative_error_axis.append(self.relative_error(_x))\n\n # draw\n fig = plt.figure()\n axe = fig.add_subplot(1, 1, 1)\n\n axe.set_title(\"relative error for x = \" + str(_x))\n axe.set_xlabel(\"mantissa length\")\n axe.set_ylabel(\"relative error\")\n\n plt.semilogy(x_axis, absolute_error_axis)\n plt.semilogy(x_axis, relative_error_axis)\n plt.show()\n\n\n# ----------------------------------------------------------------------------------------------------------\n# EXERCISE 2\n# ----------------------------------------------------------------------------------------------------------\n\n\ndef explore_machine_epsilon(float_type):\n \"\"\"\n This little algorithm tries to find the machine precision of the given float type, such as np.float16,\n iterativly.\n\n Arguments:\n float_type (class): the class for the float type we want to inspect e.g. np.float32;\n\n Returns:\n epsilon (float_type): the machine precision; its data type corresponds to the data type passed\n as the argument\n \"\"\"\n epsilon = float_type(1.0)\n\n while float_type(1.0 + epsilon * 0.5) != 1.0:\n epsilon = float_type(epsilon * 0.5)\n\n return epsilon\n\ndef main():\n \"\"\"\n She is our main-function. Use the switch, 'test_switch', to test various capabilities of this module.\n (See the docstring for more information.)\n \"\"\"\n # set here what to test\n test_switch = {'epsilon': False, 'equation': False, 'draw': True}\n\n print(globals()['__doc__'])\n\n # test here the machine precision of different data types\n if test_switch['epsilon']:\n float_type_list = (np.float16, np.float32, np.float64)\n\n print(\"In the following we print out for each given floating type the name of the type, the\" +\n \"precision found by the algorithm (see explore_machine_epsilon(float_type), the actual\" +\n \"precision given by numpy native function 'finfo()' and finally the precision given by the\" +\n \"formula eps = 7 / 3 - 4 / 3 - 1')\")\n print(\"\\n\\n\")\n\n for each in float_type_list:\n # the following is an alternative way to calculate the machine precision; for the validity of\n # this formula see the documentation\n alternative = each(abs(each(7 / 3) - each(4 / 3) - each(1.0)))\n\n # padding in the second line added for readability\n # \"__name__\" returns the name of the class; such as \"np.float16\"\n print(\"The machine epsilon for {0} is:\".format(each.__name__))\n print(\" {0}\".format(explore_machine_epsilon(each)))\n print(\"it should be: {0}\".format(np.finfo(each).eps))\n print(\"alternativly: {0}\\n\".format(alternative))\n\n print(\"\\n\\n\")\n\n # test here the Equation class\n if test_switch['equation']:\n print(\"Now we will test the class Equation.\")\n print(\"\\n\\n\")\n\n obj1 = Equation(2)\n obj2 = Equation(8)\n\n for number in range(1, 21):\n print(\"x = {0}\\n\".format(number))\n print(\"precision: {0}\".format(obj1.precision_))\n print(\"left side: {0}\".format(obj1.left_side(number)))\n print(\"right side: {0}\".format(obj1.right_side(number)))\n print(\"abs error: {0}\".format(obj1.absolute_error(number)))\n print(\"rel error: {0}\".format(obj1.relative_error(number)))\n print()\n print(\"precision: {0}\".format(obj2.precision_))\n print(\"left side: {0}\".format(obj2.left_side(number)))\n print(\"right side: {0}\".format(obj2.right_side(number)))\n print(\"abs error: {0}\".format(obj2.absolute_error(number)))\n print(\"rel error: {0}\".format(obj2.relative_error(number)))\n print(\"\\n--------------------\\n\")\n\n print(\"\\n\\n\")\n\n # here, we draw the graphs for the absolute and the relative errors\n if test_switch['draw']:\n draw_graph_x = 5\n print(\"We will draw the graph for x = {0}\".format(draw_graph_x))\n obj3 = Equation()\n obj3.draw_absolute_error(draw_graph_x)\n obj3.draw_relative_error(draw_graph_x)\n print(\"\\n\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"keithoma/EWR","sub_path":"worksheet4/application/tools4.py","file_name":"tools4.py","file_ext":"py","file_size_in_byte":13032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"6709501166","text":"# coding:utf-8\n\nimport zlib\nimport struct\nimport json\nimport random\nimport logging\nimport threading\nfrom time import sleep\nfrom io import BytesIO\nfrom gzip import GzipFile\nfrom .GlobalConfig import GC\nfrom .FilterUtil import get_action\nfrom .HTTPUtil import http_cfw\nfrom .common.dns import dns, dns_resolve\nfrom .common.net import explode_ip\n\n# IP 数相比请求数极为巨大,无需重复连接同一 IP\nhttp_cfw.max_per_ip = 1\nlock = threading.Lock()\ncfw_iplist = []\n\nclass cfw_params:\n port = 443\n ssl = True\n command = 'POST'\n host = GC.CFW_WORKER\n path = '/gh'\n url = 'https://%s%s' % (host, path)\n hostname = 'cloudflare_workers|'\n connection_cache_key = '%s:%d' % (hostname, port)\n\nclass cfw_ws_params(cfw_params):\n command = 'GET'\n path = '/ws'\n\ncfw_options = {}\nif GC.CFW_PASSWORD:\n cfw_options['password'] = GC.CFW_PASSWORD\nif GC.CFW_DECODEEMAIL:\n cfw_options['decodeemail'] = GC.CFW_DECODEEMAIL\ncfw_options_str = json.dumps(cfw_options)\n\ndef set_dns():\n if dns.gettill(cfw_params.hostname):\n return\n dns.setpadding(cfw_params.hostname)\n if not cfw_iplist:\n if GC.CFW_IPLIST:\n iplist = GC.CFW_IPLIST\n else:\n iplist = dns_resolve('cloudflare.com')\n if not iplist:\n logging.warning('无法解析 cloudflare.com,使用默认 IP 列表')\n # https://www.cloudflare.com/ips/\n # 百度云加速与 CloudFlare 合作节点,保证可用\n iplist = ['162.159.208.0', '162.159.209.0', '162.159.210.0', '162.159.211.0']\n # 每个 IP 会自动扩展为 256 个,即填满最后 8 bit 子网\n cfw_iplist[:] = sum([explode_ip(ip) for ip in iplist], [])\n random.shuffle(cfw_iplist)\n dns.set(cfw_params.hostname, cfw_iplist, expire=False)\n\ndef check_response(response, host):\n if response:\n if response.headers.get('Server') == 'cloudflare':\n if response.headers.get('X-Fetch-Status'): # ok / fail\n return 'ok'\n elif response.status == 429:\n # https://developers.cloudflare.com/workers/about/limits/\n # a burst rate limit of 1000 requests per minute.\n if lock.acquire(timeout=1):\n try:\n logging.warning('CFW %r 超限,暂停使用 30 秒', cfw_params.host)\n sleep(30)\n finally:\n lock.release()\n elif response.status == 302 or 400 <= response.status < 500 or \\\n response.status == 530 and dns_resolve(host):\n # https://support.cloudflare.com/hc/zh-cn/articles/360029779472-Cloudflare-1XXX-错误故障排除\n # https://support.cloudflare.com/hc/zh-cn/articles/115003011431-Cloudflare-5XX-错误故障排除\n with lock:\n try:\n cfw_iplist.remove(response.xip[0])\n logging.test('CFW 移除 %s', response.xip[0])\n except:\n pass\n elif response.status in (500, 530):\n return 'ok'\n else:\n #打印收集未知异常状态\n logging.warning('CFW %r 工作异常:%d %s',\n cfw_params.host, response.status, response.reason)\n return 'ok'\n else:\n logging.error('CFW %r 工作异常:%r 可能不是可用的 CloudFlare 节点',\n cfw_params.host, response.xip[0])\n return 'retry'\n else:\n logging.test('CFW %r 连接失败', cfw_params.host)\n return 'fail'\n\ndef cfw_ws_fetch(host, url, headers):\n options = cfw_options.copy()\n options['url'] = 'http' + url[2:]\n headers.update({\n 'Host': cfw_params.host,\n 'X-Fetch-Options': json.dumps(options),\n })\n realurl = 'CFW-' + url\n while True:\n response = http_cfw.request(cfw_ws_params, headers=headers,\n connection_cache_key=cfw_params.connection_cache_key,\n realurl=realurl)\n if check_response(response, host) == 'retry':\n continue\n return response\n\ndef cfw_fetch(method, host, url, headers, payload=b'', options=None):\n set_dns()\n with lock:\n pass\n if url[:2] == 'ws':\n return cfw_ws_fetch(host, url, headers)\n ae = headers.get('Accept-Encoding', '')\n if 'Range' in headers and 'gzip' not in ae:\n ae += ', gzip'\n headers['Accept-Encoding'] = ae\n if 'gzip' not in ae and 'br' not in ae:\n ae = 'gzip'\n metadata = ['%s %s' % (method, url)]\n metadata += ['%s\\t%s' % header for header in headers.items()]\n metadata = '\\n'.join(metadata).encode()\n metadata = zlib.compress(metadata)[2:-4]\n if hasattr(payload, 'read'):\n payload = payload.read()\n if payload:\n if not isinstance(payload, bytes):\n payload = payload.encode()\n payload = struct.pack('!h', len(metadata)) + metadata + payload\n else:\n payload = struct.pack('!h', len(metadata)) + metadata\n if options:\n _options = cfw_options.copy()\n _options.update(options)\n options_str = json.dumps(_options)\n else:\n options_str = cfw_options_str\n request_headers = {\n 'Host': cfw_params.host,\n 'User-Agent': 'GotoX/ls/0.4',\n 'Accept-Encoding': ae,\n 'Content-Length': str(len(payload)),\n 'X-Fetch-Options': options_str,\n }\n realurl = 'CFW-' + url\n while True:\n response = http_cfw.request(cfw_params, payload, request_headers,\n connection_cache_key=cfw_params.connection_cache_key,\n realmethod=method,\n realurl=realurl)\n status = check_response(response, host)\n if status == 'ok':\n response.http_util = http_cfw\n response.connection_cache_key = cfw_params.connection_cache_key\n if response.status == 206 and response.headers.get('Content-Encoding') == 'gzip':\n if response.headers['Content-Range'].startswith('bytes 0-'):\n response.fp = gzipfp = GzipFile(fileobj=BytesIO(response.read()))\n response.length = length = len(gzipfp.read())\n response.headers.replace_header('Content-Range', f'bytes 0-{length - 1}/{length}')\n del response.headers['Content-Encoding']\n gzipfp.rewind()\n else:\n response.status = 501\n response.reason = 'Not Implemented'\n content = b'CloudFlare Workers not support gziped response returned by range request which not starts with zero.'\n response.fp = BytesIO(content)\n response.length = len(content)\n elif status == 'retry':\n continue\n return response\n","repo_name":"aqssxlzc/gotox_docker","sub_path":"GotoX-3.6.2-cp38-win_amd64/local/CFWFetch.py","file_name":"CFWFetch.py","file_ext":"py","file_size_in_byte":7035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"70929377411","text":"import os\nimport pytest\nimport tempfile\n\nfrom distutils.version import LooseVersion\nfrom f5.bigip.tm.asm.policies.extractions import Extraction\nfrom f5.sdk_exception import MissingRequiredCreationParameter\nfrom requests.exceptions import HTTPError\n\n\n@pytest.fixture(scope='function')\ndef set_extraction(policy):\n file = tempfile.NamedTemporaryFile()\n name = os.path.basename(file.name)\n r1 = policy.extractions_s.extraction.create(\n extractFromAllItems=True,\n name=name\n )\n yield r1\n r1.delete()\n\n\n@pytest.mark.skipif(\n LooseVersion(pytest.config.getoption('--release')) < LooseVersion('11.6.0'),\n reason='This collection is fully implemented on 11.6.0 or greater.'\n)\nclass TestExtractions(object):\n def test_create_req_arg(self, policy):\n file = tempfile.NamedTemporaryFile()\n name = os.path.basename(file.name)\n r1 = policy.extractions_s.extraction.create(\n extractFromAllItems=True,\n name=name\n )\n assert r1.kind == 'tm:asm:policies:extractions:extractionstate'\n r1.delete()\n\n def test_create_mandatory_arg_missing(self, policy2):\n file = tempfile.NamedTemporaryFile()\n name = os.path.basename(file.name)\n with pytest.raises(MissingRequiredCreationParameter) as err:\n policy2.extractions_s.extraction.create(\n extractFromAllItems=False,\n name=name\n )\n\n assert 'This resource requires at least one of the' in str(err.value)\n\n def test_create_mandatory_arg_present(self, policy2):\n file = tempfile.NamedTemporaryFile()\n name = os.path.basename(file.name)\n r1 = policy2.extractions_s.extraction.create(\n extractFromAllItems=False,\n name=name,\n extractFromRegularExpression='[\"test\"]')\n assert r1.kind == 'tm:asm:policies:extractions:extractionstate'\n assert r1.extractFromRegularExpression == '[\"test\"]'\n assert r1.extractFromAllItems is False\n r1.delete()\n\n def test_refresh(self, set_extraction, policy):\n r1 = set_extraction\n r2 = policy.extractions_s.extraction.load(id=r1.id)\n assert r1.kind == r2.kind\n assert r1.extractFromAllItems == r2.extractFromAllItems\n assert r1.searchInXml == r2.searchInXml\n r2.modify(searchInXml=True)\n assert r1.searchInXml is False\n assert r2.searchInXml is True\n r1.refresh()\n assert r1.searchInXml is True\n\n def test_delete(self, policy):\n file = tempfile.NamedTemporaryFile()\n name = os.path.basename(file.name)\n r1 = policy.extractions_s.extraction.create(\n extractFromAllItems=True,\n name=name\n )\n idhash = r1.id\n r1.delete()\n with pytest.raises(HTTPError) as err:\n policy.extractions_s.extraction.load(id=idhash)\n assert err.value.response.status_code == 404\n\n def test_load_no_object(self, policy):\n with pytest.raises(HTTPError) as err:\n policy.extractions_s.extraction.load(id='Lx3553-321')\n assert err.value.response.status_code == 404\n\n def test_load(self, set_extraction, policy):\n r1 = set_extraction\n assert r1.kind == 'tm:asm:policies:extractions:extractionstate'\n assert r1.searchInXml is False\n r1.modify(searchInXml=True)\n assert r1.searchInXml is True\n r2 = policy.extractions_s.extraction.load(id=r1.id)\n assert r1.kind == r2.kind\n assert r1.searchInXml == r2.searchInXml\n\n def test_extractions_subcollection(self, policy, set_extraction):\n r1 = set_extraction\n assert r1.kind == 'tm:asm:policies:extractions:extractionstate'\n cc = policy.extractions_s.get_collection()\n assert isinstance(cc, list)\n assert len(cc)\n assert isinstance(cc[0], Extraction)\n","repo_name":"F5Networks/f5-common-python","sub_path":"f5/bigip/tm/asm/policies/test/functional/test_extractions.py","file_name":"test_extractions.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","stars":258,"dataset":"github-code","pt":"43"} +{"seq_id":"72593684611","text":"\n# python round() : rounds a no. to specified decimals.\n# the round() function returns a floating point no. rounded to the specified no.\n# of decimals\n\n\n\"\"\"\n\n# e.g. 1: how round() works in python\n\n# for integers\nprint(round(10))\n\n# for floating point\nprint(round(10.7))\n\n# even choice\nprint(round(5.5))\n\n\"\"\"\n\n\n\"\"\"\n\n# e.g. 2: round a no. to the given no. of decimal places\n\nprint(round(2.665, 2))\nprint(round(2.675, 2))\n\n\"\"\"\n\n\n# For precision: use a module named as decimal\n\nfrom decimal import Decimal\n\n# normal float\nnum = 2.675\nprint(round(num, 2))\n\n# using decimal.Decimal (passed float as string for precision)\nnum = Decimal('2.675')\nprint(round(num, 2))\n\n\n\n\n","repo_name":"avengerryan/daily_practice_codes","sub_path":"nine_sept/programiz_builtin_funcs/python_round.py","file_name":"python_round.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"36763074237","text":"def sottoseq(stringa,somma):\n vocali=\"aeiou\"\n if len(stringa)==0:\n return 0\n for i in range(len(stringa)-1):\n if (stringa[i]in vocali and stringa[i+1] in vocali) or (stringa[i]not in vocali and stringa[i+1]not in vocali):\n somma+=1\n return somma\ndef main():\n n=input()\n stringa=\"\"\n while n!=\".\":\n stringa+=n\n n=input()\n print(sottoseq(stringa, 1))\nmain()\n\n","repo_name":"Antoo22D/Exercisce_Python_UNIVERSITY","sub_path":"N24.py","file_name":"N24.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"2017543980","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 8 13:30:04 2018\n\n@author: z3525552\n\"\"\"\n\ndef alternative_theme(alternative_subjects):\n\n from collections import defaultdict\n result = defaultdict(set)\n\n themes = {'Cancer' : {'Cancer Research','Oncology', 'Cancer', 'Radiation', 'Oncology(nursing)'} ,\n 'Triple I' : {'Endocrinology','Immunology and Microbiology','Immunology', 'Microbiology',\n 'Parasitology', 'Virology', 'Dermatology', 'Allergy', 'Infectious Diseases',\n 'Rheumatology', 'Toxicology'},\n 'NMHA' : {'Clinical Neurology','Psychiatry and Mental Health', 'General Neuroscience',\n 'Neuroscience (miscellaneous)' , 'Behavioral Neuroscience', \n 'Biological Psychiatry','Cellular and Molecular Neuroscience','Cognitive Neuroscience',\n 'Developmental Neuroscience', 'Neurology' ,'Phychiatric Mental Health','Psychology (miscellaneous)',\n 'Experimental and Cognitive Psychology', 'Neuropsychology and Physiological Psychology'},\n 'NCD' : {'Cardiology', 'Cardiovascular Medicine','Cardiology and Cardiovascular Medicine',\n 'Endocrinology, Diabetes and Metabolism',\n 'Pulmonary and Respiratory Medicine'}}\n\n\n for key in themes:\n if not themes[key].isdisjoint(alternative_subjects):\n result[key] = themes[key]&alternative_subjects\n \n alternative = max(result, key=lambda k: len(result[k]))\n \n return alternative","repo_name":"sudpaul/Research_Intelligence","sub_path":"scopus_api_retrive/theme_alternatives_version.py","file_name":"theme_alternatives_version.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"7918279564","text":"from django.shortcuts import render\nfrom .models import Post, Category\nfrom .forms import PostForm, CategoryForm\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\nfrom django.urls import reverse_lazy\nimport requests\nimport pandas as pd\nimport datetime as dt\nimport plotly.graph_objects as go\nfrom binance.client import Client\nfrom . import bin_api\n\n\ndef main(request):\n return render(request, 'blog/main.html', {})\n\n\ndef admin(request):\n return render(request, 'blog/admin.html', {})\n\n\ndef portfolio(request):\n return render(request, 'blog/portfolio.html', {})\n\n\ndef crypto(request):\n json_data = requests.get(\n 'https://api.binance.com/api/v3/ticker/price').json()\n # df = pd.DataFrame(json_data)\n\n btc_price = round(float(json_data[11]['price']), 2)\n eth_price = round(float(json_data[12]['price']), 2)\n xmr_price = round(float(json_data[480]['price']), 2)\n\n return render(request, 'blog/crypto.html', {\n 'btc_price': btc_price,\n 'eth_price': eth_price,\n 'xmr_price': xmr_price,\n # 'df':df\n })\n\n\ndef crypto_trades(request):\n trades_df = bin_api.latest_trades()\n html_df = trades_df.to_html()\n\n return render(request, 'blog/crypto_trades.html', {\n 'trades_df': trades_df,\n 'html_df': html_df,\n })\n\n\ndef crypto_all(request):\n json_data = requests.get(\n 'https://api.binance.com/api/v3/ticker/price').json()\n\n btc_list = []\n eth_list = []\n bnb_list = []\n eur_list = []\n usdt_list = []\n\n for coin in json_data:\n if coin['symbol'].endswith('BTC'):\n coin['symbol'] = coin['symbol'][slice(3)]\n btc_list.append(coin)\n\n elif coin['symbol'].endswith('ETH'):\n coin['symbol'] = coin['symbol'][slice(3)]\n eth_list.append(coin)\n\n elif coin['symbol'].endswith('BNB'):\n coin['symbol'] = coin['symbol'][slice(3)]\n bnb_list.append(coin)\n\n elif coin['symbol'].endswith('EUR'):\n coin['symbol'] = coin['symbol'][slice(3)]\n coin['price'] = round(float(coin['price']), 2)\n eur_list.append(coin)\n\n elif coin['symbol'].endswith('USDT'):\n coin['symbol'] = coin['symbol'][slice(-4)]\n coin['price'] = round(float(coin['price']), 2)\n usdt_list.append(coin)\n\n return render(request, 'blog/crypto_all.html', {\n 'btc_list': btc_list,\n 'eth_list': eth_list,\n 'bnb_list': bnb_list,\n 'eur_list': eur_list,\n 'usdt_list': usdt_list,\n })\n\n\ndef btc_chart(request):\n market = 'BTCUSDT'\n tick_interval = '1d'\n\n url = 'https://api.binance.com/api/v3/klines?symbol=' + \\\n market+'&interval='+tick_interval\n data = requests.get(url).json()\n\n df = pd.DataFrame(data)\n df = df.drop(columns=[7, 8, 9, 10, 11])\n df.columns = ['open_time', 'open', 'high',\n 'low', 'close', 'volume', 'close_time']\n\n df['open_time'] = [dt.datetime.fromtimestamp(i / 1000.0) for i in df['open_time']]\n df['close_time'] = [dt.datetime.fromtimestamp(i / 1000.0) for i in df['close_time']]\n\n df.index = df['close_time']\n df.index.name = 'date'\n\n fig = go.Figure(data=[go.Candlestick(\n x=df.index,\n open=df.open,\n high=df.high,\n low=df.low,\n close=df.close)])\n\n fig.update_layout(\n title='BTC Historic Price Chart'\n )\n\n chart = fig.to_html(full_html=False, default_height=800,\n default_width='100%')\n\n return render(request, 'blog/btc_chart.html', {\n 'chart': chart\n })\n\n\nclass PostList(ListView):\n model = Post\n template_name = 'blog/post_list.html'\n ordering = ['-created_date']\n\n\nclass PostText(DetailView):\n model = Post\n # context_object_name = 'post'\n template_name = 'blog/post_text.html'\n\n\nclass PostAdd(CreateView):\n model = Post\n form_class = PostForm\n template_name = 'blog/post_add.html'\n # fields = '__all__'\n\n\nclass PostUpdate(UpdateView):\n model = Post\n form_class = PostForm\n template_name = 'blog/post_update.html'\n # fields = ['title', 'title_tag', 'lead', 'text']\n\n\nclass PostDelete(DeleteView):\n model = Post\n template_name = 'blog/post_delete.html'\n success_url = reverse_lazy('post_list')\n\n\nclass CategoryAdd(CreateView):\n model = Category\n form_class = CategoryForm\n template_name = 'blog/category_add.html'\n # fields = '__all__'\n","repo_name":"Sandmann11/Django-playground","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"22846213985","text":"class ComplexNumber:\n def __init__ (self,r,i):\n self._real = r\n self._imag = i\n print(\"__init__:\", __name__)\n\n def __repr__(self):\n string = \"\"\n string += str(self._real) + \"+i\" + str(self._imag)\n print(\"repr function: \", __name__)\n \n return string\n\nprint(\"CNF:\", __name__)\nprint(1+2)","repo_name":"sowmyamanojna/BT3051-Data-Structures-and-Algorithms","sub_path":"quiz1/ComplexNumberFile.py","file_name":"ComplexNumberFile.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"23185014189","text":"\"\"\"\nДля каждого упражнения написать программную реализацию.\n\nКод пишите в файлах с расширением .py в кодировке UTF-8 (в PyCharm работает по умолчанию).\nКаждую задачу необходимо сохранять в отдельный файл. Рекомендуем использовать английские имена, например, les_6_task_1, les_6_task_2, и т.д.\nДля оценки «Отлично» необходимо выполнить все требования, указанные в задании и примечаниях.\n1. Подсчитать, сколько было выделено памяти под переменные в ранее разработанных программах в рамках первых трех уроков.\nПроанализировать результат и определить программы с наиболее эффективным использованием памяти.\nПримечание: По аналогии с эмпирической оценкой алгоритмов идеальным решением будет:\na. выбрать хорошую задачу, которую имеет смысл оценивать по памяти;\nb. написать 3 варианта кода (один у вас уже есть);\nпроанализировать 3 варианта и выбрать оптимальный;\nc. результаты анализа (количество занятой памяти в вашей среде разработки) вставить в виде комментариев в файл с кодом.\nНе забудьте указать версию и разрядность вашей ОС и интерпретатора Python;\nd. написать общий вывод: какой из трёх вариантов лучше и почему.\nНадеемся, что вы не испортили программы, добавив в них множество sys.getsizeof после каждой переменной,\nа проявили творчество, фантазию и создали универсальный код для замера памяти.\n\"\"\"\nimport sys\nfrom types import ModuleType\n\nimport platform\nfrom distutils import util\n\nprint(sys.version_info)\n# sys.version_info(major=3, minor=8, micro=1, releaselevel='final', serial=0)\n\nprint(platform.python_version())\n# 3.8.1\n\nprint(sys.platform)\n# darwin\n\nprint(util.get_platform())\n# macosx-10.9-x86_64\n\nprint(platform.architecture())\n# ('64bit', '')\n\n\"\"\"\n1.4. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят, и сколько между ними наход��тся букв.\n\"\"\"\ndef f(*qwarks):\n sum_size =0\n count = 0\n for i in qwarks:\n count+=1\n print(f'Переменная {count}: type = {type(i)}, size = {sys.getsizeof(i)}, object = {i}')\n sum_size += sys.getsizeof(i)\n return sum_size\n\nletters = 'abcdefghijklmnopqrstuvwxyz'\nletter_range = input('Введите диапазон символов от a до z через запятую: ').split(',')\n#print(letter_range)\na = letters.index(letter_range[0]) + 1\nb = letters.index(letter_range[1]) + 1\nc = b - a\n#print('Первая буква: {} - находится на {} позиции \\nВторая буква: {} - находится на {} позиции\\nРасстояние между ними {}'.format(letter_range[0], a, letter_range[1], b, c))\n\nprint(f'Переменные в сумме занимают {f(letters, letter_range, a, b,c)}')\n\n\n\"\"\"\n1 вариант\nВведите диапазон символов от a до z через запятую: a,z\nПеременная 1: type = , size = 75, object = abcdefghijklmnopqrstuvwxyz\nПеременная 2: type = , size = 152, object = ['a', 'z']\nПеременная 3: type = , size = 28, object = 1\nПеременная 4: type = , size = 28, object = 26\nПеременная 5: type = , size = 28, object = 25\nПеременные в сумме занимают 311\n2 вариант\nВведите диапазон символов от a до z через запятую: a,c\nПеременная 1: type = , size = 75, object = abcdefghijklmnopqrstuvwxyz\nПеременная 2: type = , size = 152, object = ['a', 'c']\nПеременная 3: type = , size = 28, object = 1\nПеременная 4: type = , size = 28, object = 3\nПеременная 5: type = , size = 28, object = 2\nПеременные в сумме занимают 311\nВывод: количество занимаемой памяти не зависит от диапазона символов.\n\nВывод: Данная программа наиболее эффективная по использованию памяти. Далее коды будут написаны в файлах task_1_1_2 и task_1_1_3\n\"\"\"\n","repo_name":"AShipkov/AShipkov-Python-Algorithms-and-Data-Structures","sub_path":"lesson_6/task1_1.py","file_name":"task1_1.py","file_ext":"py","file_size_in_byte":5216,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"15201099566","text":"'''\n3개의 수의 값이 0이 되는 데이터의 인덱스 조회\n(배열의 데이터는 중복되지 않음)\n\n입력: [-1, 0, 1, 2, -4]\n출력: [[-1, 0, 1]]\n'''\n\nfrom itertools import combinations\n\n\ndef threeNums(li) -> list:\n result = []\n temp = list(combinations(li, 3))\n # print(temp)\n for tmp in temp:\n # print(tmp)\n # print(sum(tmp))\n if sum(tmp) == 0:\n result.append(tmp)\n return result\n\n\ndata1 = [-1, 0, 1, 2, -4]\ndata2 = [-1, 0, 1, 2, -1, -4]\nprint(threeNums(data2))","repo_name":"KijinBANG/pythonProject","sub_path":"dataStructure/array/threeNums.py","file_name":"threeNums.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"38075713536","text":"import os\nimport sys\nfrom textwrap import dedent\n\nimport pytest\n\nfrom pants.backend.python import target_types_rules\nfrom pants.backend.python.goals import export\nfrom pants.backend.python.goals.export import ExportVenvsRequest\nfrom pants.backend.python.target_types import PythonRequirementTarget\nfrom pants.backend.python.util_rules import pex_from_targets\nfrom pants.base.specs import RawSpecs, RecursiveGlobSpec\nfrom pants.core.goals.export import ExportResults\nfrom pants.core.util_rules import distdir\nfrom pants.engine.rules import QueryRule\nfrom pants.engine.target import Targets\nfrom pants.testutil.rule_runner import RuleRunner\nfrom pants.util.frozendict import FrozenDict\n\n\n@pytest.fixture\ndef rule_runner() -> RuleRunner:\n return RuleRunner(\n rules=[\n *export.rules(),\n *pex_from_targets.rules(),\n *target_types_rules.rules(),\n *distdir.rules(),\n QueryRule(Targets, [RawSpecs]),\n QueryRule(ExportResults, [ExportVenvsRequest]),\n ],\n target_types=[PythonRequirementTarget],\n )\n\n\n@pytest.mark.parametrize(\"enable_resolves\", [False, True])\n@pytest.mark.parametrize(\"symlink\", [False, True])\ndef test_export_venv_pipified(\n rule_runner: RuleRunner,\n enable_resolves: bool,\n symlink: bool,\n) -> None:\n # We know that the current interpreter exists on the system.\n vinfo = sys.version_info\n current_interpreter = f\"{vinfo.major}.{vinfo.minor}.{vinfo.micro}\"\n rule_runner.write_files(\n {\n \"src/foo/BUILD\": dedent(\n \"\"\"\\\n python_requirement(name='req1', requirements=['ansicolors==1.1.8'], resolve='a')\n python_requirement(name='req2', requirements=['ansicolors==1.1.8'], resolve='b')\n \"\"\"\n ),\n \"lock.txt\": \"ansicolors==1.1.8\",\n }\n )\n\n symlink_flag = f\"--{'' if symlink else 'no-'}export-symlink-python-virtualenv\"\n rule_runner.set_options(\n [\n f\"--python-interpreter-constraints=['=={current_interpreter}']\",\n \"--python-resolves={'a': 'lock.txt', 'b': 'lock.txt'}\",\n f\"--python-enable-resolves={enable_resolves}\",\n # Turn off lockfile validation to make the test simpler.\n \"--python-invalid-lockfile-behavior=ignore\",\n symlink_flag,\n ],\n env_inherit={\"PATH\", \"PYENV_ROOT\"},\n )\n targets = rule_runner.request(\n Targets,\n [RawSpecs(recursive_globs=(RecursiveGlobSpec(\"src/foo\"),), description_of_origin=\"tests\")],\n )\n all_results = rule_runner.request(ExportResults, [ExportVenvsRequest(targets)])\n\n for result, resolve in zip(all_results, [\"a\", \"b\"] if enable_resolves else [\"\"]):\n if symlink:\n assert len(result.post_processing_cmds) == 1\n ppc0 = result.post_processing_cmds[0]\n assert ppc0.argv[0:2] == (\"ln\", \"-s\")\n # The third arg is the full path to the venv under the pex_root, which we\n # don't easily know here, so we ignore it in this comparison.\n assert ppc0.argv[3] == os.path.join(\"{digest_root}\", current_interpreter)\n assert ppc0.extra_env == FrozenDict()\n else:\n assert len(result.post_processing_cmds) == 2\n\n ppc0 = result.post_processing_cmds[0]\n assert ppc0.argv[1:] == (\n # The first arg is the full path to the python interpreter, which we\n # don't easily know here, so we ignore it in this comparison.\n os.path.join(\"{digest_root}\", f\".{resolve}.tmp\", \".\", \"pex\"),\n os.path.join(\"{digest_root}\", \"requirements.pex\"),\n \"venv\",\n \"--pip\",\n \"--collisions-ok\",\n \"--remove=pex\",\n f\"{{digest_root}}/{current_interpreter}\",\n )\n assert ppc0.extra_env[\"PEX_MODULE\"] == \"pex.tools\"\n assert ppc0.extra_env.get(\"PEX_ROOT\") is not None\n\n ppc1 = result.post_processing_cmds[1]\n assert ppc1.argv == (\n \"rm\",\n \"-rf\",\n os.path.join(\"{digest_root}\", f\".{resolve}.tmp\"),\n )\n assert ppc1.extra_env == FrozenDict()\n\n reldirs = [result.reldir for result in all_results]\n if enable_resolves:\n assert reldirs == [\n \"python/virtualenvs/a\",\n \"python/virtualenvs/b\",\n ]\n else:\n assert reldirs == [\"python/virtualenv\"]\n","repo_name":"riebecj/pants","sub_path":"src/python/pants/backend/python/goals/export_test.py","file_name":"export_test.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"43"} +{"seq_id":"3206489102","text":"import matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nfrom .gme import GuidedModeExp\nfrom .phc import PhotCryst, Circle\nfrom .pwe import PlaneWaveExp\n\n\ndef bands(gme,\n Q=False,\n Q_clip=1e10,\n cone=True,\n conecolor='#eeeeee',\n ax=None,\n figsize=(4, 5),\n Q_cmap='viridis',\n markersize=6,\n markeredgecolor='w',\n markeredgewidth=1.5):\n \"\"\"Plot photonic band structure from a GME simulation\n\n Note\n ----\n The bands must be solved for and stored in the `GuidedModeExp` or \n `PlaneWaveExp` object prior to calling this function.\n\n Parameters\n ----------\n gme : GuidedModeExp\n Q : bool, optional\n Whether each point should be colored according to the quality factor. \n Default is False.\n Q_clip : float, optional\n The clipping (vmax) value for the quality factor colormap. Default is\n 1e10.\n cone : bool , optional\n Whether the the light cone region of the band structure should be \n shaded. Default is True.\n conecolor : str, optional\n Color of the light cone region. Default is '#eeeeee' (light grey).\n ax : matplotlib axis object, optional\n Matplotlib axis object for plotting. If not provided, a new figure and \n axis are automatically created.\n figsize : Tuple, optional\n Figure size for created figure. Default is (4,5).\n Q_cmap : str or matplotlib colormap object, optional\n Colormap used for the quality factor. Default is 'viridis'.\n markersize : float, optional\n Band marker size. Default is 6.\n markeredgecolor : str, optional\n Band marker edge border color. Default is white.\n markeredgewidth : float, optional\n Band marker edge border width. Default is 1.5.\n\n Returns\n -------\n ax : matplotlib axis object\n Axis object for the plot.\n \"\"\"\n\n if np.all(gme.kpoints[0,:]==0) and not np.all(gme.kpoints[1,:]==0) \\\n or np.all(gme.kpoints[1,:]==0) and not np.all(gme.kpoints[0,:]==0):\n X0 = np.sqrt(\n np.square(gme.kpoints[0, :]) +\n np.square(gme.kpoints[1, :])) / 2 / np.pi\n else:\n X0 = np.arange(len(gme.kpoints[0, :]))\n\n X = np.tile(X0.reshape(len(X0), 1), (1, gme.freqs.shape[1]))\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, constrained_layout=True, figsize=figsize)\n if Q:\n if len(gme.freqs_im) == 0:\n gme.run_im()\n freqs_im = np.array(gme.freqs_im).flatten() + 1e-16\n Q = gme.freqs.flatten() / 2 / freqs_im\n Q_max = np.max(Q[Q < Q_clip])\n\n p = ax.scatter(X.flatten(),\n gme.freqs.flatten(),\n c=Q,\n cmap=Q_cmap,\n s=markersize**2,\n norm=mpl.colors.LogNorm(vmax=Q_max),\n edgecolors=markeredgecolor,\n linewidth=markeredgewidth)\n plt.colorbar(p, ax=ax, label=\"Radiative quality factor\", extend=\"max\")\n else:\n ax.plot(X,\n gme.freqs,\n 'o',\n c=\"#1f77b4\",\n label=\"\",\n ms=markersize,\n mew=markeredgewidth,\n mec=markeredgecolor)\n\n if cone:\n eps_clad = [\n gme.phc.claddings[0].eps_avg, gme.phc.claddings[-1].eps_avg\n ]\n vec_LL = np.sqrt(\n np.square(gme.kpoints[0, :]) +\n np.square(gme.kpoints[1, :])) / 2 / np.pi / np.sqrt(max(eps_clad))\n ax.fill_between(X0,\n vec_LL,\n max(100, vec_LL.max(), gme.freqs[:].max()),\n facecolor=conecolor,\n zorder=0)\n\n ax.set_xlim(left=0, right=max(X0))\n ax.set_ylim(bottom=0.0, top=gme.freqs[:].max())\n ax.set_xlabel('Wave vector')\n ax.set_ylabel('Frequency')\n\n return ax\n\n\ndef _plot_eps(eps_r,\n clim=None,\n ax=None,\n extent=None,\n cmap='Greys',\n cbar=False,\n cax=None):\n\n if ax is None:\n fig, ax = plt.subplots(1, constrained_layout=True)\n\n im = ax.imshow(eps_r, cmap=cmap, origin='lower', extent=extent)\n if clim:\n im.set_clim(vmin=clim[0], vmax=clim[1])\n\n if cbar:\n # cax = ax.figure.add_axes([ax.get_position().x1+0.01,\n # ax.get_position().y0, 0.02, ax.get_position().height])\n # plt.colorbar(im, cax=cax)\n if cax is not None:\n plt.colorbar(im, ax=ax, cax=cax)\n else:\n plt.colorbar(im, ax=ax)\n\n return im\n\n\ndef _plot_circle(x, y, r, ax=None, color='b', lw=1, npts=51):\n\n if ax is None:\n fig, ax = plt.subplots(1, constrained_layout=True)\n\n phi = np.linspace(0, 2 * np.pi, npts)\n xs = x + r * np.cos(phi)\n ys = y + r * np.sin(phi)\n pl = ax.plot(xs, ys, c=color, lw=lw)\n\n return pl\n\n\ndef eps(layer, Nx=100, Ny=100, ax=None, clim=None, cbar=False, cmap='Greys'):\n \"\"\"Plot the in-plane permittivity distribution of a Layer instance\n\n Parameters\n ----------\n layer : Layer\n Nx : int, optional\n Number of sample points to use in x-direction.\n Default is 100.\n Ny : int, optional\n Number of sample points to use in y-direction.\n Default is 100.\n ax : int, optional\n Matplotlib axis object to use for plot.\n clim : List[float], optional\n Matplotlib color limit to use for plot.\n Default is None.\n cbar : bool, optional\n Whether or not a colorbar should be added to the plot.\n Default is False.\n cmap : bool, optional\n Matplotlib colormap to use for plot\n Default is 'Greys'.\n \"\"\"\n (xgrid, ygrid) = layer.lattice.xy_grid(Nx=Nx, Ny=Ny)\n [xmesh, ymesh] = np.meshgrid(xgrid, ygrid)\n\n eps_r = layer.get_eps((xmesh, ymesh))\n extent = [xgrid[0], xgrid[-1], ygrid[0], ygrid[-1]]\n\n _plot_eps(eps_r, clim=clim, ax=ax, extent=extent, cbar=cbar, cmap=cmap)\n\n\ndef eps_xz(phc,\n y=0,\n Nx=100,\n Nz=50,\n ax=None,\n clim=None,\n cbar=False,\n cmap='Greys',\n cax=None,\n plot=True):\n \"\"\"Plot permittivity cross section of a photonic crystal in an xz plane\n\n Parameters\n ----------\n phc : PhotCryst\n y : float, optional\n The y-coordinate of the xz plane.\n Default is 0.\n Nx : int, optional\n Number of sample points to use in x-direction.\n Default is 100.\n Nz : int, optional\n Number of sample points to use in z-direction.\n Default is 50.\n ax : int, optional\n Matplotlib axis object to use for plot.\n clim : List[float], optional\n Matplotlib color limit to use for plot.\n Default is None.\n cbar : bool, optional\n Whether or not a colorbar should be added to the plot.\n Default is False.\n cmap : string, optional\n Matplotlib colormap to use for plot\n Default is 'Greys'.\n cax : matplotlib axis object, optional\n Axis handle for the colorbar\n Default it None.\n plot : bool, optional\n Whether or not the a plot should be generated. Useful for cases where\n only the array values are needed, e.g. for logging during optimization.\n Default is True.\n\n Returns\n -------\n eps_r : np.ndarray\n Array containing permittivity values\n \"\"\"\n (xgrid, zgrid) = (phc.lattice.xy_grid(Nx=Nx)[0], phc.z_grid(Nz=Nz))\n\n [xmesh, zmesh] = np.meshgrid(xgrid, zgrid)\n ymesh = y * np.ones(xmesh.shape)\n\n eps_r = phc.get_eps((xmesh, ymesh, zmesh))\n extent = [xgrid[0], xgrid[-1], zgrid[0], zgrid[-1]]\n\n if plot:\n _plot_eps(eps_r,\n clim=clim,\n ax=ax,\n extent=extent,\n cbar=cbar,\n cmap=cmap,\n cax=cax)\n\n return eps_r\n\n\ndef eps_xy(phc,\n z=0,\n Nx=100,\n Ny=100,\n ax=None,\n clim=None,\n cbar=False,\n cmap='Greys',\n cax=None,\n plot=True):\n \"\"\"Plot permittivity cross section of a photonic crystal in an xy plane\n\n Parameters\n ----------\n phc : PhotCryst\n z : float, optional\n The z-coordinate of the xz plane.\n Default is 0.\n Nx : int, optional\n Number of sample points to use in x-direction.\n Default is 100.\n Ny : int, optional\n Number of sample points to use in y-direction.\n Default is 100.\n ax : int, optional\n Matplotlib axis object to use for plot.\n clim : List[float], optional\n Matplotlib color limit to use for plot.\n Default is None.\n cbar : bool, optional\n Whether or not a colorbar should be added to the plot.\n Default is False.\n cmap : string, optional\n Matplotlib colormap to use for plot\n Default is 'Greys'.\n cax : matplotlib axis object, optional\n Axis handle for the colorbar\n Default it None.\n plot : bool, optional\n Whether or not the a plot should be generated. Useful for cases where\n only the array values are needed, e.g. for logging during optimization.\n Default is True.\n\n Returns\n -------\n eps_r : np.ndarray\n Array containing permittivity values\n \"\"\"\n (xgrid, ygrid) = phc.lattice.xy_grid(Nx=Nx, Ny=Ny)\n [xmesh, ymesh] = np.meshgrid(xgrid, ygrid)\n zmesh = z * np.ones(xmesh.shape)\n\n eps_r = phc.get_eps((xmesh, ymesh, zmesh))\n extent = [xgrid[0], xgrid[-1], ygrid[0], ygrid[-1]]\n\n if plot:\n _plot_eps(eps_r,\n clim=clim,\n ax=ax,\n extent=extent,\n cbar=cbar,\n cmap=cmap,\n cax=cax)\n\n return eps_r\n\n\ndef eps_yz(phc,\n x=0,\n Ny=100,\n Nz=50,\n ax=None,\n clim=None,\n cbar=False,\n cmap='Greys',\n cax=None,\n plot=True):\n \"\"\"Plot permittivity cross section of a photonic crystal in an yz plane\n\n Parameters\n ----------\n phc : PhotCryst\n x : float, optional\n The x-coordinate of the xz plane.\n Default is 0.\n Ny : int, optional\n Number of sample points to use in y-direction.\n Default is 100.\n Nz : int, optional\n Number of sample points to use in z-direction.\n Default is 50.\n ax : int, optional\n Matplotlib axis object to use for plot.\n clim : List[float], optional\n Matplotlib color limit to use for plot.\n Default is None.\n cbar : bool, optional\n Whether or not a colorbar should be added to the plot.\n Default is False.\n cmap : string, optional\n Matplotlib colormap to use for plot\n Default is 'Greys'.\n cax : matplotlib axis object, optional\n Axis handle for the colorbar\n Default it None.\n plot : bool, optional\n Whether or not the a plot should be generated. Useful for cases where\n only the array values are needed, e.g. for logging during optimization.\n Default is True.\n\n Returns\n -------\n eps_r : np.ndarray\n Array containing permittivity values\n \"\"\"\n (ygrid, zgrid) = (phc.lattice.xy_grid(Ny=Ny)[1], phc.z_grid(Nz=Nz))\n [ymesh, zmesh] = np.meshgrid(ygrid, zgrid)\n xmesh = x * np.ones(ymesh.shape)\n\n eps_r = phc.get_eps((xmesh, ymesh, zmesh))\n extent = [ygrid[0], ygrid[-1], zgrid[0], zgrid[-1]]\n\n if plot:\n _plot_eps(eps_r,\n clim=clim,\n ax=ax,\n extent=extent,\n cbar=cbar,\n cmap=cmap,\n cax=cax)\n\n return eps_r\n\n\ndef shapes(layer, ax=None, npts=101, color='k', lw=1, pad=True):\n \"\"\"Plot all shapes of Layer\n \"\"\"\n\n (xext, yext) = layer.lattice.xy_grid(Nx=2, Ny=2)\n if ax is None:\n fig, ax = plt.subplots(1, constrained_layout=True)\n\n if pad == True:\n a1 = layer.lattice.a1\n a2 = layer.lattice.a2\n xy_p = [a1, -a1, a2, -a2]\n\n for shape in layer.shapes:\n if type(shape) == Circle:\n x = shape.x_cent\n y = shape.y_cent\n r = shape.r\n _plot_circle(x, y, r, ax=ax, color=color, lw=lw, npts=npts)\n if pad == True:\n for (x_p, y_p) in xy_p:\n _plot_circle(x + x_p,\n y + y_p,\n r,\n ax=ax,\n color=color,\n lw=lw,\n npts=npts)\n else:\n # Everything else should be a Poly subclass\n ax.plot(shape.x_edges, shape.y_edges, c=color, lw=lw)\n if pad == True:\n for (x_p, y_p) in xy_p:\n ax.plot(shape.x_edges + x_p,\n shape.y_edges + y_p,\n c=color,\n lw=lw)\n ax.set_xlim(xext)\n ax.set_ylim(yext)\n ax.set_aspect('equal')\n\n\ndef structure(struct,\n Nx=100,\n Ny=100,\n Nz=50,\n cladding=False,\n cbar=True,\n cmap='Greys',\n gridspec=None,\n fig=None,\n figsize=None,\n xy=True,\n xz=False,\n yz=False):\n \"\"\"Plot permittivity for all cross sections of a photonic crystal\n\n Parameters\n ----------\n struct : GuidedModeExp or PlaneWaveExp \n Nx : int, optional\n Number of sample points to use in x-direction.\n Default is 100.\n Ny : int, optional\n Number of sample points to use in y-direction.\n Default is 100.\n Nz : int, optional\n Number of sample points to use in z-direction.\n Default is 50.\n cladding : bool, optional\n Whether or not the cladding should be plotted.\n Default is False.\n cbar : bool, optional\n Whether or not a colorbar should be added to the plot.\n Default is False.\n cmap : bool, optional\n Matplotlib colormap to use for plot\n Default is 'Greys'.\n gridspec : Matplotlib gridspec object, optional\n Gridspec to use for creating the plots.\n Default is None.\n fig : Matplotlib figure object, optional\n Figure to use for creating the plots.\n Default is None.\n figsize : int, float or tuple, optional\n Size of Matplotlib figure to create.\n Default is None, which sets the width to 4in and the height depending \n on the aspect ratios. If int or float, it's taken as the figure width.\n xy : bool, optional\n Plot the xy cross-section in every layer.\n Default is True.\n xz : bool, optional\n Also plot an xz cross-section.\n Default is False.\n yz : bool, optional\n Also plot a yz cross-section.\n Default is False.\n \"\"\"\n if isinstance(struct, GuidedModeExp):\n phc = struct.phc\n elif isinstance(struct, PhotCryst):\n phc = struct\n else:\n raise ValueError(\"'struct' should be a 'PhotCryst' or a \"\n \"'GuidedModeExp' instance\")\n\n (eps_min, eps_max) = phc.get_eps_bounds()\n\n if cladding == True:\n all_layers = [phc.claddings[0]] + phc.layers + [phc.claddings[1]]\n else:\n all_layers = phc.layers\n N_layers = len(all_layers)\n\n (xb, yb) = all_layers[0].lattice.xy_grid(Nx=2, Ny=2)\n zb = phc.z_grid(Nz=2)\n ar_xy = (yb[1] - yb[0]) / (xb[1] - xb[0]) # aspect ratio\n ar_xz = (zb[1] - zb[0]) / (xb[1] - xb[0])\n ar_yz = (zb[1] - zb[0]) / (yb[1] - yb[0])\n\n ars = []\n if xz == True: ars.append(ar_xz)\n if yz == True: ars.append(ar_yz)\n if xy == True: ars = ars + [ar_xy for i in range(N_layers)]\n\n if isinstance(figsize, float) or isinstance(figsize, int):\n xw = figsize\n else:\n xw = 4\n\n # Width in x of the image, colorbar takes 5% by default, and exclude some\n # space for the axis label\n cbwidth = 0.05\n xwi = xw - 0.3 if cbar == False else (1 - cbwidth) * xw - 0.8\n\n if not isinstance(figsize, tuple):\n figsize = (xw, xwi * sum(ars) + len(ars) * 0.2)\n\n if gridspec is None and fig is None:\n fig = plt.figure(constrained_layout=True, figsize=figsize)\n if cbar == False:\n gs = mpl.gridspec.GridSpec(len(ars),\n 1,\n figure=fig,\n height_ratios=ars)\n else:\n gs = mpl.gridspec.GridSpec(len(ars),\n 2,\n figure=fig,\n height_ratios=ars,\n width_ratios=[1 - cbwidth, cbwidth])\n elif gridspec is not None and fig is not None:\n if cbar == False:\n gs = mpl.gridspec.GridSpecFromSubplotSpec(len(ars), 1, gridspec)\n else:\n gs = mpl.gridspec.GridSpecFromSubplotSpec(len(ars), 2, gridspec)\n else:\n raise ValueError(\n \"Parameters gridspec and fig should be both specified \"\n \"or both unspecified\")\n axind = 0\n\n if xz == True:\n ax1 = fig.add_subplot(gs[axind, 0])\n cax = None if cbar == False else fig.add_subplot(gs[axind, 1])\n eps_xz(phc,\n ax=ax1,\n Nx=Nx,\n Nz=Nz,\n clim=[eps_min, eps_max],\n cbar=cbar,\n cmap=cmap,\n cax=cax)\n ax1.set_title(\"xz at y = 0\")\n axind += 1\n\n if yz == True:\n ax2 = fig.add_subplot(gs[axind, 0])\n cax = None if cbar == False else fig.add_subplot(gs[axind, 1])\n eps_yz(phc,\n ax=ax2,\n Ny=Ny,\n Nz=Nz,\n clim=[eps_min, eps_max],\n cbar=cbar,\n cmap=cmap,\n cax=cax)\n ax2.set_title(\"yz at x = 0\")\n axind += 1\n\n if xy == True:\n ax = []\n\n for indl in range(N_layers):\n zpos = (all_layers[indl].z_max + all_layers[indl].z_min) / 2\n ax.append(fig.add_subplot(gs[axind + indl, 0]))\n cax = None if cbar == False else fig.add_subplot(gs[axind + indl,\n 1])\n eps_xy(phc,\n z=zpos,\n ax=ax[indl],\n Nx=Nx,\n Ny=Ny,\n clim=[eps_min, eps_max],\n cbar=cbar,\n cmap=cmap,\n cax=cax)\n if cladding == True:\n if indl > 0 and indl < N_layers - 1:\n ax[indl].set_title(\"xy in layer %d\" % indl)\n elif indl == N_layers - 1:\n ax[0].set_title(\"xy in lower cladding\")\n ax[-1].set_title(\"xy in upper cladding\")\n else:\n ax[indl].set_title(\"xy in layer %d\" % indl)\n\n\ndef eps_ft(struct,\n Nx=100,\n Ny=100,\n cladding=False,\n cbar=True,\n cmap='Greys',\n gridspec=None,\n fig=None,\n figsize=None,\n xz=False,\n yz=False):\n \"\"\"Plot a permittivity cross section computed from an inverse FT\n\n The Fourier transform is computed with respect to the GME reciprocal\n lattice vectors.\n\n Parameters\n ----------\n struct : GuidedModeExp or PlaneWaveExp \n Nx : int, optional\n Number of sample points to use in x-direction.\n Default is 100.\n Ny : int, optional\n Number of sample points to use in y-direction.\n Default is 100.\n cladding : bool, optional\n Whether or not the cladding should be plotted.\n Default is False.\n cbar : bool, optional\n Whether or not a colorbar should be added to the plot.\n Default is False.\n cmap : bool, optional\n Matplotlib colormap to use for plot\n Default is 'Greys'.\n gridspec : Matplotlib gridspec object, optional\n Gridspec to use for creating the plots.\n Default is None.\n fig : Matplotlib figure object, optional\n Figure to use for creating the plots.\n Default is None.\n figsize : int, float or tuple, optional\n Size of Matplotlib figure to create.\n Default is None, which sets the width to 4in and the height depending \n on the aspect ratios. If int or float, it's taken as the figure width.\n \"\"\"\n\n # Do some parsing of the inputs\n if isinstance(struct, GuidedModeExp):\n str_type = 'gme'\n elif isinstance(struct, PlaneWaveExp):\n str_type = 'pwe'\n else:\n raise ValueError(\"'struct' should be a 'PlaneWaveExp' or a \"\n \"'GuidedModeExp' instance\")\n\n if cladding == True:\n if str_type == 'pwe':\n print(\"Warning: ignoring 'cladding=True' for PlaneWaveExp \"\n \"structure.\")\n all_layers = [struct.layer]\n else:\n all_layers = [struct.phc.claddings[0]] + struct.phc.layers + \\\n [struct.phc.claddings[1]]\n else:\n all_layers = struct.phc.layers if str_type == 'gme' else [struct.layer]\n N_layers = len(all_layers)\n\n (xb, yb) = all_layers[0].lattice.xy_grid(Nx=2, Ny=2)\n ar = (yb[1] - yb[0]) / (xb[1] - xb[0]) # aspect ratio\n\n if isinstance(figsize, float) or isinstance(figsize, int):\n xw = figsize\n else:\n xw = 4\n\n # Width in x of the image, colorbar takes 5% by default, and exclude some\n # space for the axis label\n cbwidth = 0.05\n xwi = xw - 0.3 if cbar == False else (1 - cbwidth) * xw - 0.8\n\n if not isinstance(figsize, tuple):\n figsize = (xw, xwi * N_layers * ar + N_layers * 0.2)\n\n if gridspec is None and fig is None:\n fig = plt.figure(constrained_layout=True, figsize=figsize)\n if cbar == False:\n gs = mpl.gridspec.GridSpec(N_layers, 1, figure=fig)\n else:\n gs = mpl.gridspec.GridSpec(N_layers,\n 2,\n figure=fig,\n width_ratios=[1 - cbwidth, cbwidth])\n elif gridspec is not None and fig is not None:\n if cbar == False:\n gs = mpl.gridspec.GridSpecFromSubplotSpec(len(all_layers), 1, gridspec)\n else:\n gs = mpl.gridspec.GridSpecFromSubplotSpec(len(all_layers), 2, gridspec)\n else:\n raise ValueError(\n \"Parameters gridspec and fig should be both specified \"\n \"or both unspecified\")\n\n (eps_min, eps_max) = (all_layers[0].eps_b, all_layers[0].eps_b)\n ims = []\n ax = []\n\n for (indl, layer) in enumerate(all_layers):\n ax.append(fig.add_subplot(gs[indl, :]))\n (eps_r, xgrid,\n ygrid) = struct.get_eps_xy(Nx=Nx,\n Ny=Ny,\n z=(layer.z_min + layer.z_max) / 2)\n\n eps_min = min([eps_min, np.amin(np.real(eps_r))])\n eps_max = max([eps_max, np.amax(np.real(eps_r))])\n extent = [xgrid[0], xgrid[-1], ygrid[0], ygrid[-1]]\n cax = None if cbar == False else fig.add_subplot(gs[indl, 1])\n im = _plot_eps(np.real(eps_r),\n ax=ax[indl],\n extent=extent,\n cbar=cbar,\n cax=cax)\n ims.append(im)\n if cladding:\n if indl > 0 and indl < N_layers - 1:\n ax[indl].set_title(\"xy in layer %d\" % indl)\n elif indl == N_layers - 1:\n ax[0].set_title(\"xy in lower cladding\")\n ax[-1].set_title(\"xy in upper cladding\")\n else:\n ax[indl].set_title(\"xy in layer %d\" % indl)\n\n for il in range(N_layers):\n ims[il].set_clim(vmin=eps_min, vmax=eps_max)\n\n\ndef reciprocal(struct):\n \"\"\"Plot the reciprocal lattice of a GME or PWE object\n\n Parameters\n ----------\n struct : GuidedModeExp or PlaneWaveExp \n \"\"\"\n fig, ax = plt.subplots(1, constrained_layout=True)\n plt.plot(struct.gvec[0, :], struct.gvec[1, :], 'bx')\n ax.set_title(\"Reciprocal lattice\")\n\n\ndef field(struct,\n field,\n kind,\n mind,\n x=None,\n y=None,\n z=None,\n periodic=True,\n component='xyz',\n val='re',\n N1=100,\n N2=100,\n cbar=True,\n eps=True,\n eps_levels=None):\n \"\"\"Visualize mode fields over a 2D slice in x, y, or z\n\n Note\n ----\n The fields must be solved for and stored in the `GuidedModeExp` or \n `PlaneWaveExp` object prior to calling this function.\n\n Parameters\n ----------\n struct : GuidedModeExp or PlaneWaveExp \n field : {'H', 'D', 'E'}\n The field quantity to plot\n kind : int\n The wave vector index to plot\n mind : int\n The mode index to plot\n x, y, z : float\n Coordinate of the slice in either x, y, or z. One and \n only one of these should be specified\n periodic : bool, optional\n Whether the periodic portion or the full field should be plotted\n component : str, optional\n Component of the vector field to plot\n val : {'re', 'im', 'abs'}, optional\n Field value to plot\n N1 : int, optional\n Number of grid points to sample in first spatial dim\n N2 : int, optional\n Number of grid points to sample in second spatial dim\n cbar : bool, optional\n Whether to include a colorbar\n eps : bool, optional\n Whether an outline of the permittivity should be overlaid\n eps_levels : List, optional\n A list of contour levels for the permittivity\n\n Returns\n -------\n fig : matplotlib figure object\n Figure object for the plot.\n \"\"\"\n\n if isinstance(struct, GuidedModeExp):\n str_type = 'gme'\n elif isinstance(struct, PlaneWaveExp):\n str_type = 'pwe'\n else:\n raise ValueError(\"'struct' should be a 'PlaneWaveExp' or a \"\n \"'GuidedModeExp' instance\")\n\n field = field.lower()\n val = val.lower()\n component = component.lower()\n\n # Get the field fourier components\n if (x is None and y is None and z is None and str_type == 'pwe') or \\\n (z is not None and x is None and y is None):\n\n zval = 0. if z == None else z\n (fi, grid1, grid2) = struct.get_field_xy(field,\n kind,\n mind,\n z,\n component=component,\n Nx=N1,\n Ny=N2)\n if eps == True:\n if str_type == 'pwe':\n epsr = struct.layer.get_eps(np.meshgrid(grid1,\n grid2)).squeeze()\n\n else:\n epsr = struct.phc.get_eps(\n np.meshgrid(grid1, grid2, np.array(z))).squeeze()\n\n pl, o, v = 'xy', 'z', zval\n if periodic == False:\n kenv = np.exp(1j * grid1[None, :] * struct.kpoints[0, kind] +\n 1j * grid2[:, None] * struct.kpoints[1, kind])\n\n elif x is not None and z is None and y is None:\n if str_type == 'pwe':\n raise NotImplementedError(\"Only plotting in the xy-plane is \"\n \"supported for PlaneWaveExp structures.\")\n\n (fi, grid1, grid2) = struct.get_field_yz(field,\n kind,\n mind,\n x,\n component=component,\n Ny=N1,\n Nz=N2)\n if eps == True:\n epsr = struct.phc.get_eps(np.meshgrid(\n np.array(x), grid1, grid2)).squeeze().transpose()\n pl, o, v = 'yz', 'x', x\n if periodic == False:\n kenv = np.exp(1j * grid1 * struct.kpoints[1, kind] +\n 1j * x * struct.kpoints[0, kind])\n elif y is not None and z is None and x is None:\n if str_type == 'pwe':\n raise NotImplementedError(\"Only plotting in the xy-plane is \"\n \"supported for PlaneWaveExp structures.\")\n\n (fi, grid1, grid2) = struct.get_field_xz(field,\n kind,\n mind,\n y,\n component=component,\n Nx=N1,\n Nz=N2)\n if eps == True:\n epsr = struct.phc.get_eps(np.meshgrid(\n grid1, np.array(y), grid2)).squeeze().transpose()\n pl, o, v = 'xz', 'y', y\n if periodic == False:\n kenv = np.exp(1j * grid1 * struct.kpoints[0, kind] +\n 1j * y * struct.kpoints[1, kind])\n else:\n raise ValueError(\"Specify exactly one of 'x', 'y', or 'z'.\")\n\n sp = len(component)\n f1, axs = plt.subplots(1, sp, constrained_layout=True)\n for ic, comp in enumerate(component):\n f = fi[comp]\n if periodic == False:\n f *= kenv\n\n extent = [grid1[0], grid1[-1], grid2[0], grid2[-1]]\n if sp > 1:\n ax = axs[ic]\n else:\n ax = axs\n\n if val == 're' or val == 'im':\n Z = np.real(f) if val == 're' else np.imag(f)\n cmap = 'RdBu'\n vmax = np.abs(Z).max()\n vmin = -vmax\n elif val == 'abs':\n Z = np.abs(f)\n cmap = 'magma'\n vmax = Z.max()\n vmin = 0\n else:\n raise ValueError(\"'val' can be 'im', 're', or 'abs'\")\n\n im = ax.imshow(Z,\n extent=extent,\n cmap=cmap,\n vmin=vmin,\n vmax=vmax,\n origin='lower')\n\n if eps == True:\n lcs = 'k' if val.lower() in ['re', 'im'] else 'w'\n ax.contour(grid1, grid2, epsr, 0 if eps_levels is None else \\\n eps_levels, colors=lcs, linewidths=1, alpha=0.5)\n\n if cbar == True:\n f1.colorbar(im, ax=ax, shrink=0.5)\n\n title_str = \"\"\n\n title_str += \"%s$(%s_{%s%d})$ at $k_{%d}$\\n\" % (\n val.capitalize(), field.capitalize(), comp, mind, kind)\n title_str += \"%s-plane at $%s = %1.2f$\\n\" % (pl, o, v)\n title_str += \"$f = %.2f$\" % (struct.freqs[kind, mind])\n if str_type == 'gme':\n if struct.freqs_im != []:\n if np.abs(struct.freqs_im[kind, mind]) > 1e-20:\n title_str += \" $Q = %.2E$\\n\" % (\n struct.freqs[kind, mind] / 2 /\n struct.freqs_im[kind, mind])\n else:\n title_str += \" $Q = $Inf\\n\"\n\n ax.set_title(title_str)\n\n return f1\n","repo_name":"fancompute/legume","sub_path":"legume/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":31382,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"43"} +{"seq_id":"11811123825","text":"'''\nFahrenheit to Celsius:\n\nWrite the necessary code to read a degree in Fahrenheit from the console\nthen convert it to Celsius and print it to the console.\n\n C = (F - 32) * (5 / 9)\n\nOutput should read like - \"81.32 degrees fahrenheit = 27.4 degrees celsius\"\n\n\n'''\n\nfahrenheit = float(input(\"Enter Fahrenheit degrees to convert: \"))\n\ncelsius = (fahrenheit - 32) * (5 / 9)\n\nprint(f\"{fahrenheit} degrees fahrenheit = {celsius} degrees celsius\")\n","repo_name":"Aleks-me/CodingNomads","sub_path":"python/labs/02_basic_datatypes/1_numbers/02_04_temp.py","file_name":"02_04_temp.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"17045223686","text":"\n# 원반 개수, 시작점, 목적지, 경유지\ndef hanoi(n, start, to, mid, answer):\n if n == 1:\n return answer.append([start, to])\n hanoi(n-1, start, mid, to, answer) # 하나 적은 원반들을 목적지가 아닌 곳으로 옮긴다\n answer.append([start, to]) # 원하는 원반(마지막 원반)을 목적지로 이동\n hanoi(n-1, mid, to, start, answer) # 나머지 원반을 목적지로 이동한다.\n\ndef solution(n):\n answer = []\n hanoi(n, 1, 3, 2, answer)\n return answer\n\nanswer = solution(2)\nprint(answer)","repo_name":"MindException/TIL","sub_path":"Algorithm/재귀함수(Recursive Function)/Hanoi.py","file_name":"Hanoi.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"41078219034","text":"from ultralytics import YOLO\r\nmodel=YOLO(\"Boar-Hunt.pt\")\r\nimport cv2\r\nimport serial\r\n# Replace 'COMX' with the actual COM port of your Arduino\r\nser = serial.Serial('COM1', 9600, timeout=1)\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nif not cap.isOpened():\r\n print(\"Error: Could not open the webcam.\")\r\n exit()\r\n\r\nwhile True:\r\n ret, frame = cap.read()\r\n results=model.predict(source=frame,conf=0.8,show=True)\r\n try :\r\n x=results[0]\r\n box = x.boxes[0]\r\n command='1'\r\n ser.write(command.encode('utf-8'))\r\n except:\r\n pass\r\n cv2.imshow(\"Webcam\", frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()","repo_name":"SadhaSivamx/Boar-Hunting-YOLOv8","sub_path":"Arduino-Boar.py","file_name":"Arduino-Boar.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"23165729609","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 lower = math.ceil(math.sqrt(a))\n upper = math.floor(math.sqrt(b))\n return upper - lower + 1\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":"UtkarshPathrabe/Competitive-Coding","sub_path":"HackerRank Solutions/Algorithms/Implementation/Sherlock and Squares.py","file_name":"Sherlock and Squares.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"43"} +{"seq_id":"17616800303","text":"'''\r\nGiven an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique.\r\n'''\r\n\r\ndef uniqueOccurrences(self, arr: List[int]) -> bool:\r\n d={}\r\n for i in arr:\r\n if i not in d:\r\n d[i] = 1\r\n else:\r\n d[i] += 1\r\n return len(d) == len(set(d.values()))\r\n ","repo_name":"iamdeepakvashisth/LeetCode-Algorithms-Python","sub_path":"uniqueNoOfOccurances.py","file_name":"uniqueNoOfOccurances.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"40303601216","text":"import random\nfrom typing import Any, Callable, Dict, Optional\n\nimport pytest\nfrom dash import Dash, Input, Output\nfrom dash.testing.composite import DashComposite\nfrom selenium.webdriver.common.action_chains import ActionChains\n\nimport dash_material_components as mdc\n\n\nSLIDER_OPTIONS = {\"minValue\": 0, \"maxValue\": 100, \"stepValue\": 1, \"selected\": 50, \"width\": 100}\n\n\n@pytest.fixture\ndef dash_app() -> Callable[[Optional[int], Optional[str]], Dash]:\n def app_factory(selected: Optional[int] = None, input_type: Optional[str] = None) -> Dash:\n kwargs: Dict[str, Any] = SLIDER_OPTIONS\n if selected is not None:\n kwargs[\"selected\"] = selected\n kwargs[\"inputType\"] = input_type\n\n app = Dash(name=__name__)\n app.layout = mdc.Dashboard(\n children=mdc.Page(\n children=mdc.Section(\n children=mdc.Box(\n children=[\n mdc.Slider(id=\"slider\", **kwargs),\n mdc.Typography(id=\"text\"),\n ],\n ),\n cards=[{\"title\": \"Card\"}],\n ),\n )\n )\n\n @app.callback(\n Output(component_id=\"text\", component_property=\"text\"),\n Input(component_id=\"slider\", component_property=\"selected\"),\n )\n def on_change(selected: int) -> str:\n return str(selected)\n\n return app\n\n return app_factory\n\n\n@pytest.mark.parametrize(\n \"selected,text\",\n [\n (0, \"0\"),\n (50, \"50\"),\n (100, \"100\"),\n ],\n)\ndef test_props(dash_duo: DashComposite, dash_app, selected, text):\n dash_duo.start_server(dash_app(selected))\n dash_duo.wait_for_text_to_equal(\"#text\", text)\n\n assert dash_duo.find_element(\"#text\").text == text\n assert dash_duo.get_logs() is None\n\n\ndef test_slide_action(dash_duo: DashComposite, dash_app):\n initial_value = 50\n dash_duo.start_server(dash_app(initial_value))\n slider = dash_duo.find_element(\".MuiSlider-thumb\")\n\n # move slider\n slide_amount = random.randint(-50, 50)\n ActionChains(dash_duo.driver).drag_and_drop_by_offset(slider, slide_amount, 0).perform()\n assert dash_duo.find_element(\"#text\").text == str(initial_value + slide_amount)\n\n assert dash_duo.get_logs() is None\n\n\ndef test_slider_render_float_input_text(dash_duo: DashComposite, dash_app):\n dash_duo.start_server(dash_app(input_type=\"float\", selected=12.34))\n input_field = dash_duo.find_element(\"input\")\n assert input_field.get_attribute(\"value\") == \"12.34\"\n assert dash_duo.get_logs() is None\n\n\ndef test_slider_render_integer_input_text(dash_duo: DashComposite, dash_app):\n dash_duo.start_server(dash_app(input_type=\"float\", selected=12))\n input_field = dash_duo.find_element(\"input\")\n assert input_field.get_attribute(\"value\") == \"12\"\n assert dash_duo.get_logs() is None\n\n\ndef test_slider_update_from_input_text(dash_duo: DashComposite, dash_app):\n dash_duo.start_server(dash_app(input_type=\"float\", selected=12.34))\n input_field = dash_duo.find_element(\".MuiInputBase-input\")\n\n # test if input text is reflected in output typography\n input_field.clear()\n input_field.send_keys(\"56.78\")\n assert dash_duo.find_element(\"#text\").text == \"56.78\"\n\n assert dash_duo.get_logs() is None\n\n\ndef test_slider_input_validation(dash_duo: DashComposite, dash_app):\n dash_duo.start_server(dash_app(input_type=\"float\", selected=12.34))\n input_field = dash_duo.find_element(\".MuiInputBase-input\")\n\n # test if default precision (2) is respected\n input_field.clear()\n input_field.send_keys(\"12.345678\")\n assert dash_duo.find_element(\"#text\").text == \"12.34\"\n\n # test if invalid characters are ignored\n input_field.clear()\n input_field.send_keys(\"-\")\n input_field.send_keys(\".\")\n assert dash_duo.find_element(\"#text\").text == \"12.34\"\n input_field.clear()\n input_field.send_keys(\"0\")\n input_field.send_keys(\".\")\n input_field.send_keys(\"abcd\")\n assert dash_duo.find_element(\"#text\").text == \"0\"\n input_field.clear()\n input_field.send_keys(\"--\")\n assert dash_duo.find_element(\"#text\").text == \"0\"\n\n assert dash_duo.get_logs() is None\n","repo_name":"noosenergy/dash-material-components","sub_path":"tests/input/test_slider.py","file_name":"test_slider.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"43"} +{"seq_id":"23303990193","text":"import copy\nimport random\n\nBOARD_SIZE = 9\nSUBGRID_SIZE = 3\n\nclass Sudoku:\n def __init__(self, rows):\n # Board with fixed values\n self.sudoku = []\n for row in range(len(rows)):\n self.sudoku.append(rows[row])\n \n # Board with solution\n self.solution = []\n for row in range(BOARD_SIZE):\n self.solution.append([])\n for column in range(BOARD_SIZE):\n self.solution[row].append(0)\n\n def print_board(self, board):\n print(\"\\n|-------|-------|-------|\")\n for row in range(BOARD_SIZE):\n for column in range(BOARD_SIZE):\n if (column % 3 == 2):\n print(board[row][column], \"| \", end=\"\")\n elif (column == 0):\n print(\"|\", board[row][column], end=\" \")\n else:\n print(board[row][column], \"\", end=\"\")\n if (row % 3 == 2):\n print(\"\\n|-------|-------|-------|\")\n else:\n print(\"\")\n # Print board with fixed values\n def print_sudoku(self):\n self.print_board(self.sudoku)\n\n # Print board with solution\n def print_solution(self):\n self.print_board(self.solution)\n \n # Returns if solution's board is a valid solution\n def is_solution(self):\n # Check if there is any empty grid (0 value)\n is_solution = not self.empty_grid()\n\n # Check rows\n is_solution = not self.are_duplicated_in_rows(self.solution)\n \n # Check columns\n if is_solution != False:\n is_solution = not self.are_duplicated_in_columns()\n \n # Check 3x3 subgrids\n if is_solution != False:\n is_solution = not self.are_duplicated_in_subgrids()\n \n return is_solution\n\n # Returns True if there is an empty grid (equal 0) in the solution,\n # otherwise returns False\n def empty_grid(self):\n for row in self.solution:\n if 0 in row:\n return True\n return False\n # Returns True if there is any duplicated number in any row of the board,\n # otherwise returns false\n def are_duplicated_in_rows(self, board):\n duplicated = False\n for row in board:\n duplicated_nums = {num for num in row if row.count(num) > 1}\n # if there's any duplicated num in the row\n if (len(duplicated_nums) > 0 and not 0 in duplicated_nums):\n duplicated = True\n break\n return duplicated\n # Returns True if there is any duplicated number in any column of the board,\n # otherwise returns false\n def are_duplicated_in_columns(self):\n duplicated = False\n columns = [[],[],[],[],[],[],[],[],[]]\n # Extract and store columns\n for i in range(BOARD_SIZE):\n for j in range(BOARD_SIZE): \n columns[i].append(self.solution[j][i])\n # Check columns\n duplicated = self.are_duplicated_in_rows(columns)\n return duplicated\n \n # Returns True if there is any duplicated number in any 3x3 subgrid of the board,\n # otherwise returns false\n def are_duplicated_in_subgrids(self):\n duplicated = False\n subgrid = []\n # Scroll grid in rows\n for rgrid in range(SUBGRID_SIZE):\n # Scroll grid in columns\n for cgrid in range(SUBGRID_SIZE):\n if not duplicated:\n # Make Subgrid\n for row in range(SUBGRID_SIZE):\n for column in range(SUBGRID_SIZE):\n subgrid.append(self.solution[row + SUBGRID_SIZE*rgrid][column + SUBGRID_SIZE*cgrid])\n # Check subgrid\n duplicated = self.are_duplicated_in_3x3_subgrid(subgrid)\n subgrid.clear()\n if(duplicated):\n break;\n \n return duplicated\n # Returns True if there is any duplicated number in an specific 3x3 subgrid of the board,\n # otherwise returns false\n def are_duplicated_in_3x3_subgrid(self, grid):\n duplicated = False\n duplicated_nums = {num for num in grid if grid.count(num) > 1 and num != 0}\n if (len(duplicated_nums) > 0 and not 0 in duplicated_nums):\n duplicated = True\n return duplicated \n\n # Returns the amount of duplicated numbers in the solution\n # Is used to get the FITNESS for the genetic algorithm\n def count_duplicates(self):\n # Duplicates in rows\n duplicates = self.count_duplicates_in_rows(self.solution) \n # Duplicates in columns\n columns = [[],[],[],[],[],[],[],[],[]]\n # Extract and store columns\n for i in range(BOARD_SIZE):\n for j in range(BOARD_SIZE): \n columns[i].append(self.solution[j][i])\n duplicates += self.count_duplicates_in_rows(columns)\n return duplicates\n \n # Returns the amount of duplicated numbers in the rows of the solution\n def count_duplicates_in_rows(self, board):\n duplicates = 0\n for row in board:\n duplicated_nums = {num for num in row if row.count(num) > 1}\n for dnum in duplicated_nums:\n duplicates += row.count(dnum)-1\n return duplicates\n \n # Returns the 3x3 subgrids of the solution\n def get_3x3_subgrids(self):\n subgrids = []\n subgrid = []\n # Scroll grid in rows\n for rgrid in range(SUBGRID_SIZE):\n # Scroll grid in columns\n for cgrid in range(SUBGRID_SIZE):\n # Make Subgrid\n for row in range(SUBGRID_SIZE):\n for column in range(SUBGRID_SIZE):\n subgrid.append(self.solution[row + SUBGRID_SIZE*rgrid][column + SUBGRID_SIZE*cgrid])\n # Check subgrid\n subgrids.append(copy.copy(subgrid))\n subgrid.clear() \n return subgrids\n \n '''\n indexes of subgrids:\n |0|1|2|\n |3|4|5|\n |6|7|8|\n '''\n # Sets a new value (subgrid) to a 3x3 subgrid\n # Is used for CROSSOVER of the genetic algorithm\n def set_3x3_subgrid(self, subgrid, index):\n grid_row = 0\n if (index > 2 and index < 6):\n grid_row = 1\n elif (index >= 6 and index < 10):\n grid_row = 2\n \n subgrid_index = 0\n for row in range(SUBGRID_SIZE):\n for column in range(SUBGRID_SIZE):\n self.solution[row + SUBGRID_SIZE*grid_row][column + SUBGRID_SIZE*(index%3)] = subgrid[subgrid_index]\n subgrid_index += 1\n\n # Randomly swaps two values within a 3x3 subgrid\n # Is used for MUTATION of the genetic algorithm\n def swap_2_values(self, subgrid_index):\n if subgrid_index < 3:\n # 0 -> [0-2], [0-2] \n # 1 -> [0-2], [3-5] \n # 2 -> [0-2], [6-8] \n self.swap(0)\n\n elif subgrid_index > 2 and subgrid_index < 6:\n # 3 -> [3-5], [0-2] \n # 4 -> [3-5], [3-5] \n # 5 -> [3-5], [6-8] \n self.swap(1)\n elif subgrid_index > 5 and subgrid_index < 9:\n # 6 -> [6-8], [0-2] \n # 7 -> [6-8], [3-5] \n # 8 -> [6-8], [6-8] \n self.swap(2)\n \n # Swap two values within a 3x3 subgrid\n # Grid_row is the row where the 3x3 subgrid is located (0, 1 or 2)\n def swap(self, grid_row):\n\n row_1 = random.randrange(0, 3) + grid_row*SUBGRID_SIZE\n column_1 = random.randrange(0, 3) + ((row_1 - grid_row*SUBGRID_SIZE) * SUBGRID_SIZE)\n row_2 = random.randrange(0, 3) + grid_row*SUBGRID_SIZE\n column_2 = random.randrange(0, 3) + ((row_1 - grid_row*SUBGRID_SIZE) * SUBGRID_SIZE)\n # Swap\n aux = self.solution[row_1][column_1]\n self.solution[row_1][column_1] = self.solution[row_2][column_2]\n self.solution[row_2][column_2] = aux\n","repo_name":"GilbertAb/Computability-and-Complexity","sub_path":"Tarea_2/sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":7977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"6787729173","text":"# Source https://github.com/vy007vikas/PyTorch-ActorCriticRL\n\nfrom __future__ import division\nimport numpy as np\nimport random\nfrom collections import deque\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\nfrom agent_baseline import Agent\nfrom env import Env\n\nEPS = 0.003\nBATCH_SIZE = 128\nLEARNING_RATE = 0.001\nGAMMA = 0.95\nTAU = 0.001\nS_DIM = 6\nA_DIM = 2\nA_MAX = 1\nMAX_BUFFER = 1000000\nNOISE_DECAY = 1\n\n\ndef soft_update(target, source, tau):\n \"\"\"\n Copies the parameters from source network (x) to target network (y) using the below update\n y = TAU*x + (1 - TAU)*y\n :param target: Target network (PyTorch)\n :param source: Source network (PyTorch)\n :return:\n \"\"\"\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(target_param.data * (1.0 - tau) + param.data * tau)\n\n\ndef hard_update(target, source):\n \"\"\"\n Copies the parameters from source network to target network\n :param target: Target network (PyTorch)\n :param source: Source network (PyTorch)\n :return:\n \"\"\"\n for target_param, param in zip(target.parameters(), source.parameters()):\n target_param.data.copy_(param.data)\n\n\n# Based on:\n# http://math.stackexchange.com/questions/1287634/implementing-ornstein-uhlenbeck-in-matlab\nclass OrnsteinUhlenbeckActionNoise:\n def __init__(self, action_dim, mu=0, theta=0.15, sigma=0.2):\n self.action_dim = action_dim\n self.mu = mu\n self.theta = theta\n self.sigma = sigma\n self.X = np.ones(self.action_dim) * self.mu\n\n def reset(self):\n self.X = np.ones(self.action_dim) * self.mu\n\n def sample(self):\n dx = self.theta * (self.mu - self.X)\n dx = dx + self.sigma * np.random.randn(len(self.X))\n self.X = self.X + dx\n return self.X\n\n\nclass MemoryBuffer:\n def __init__(self, size):\n self.buffer = deque(maxlen=size)\n self.maxSize = size\n self.len = 0\n\n def sample(self, count):\n \"\"\"\n samples a random batch from the replay memory buffer\n :param count: batch size\n :return: batch (numpy array)\n \"\"\"\n batch = []\n count = min(count, self.len)\n batch = random.sample(self.buffer, count)\n\n s_arr = np.float32([arr[0] for arr in batch])\n a_arr = np.float32([arr[1] for arr in batch])\n r_arr = np.float32([arr[2] for arr in batch])\n s1_arr = np.float32([arr[3] for arr in batch])\n\n return s_arr, a_arr, r_arr, s1_arr\n\n def len(self):\n return self.len\n\n def add(self, s, a, r, s1):\n \"\"\"\n adds a particular transaction in the memory buffer\n :param s: current state\n :param a: action taken\n :param r: reward received\n :param s1: next state\n :return:\n \"\"\"\n transition = (s, a, r, s1)\n self.len += 1\n if self.len > self.maxSize:\n self.len = self.maxSize\n self.buffer.append(transition)\n\n\ndef fanin_init(size, fanin=None):\n fanin = fanin or size[0]\n v = 1.0 / np.sqrt(fanin)\n return torch.Tensor(size).uniform_(-v, v)\n\n\nclass Critic(nn.Module):\n def __init__(self, state_dim, action_dim):\n \"\"\"\n param state_dim: Dimension of input state (int)\n param action_dim: Dimension of input action (int)\n \"\"\"\n super(Critic, self).__init__()\n\n self.state_dim = state_dim\n self.action_dim = action_dim\n\n self.fcs1 = nn.Linear(state_dim, 128)\n self.fcs1.weight.data = fanin_init(self.fcs1.weight.data.size())\n self.fcs2 = nn.Linear(128, 64)\n self.fcs2.weight.data = fanin_init(self.fcs2.weight.data.size())\n\n self.fca1 = nn.Linear(action_dim, 64)\n self.fca1.weight.data = fanin_init(self.fca1.weight.data.size())\n\n self.fc2 = nn.Linear(128, 64)\n self.fc2.weight.data = fanin_init(self.fc2.weight.data.size())\n\n self.fc3 = nn.Linear(64, 1)\n self.fc3.weight.data.uniform_(-EPS, EPS)\n\n def forward(self, state, action):\n \"\"\"\n returns Value function Q(s,a) obtained from critic network\n :param state: Input state (Torch Variable : [n,state_dim] )\n :param action: Input Action (Torch Variable : [n,action_dim] )\n :return: Value function : Q(S,a) (Torch Variable : [n,1] )\n \"\"\"\n s1 = F.relu(self.fcs1(state))\n s2 = F.relu(self.fcs2(s1))\n a1 = F.relu(self.fca1(action))\n x = torch.cat((s2, a1), dim=1)\n\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n\n return x\n\n\nclass Actor(nn.Module):\n def __init__(self, state_dim, action_dim, action_lim):\n \"\"\"\n :param state_dim: Dimension of input state (int)\n :param action_dim: Dimension of output action (int)\n :param action_lim: Used to limit action in [-action_lim,action_lim]\n :return:\n \"\"\"\n super(Actor, self).__init__()\n\n self.state_dim = state_dim\n self.action_dim = action_dim\n self.action_lim = action_lim\n\n self.fc1 = nn.Linear(state_dim, 128)\n self.fc1.weight.data = fanin_init(self.fc1.weight.data.size())\n\n self.fc2 = nn.Linear(128, 64)\n self.fc2.weight.data = fanin_init(self.fc2.weight.data.size())\n\n self.fc3 = nn.Linear(64, action_dim)\n self.fc3.weight.data.uniform_(-EPS, EPS)\n\n def forward(self, state):\n \"\"\"\n returns policy function Pi(s) obtained from actor network\n this function is a gaussian prob distribution for all actions\n with mean lying in (-1,1) and sigma lying in (0,1)\n The sampled action can , then later be rescaled\n :param state: Input state (Torch Variable : [n,state_dim] )\n :return: Output action (Torch Variable: [n,action_dim] )\n \"\"\"\n x = F.relu(self.fc1(state))\n x = F.relu(self.fc2(x))\n # activation function to limit action in [-1,1]\n x = F.sigmoid(x)\n # print(\"inside\", self.fc3(x))\n action = (1 + F.tanh(self.fc3(x))) / 2\n return action\n\n\nclass DDPG(Agent):\n def __init__(self, env):\n \"\"\"\n param env: Environment\n \"\"\"\n ram = MemoryBuffer(MAX_BUFFER)\n self.state_dim = S_DIM\n self.action_dim = A_DIM\n self.action_lim = A_MAX\n self.ram = ram\n self.noise_scale = 1.0\n self.noise_decay = NOISE_DECAY\n self.iter = 0\n self.noise = OrnsteinUhlenbeckActionNoise(self.action_dim)\n\n self.actor = Actor(self.state_dim, self.action_dim, self.action_lim)\n self.target_actor = Actor(self.state_dim, self.action_dim, self.action_lim)\n self.actor_optimizer = torch.optim.Adam(self.actor.parameters(), LEARNING_RATE)\n\n self.critic = Critic(self.state_dim, self.action_dim)\n self.target_critic = Critic(self.state_dim, self.action_dim)\n self.critic_optimizer = torch.optim.Adam(\n self.critic.parameters(), LEARNING_RATE\n )\n\n hard_update(self.target_actor, self.actor)\n hard_update(self.target_critic, self.critic)\n\n def act(self, state):\n \"\"\"\n gets the action from actor added with exploration noise\n :param state: state (Numpy array)\n :return: sampled action (Numpy array)\n \"\"\"\n state = Variable(torch.from_numpy(state))\n action = self.actor.forward(state).detach()\n new_action = (\n action.data.numpy() + self.noise.sample() * self.noise_scale\n ) # + np.random.randn(A_DIM) * 0.5\n self.noise_scale *= self.noise_decay\n return new_action\n\n def optimize(self):\n \"\"\"\n Samples a random batch from replay memory and performs optimization\n :return:\n \"\"\"\n s1, a1, r1, s2 = self.ram.sample(BATCH_SIZE)\n\n s1 = Variable(torch.from_numpy(s1))\n a1 = Variable(torch.from_numpy(a1))\n r1 = Variable(torch.from_numpy(r1))\n s2 = Variable(torch.from_numpy(s2))\n\n # ---------------------- optimize critic ----------------------\n # Use target actor exploitation policy here for loss evaluation\n a2 = self.target_actor.forward(s2).detach()\n next_val = torch.squeeze(self.target_critic.forward(s2, a2).detach())\n # y_exp = r + gamma*Q'( s2, pi'(s2))\n y_expected = r1 + GAMMA * next_val\n # y_pred = Q( s1, a1)\n y_predicted = torch.squeeze(self.critic.forward(s1, a1))\n # compute critic loss, and update the critic\n loss_critic = F.smooth_l1_loss(y_predicted, y_expected)\n self.critic_optimizer.zero_grad()\n loss_critic.backward()\n self.critic_optimizer.step()\n\n # ---------------------- optimize actor ----------------------\n pred_a1 = self.actor.forward(s1)\n loss_actor = -1 * torch.sum(self.critic.forward(s1, pred_a1))\n self.actor_optimizer.zero_grad()\n loss_actor.backward()\n self.actor_optimizer.step()\n\n soft_update(self.target_actor, self.actor, TAU)\n soft_update(self.target_critic, self.critic, TAU)\n\n def train(self, env: Env, episodes=50):\n print(f\"Training agent {self.__class__.__name__}\")\n success = 0\n plot_rewards = []\n plot_success = []\n for eps in range(1, episodes + 1):\n s = np.float32(env.reset())\n score = 0\n while True:\n action = self.act(s)\n for i in range(30):\n env.render()\n\n s2, r, done, info = env.step(action)\n s2 = np.float32(s2)\n self.ram.add(s, action, r, s2)\n s = s2\n score += r\n self.optimize()\n if done:\n break\n if done:\n if r == 100:\n success += 1\n break\n plot_rewards.append(score)\n plot_success.append(success / eps)\n print(\"Episode : \", eps, \" Reward : \", score)\n episode_number = np.arange(1, episodes + 1)\n plt.plot(episode_number, plot_rewards)\n plt.xlabel(\"Episode\")\n plt.ylabel(\"Episode Reward\")\n plt.title(\"DDPG Reward during training\")\n plt.show()\n plt.plot(episode_number, plot_success)\n plt.xlabel(\"Episode\")\n plt.ylabel(\"Success rate since beginning\")\n plt.title(\"DDPG Average success rate during training\")\n plt.show()\n","repo_name":"antoinegleisberg/inf581_parachutist","sub_path":"ddpg_agent.py","file_name":"ddpg_agent.py","file_ext":"py","file_size_in_byte":10539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"32001247003","text":"'''\nCreated on Jun 9, 2015\n\n@author: mewolot\n'''\nfrom cmath import log\nfrom twisted.conch.openssh_compat import primes\n\ndef bitSize(a,b):\n #Finds number of bits of largest number\n if a > b:\n sizenum = a\n else:\n sizenum = b\n size = int((log(sizenum,2)).real) + 1\n return size\n\n#Adds a and b in finite field n\ndef addition(a,b,n):\n return ((a % n) + (b % n)) % n\n\n#Subtracts b from a in finite field n\ndef subtraction(a,b,n):\n return addition(a,-1 * b,n)\n\n#Multiplies a by b in finite field n\ndef multiplication(a,b,n):\n #Number a x 1\n round = abs(a)\n #To check least significant bit of b\n number = abs(b)\n #The total\n total = 0\n while number > 0:\n if (number & 1 == 1):\n total = addition(total,round,n)\n round = round << 1\n number = number >> 1\n if (a < 0 or b < 0) and (a >= 0 or b >=0):\n return total * -1 % n\n return total\n \ndef gcd(num,prime):\n #a = qn + r\n a = prime\n q = num\n #Default r\n r = a\n while r > 0:\n n = a / q\n r = a % q\n a = q\n q = r\n return a\n \ndef eea(num, prime):\n i,j = prime,num\n s,t,u,v = 1,0,0,1\n while j != 0:\n q,r = i // j, i % j\n un, vn = s,t \n s = u - (q * s)\n t = v - (q * t)\n i,j = j,r\n u,v = un, vn \n d,m,n = i,u,v\n return m\n\ndef division(a,b,n):\n newB = eea(b,n)\n return multiplication(a,newB,n)\n\n\n#Proof of Addition/Subtraction\n# print addition(13,57,101)\n# print addition(13,9,23)\n# print subtraction(13,57,101)\n# print subtraction(13,9,23)\n \n#Proof of Multiplication\n# print multiplication(13,9,23) #Desired 16? I think the answer key I am using is wrong\n# print multiplication(13,57,101)\n# print multiplication(123,456,2003) \n# print division(77,13,101)\n \n# print division(77,13,101)\n# print division(13,77,101)\n# print division(123,1234,2003)\n","repo_name":"mwolotsky/Matasano-Crypto-Challenges","sub_path":"Set5/ModMath.py","file_name":"ModMath.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"36146165785","text":"import os\nfrom flask import Flask, request, jsonify, abort\nfrom sqlalchemy import exc\nimport json\nfrom flask_cors import CORS\nimport traceback\n\nfrom .database.models import db_drop_and_create_all, setup_db, Drink\nfrom .auth.auth import AuthError, requires_auth\n\napp = Flask(__name__)\nsetup_db(app)\nCORS(app)\n\n# To be commented from 2nd run or else the database would be reset\ndb_drop_and_create_all()\n\n# ROUTES\n\n'''\n@requires_auth() is not needed for this end point.\nIt is public. Anyone even without token can view it.\n'''\n@app.route('/drinks')\ndef get_drinks():\n '''\n Endpoint to view the drinks. Since It is a public endpoint\n Anyone can view even without loggin in.\n '''\n drinks_list = Drink.query.order_by(Drink.id).all()\n drinks = [drink.short() for drink in drinks_list]\n return jsonify({\n \"success\": True,\n \"drinks\": drinks\n })\n\n\n@app.route('/drinks-detail')\n@requires_auth('get:drinks-detail')\ndef get_drinks_detail(payload):\n '''\n Endpoint to get a detailed view of the drinks\n '''\n drinks_list = Drink.query.order_by(Drink.id).all()\n drinks = [drink.long() for drink in drinks_list]\n return jsonify({\n \"success\": True,\n \"drinks\": drinks\n })\n\n\n@app.route('/drinks', methods=['POST'])\n@requires_auth('post:drinks')\ndef create_drink(payload):\n '''\n Endpoint to create a new drink\n '''\n body = request.get_json()\n new_title = body.get(\"title\", None)\n new_recipe = body.get(\"recipe\", [])\n\n if not new_title or not new_recipe:\n abort(400) # Bad request since body is not in requied format\n\n new_recipe = str(new_recipe) # since list cannot be used in SQL prepared statememts\n new_recipe = new_recipe.replace(\"'\", '\"') # frontend sends recipe with ' that is to be replaced with \"\n\n try:\n drink = Drink(title=new_title, recipe=new_recipe)\n drink.insert()\n\n return jsonify({\n \"success\": True,\n \"drinks\": [drink.long()]\n })\n except Exception as e:\n traceback.print_exc() # useful for debugging\n abort(422) # unexpected errors\n\n\n@app.route(\"/drinks/\", methods=['PATCH'])\n@requires_auth('patch:drinks')\ndef update_drink(payload, id):\n body = request.get_json()\n print(body)\n new_title = body.get(\"title\", None)\n new_recipe = body.get(\"recipe\", [])\n\n if not new_title and not new_recipe:\n abort(400) # Bad request since body is not in requied format\n\n new_recipe = str(new_recipe) # since list cannot be used in SQL prepared statememts\n new_recipe = new_recipe.replace(\"'\", '\"') # frontend sends recipe with ' that is to be replaced with \"\n\n drink = Drink.query.filter(Drink.id == id).one_or_none()\n if drink is None:\n abort(404) # 404 not found if a drink with the id is not in database\n drink.title = new_title\n drink.recipe = new_recipe\n try:\n drink.update()\n\n return jsonify({\n \"success\": True,\n \"drinks\": [drink.long()]\n })\n except Exception as e:\n traceback.print_exc() # useful for debugging\n abort(422) # unexpected errors\n\n\n@app.route(\"/drinks/\", methods=['DELETE'])\n@requires_auth('delete:drinks')\ndef delete_drink(payload, id):\n drink = Drink.query.filter(Drink.id == id).one_or_none()\n if drink is None:\n abort(404) # 404 not found if a drink with the id is not in database\n try:\n drink.delete()\n\n return jsonify({\n \"success\": True,\n \"delete\": id\n })\n except Exception as e:\n traceback.print_exc() # useful for debugging\n abort(422) # unexpected errors\n\n# Error Handling\n\n@app.errorhandler(422)\ndef unprocessable(error):\n '''\n error handling for unprocessable entity\n '''\n return jsonify({\n \"success\": False,\n \"error\": 422,\n \"message\": \"unprocessable\"\n }), 422\n\n\n@app.errorhandler(404)\ndef not_found(error):\n '''\n error handler for 404 not found\n '''\n return (\n jsonify({\n \"success\": False,\n \"error\": 404,\n \"message\": \"resource not found\"\n }), 404,\n )\n\n\n@app.errorhandler(405)\ndef method_not_allowed(error):\n '''\n error handler for 405 method not allowed\n '''\n return (\n jsonify({\"success\": False, \"error\": 405, \"message\": \"method not allowed\"}),\n 405,\n )\n\n\n@app.errorhandler(400)\ndef bad_request(error):\n '''\n error handler for 400 bad request \n '''\n return jsonify({\"success\": False, \"error\": 400, \"message\": \"bad request\"}), 400\n\n\n@app.errorhandler(500)\ndef internal_server_error(error):\n '''\n error handler for 500 internal server error\n '''\n return jsonify({\"success\": False, \"error\": 500, \"message\": \"internal server error\"}), 500\n\n\n@app.errorhandler(AuthError)\ndef handle_auth_error(exeption):\n '''\n error handler for AuthError\n '''\n response = jsonify(exeption.error)\n response.status_code = exeption.status_code\n return response\n","repo_name":"Kavia-M/Udacity-Coffee-Shop-project","sub_path":"backend/src/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"23961665604","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework import status, generics\nfrom .models import Task\nfrom .serializers import TaskSerializer\nimport math\n\nfrom datetime import datetime\n\n\n# Create your views here.\nclass Tasks(generics.GenericAPIView):\n serializer_class = TaskSerializer\n queryset = Task.objects.all()\n\n def post(self, request):\n serializer = self.serializer_class(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response({\"status\": \"success\", \"task\": serializer.data}, status=status.HTTP_201_CREATED)\n else:\n return Response({\"status\": \"fail\", \"message\": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)\n\n def get(self, request):\n page_num = int(request.GET.get(\"page\", 1))\n limit_num = int(request.GET.get(\"limit\", 10))\n start_num = (page_num - 1) * limit_num\n end_num = limit_num * page_num\n search_param = request.GET.get(\"search\")\n tasks = Task.objects.all()\n total_notes = tasks.count()\n if search_param:\n notes = tasks.filter(title__icontains=search_param)\n serializer = self.serializer_class(notes[start_num:end_num], many=True)\n return Response({\n \"status\": \"success\",\n \"total\": total_notes,\n \"page\": page_num,\n \"last_page\": math.ceil(total_notes / limit_num),\n \"tasks\": serializer.data\n })","repo_name":"vickychhetri/restmedjango","sub_path":"task/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"34611090504","text":"import unittest\nfrom unittest import mock\nimport os\nimport subprocess\nfrom testfixtures import TempDirectory\nfrom simplegallery.upload.uploader_factory import get_uploader\n\n\nclass AWSUploaderTestCase(unittest.TestCase):\n def test_no_location(self):\n uploader = get_uploader(\"aws\")\n self.assertFalse(uploader.check_location(\"\"))\n\n @mock.patch(\"subprocess.run\")\n def test_upload_gallery(self, subprocess_run):\n subprocess_run.return_value = subprocess.CompletedProcess([], returncode=0)\n\n with TempDirectory() as tempdir:\n # Setup mock file and uploader\n tempdir.write(\"index.html\", b\"\")\n gallery_path = os.path.join(tempdir.path, \"index.html\")\n uploader = get_uploader(\"aws\")\n\n # Test upload to bucket\n uploader.upload_gallery(\"s3://testbucket/path/\", gallery_path)\n subprocess_run.assert_called_with(\n [\n \"aws\",\n \"s3\",\n \"sync\",\n gallery_path,\n \"s3://testbucket/path/\",\n \"--exclude\",\n \".DS_Store\",\n ]\n )\n\n # Test upload to bucket without prefix\n uploader.upload_gallery(\"testbucket/path/\", gallery_path)\n subprocess_run.assert_called_with(\n [\n \"aws\",\n \"s3\",\n \"sync\",\n gallery_path,\n \"s3://testbucket/path/\",\n \"--exclude\",\n \".DS_Store\",\n ]\n )\n\n # Test upload to bucket without trailing /\n uploader.upload_gallery(\"s3://testbucket/path\", gallery_path)\n subprocess_run.assert_called_with(\n [\n \"aws\",\n \"s3\",\n \"sync\",\n gallery_path,\n \"s3://testbucket/path/\",\n \"--exclude\",\n \".DS_Store\",\n ]\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"haltakov/simple-photo-gallery","sub_path":"simplegallery/test/upload/variants/test_aws_uploader.py","file_name":"test_aws_uploader.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"43"} +{"seq_id":"12234185583","text":"\"\"\"\n===============\no. taylor plot\n===============\n\n.. currentmodule:: easy_mpl\n\nThis file shows the usage of :func:`taylor_plot` function.\n\nA Taylor plot can be used to show statistical summary of one or more measurements/models.\n\n\"\"\"\n\nimport numpy as np\nfrom easy_mpl import taylor_plot\nfrom easy_mpl.utils import version_info\n\nversion_info()\n\n# sphinx_gallery_thumbnail_number = -1\n\n#############################\n\n# The desired covariance matrix.\ncov = np.array(\n [[1, 0.8, 0.6, 0.4, 0.2],\n [0.8, 1.2, 0.8, 0.6, 0.4],\n [0.6, 0.8, 0.8, 0.8, 0.6],\n [0.4, 0.6, 0.8, 1.4, 0.8],\n [0.2, 0.4, 0.6, 0.8, 0.6]]\n)\n\n# Generate the random samples.\nrng = np.random.default_rng(313)\ndata = rng.multivariate_normal(np.zeros(5), cov, size=100)\nprint(data.shape)\n\nobservations = data[:, 0]\nsimulations = {\"LSTM\": data[:, 1],\n \"CNN\": data[:, 2],\n \"TCN\": data[:, 3],\n \"CNN-LSTM\": data[:, 4]}\n_ = taylor_plot(observations=observations,\n simulations=simulations,\n title=\"Taylor Plot\")\n\n#############################\n# multiple taylor plots in one figure\n\ndef create_data(cov, seed=313, mu=np.zeros(5), size=100):\n\n # Generate the random samples.\n rng = np.random.default_rng(seed)\n\n return rng.multivariate_normal(np.zeros(5), cov, size=size)\n\ncov1 = np.array(\n [[1, 0.8, 0.6, 0.4, 0.2],\n [0.8, 1.2, 0.8, 0.6, 0.4],\n [0.6, 0.8, 0.8, 0.8, 0.6],\n [0.4, 0.6, 0.8, 1.4, 0.8],\n [0.2, 0.4, 0.6, 0.8, 0.6]]\n)\n\ncov2 = np.array(\n [[1, 0.8, 0.6, 0.4, 0.2],\n [0.8, 1.2, 0.8, 0.6, 0.4],\n [0.6, 0.8, 0.8, 0.8, 0.6],\n [0.4, 0.6, 0.8, 1.4, 0.8],\n [0.2, 0.4, 0.6, 0.8, 0.6]]\n)\n\ncov3 = np.array(\n [[1, 0.8, 0.6, 0.4, 0.2],\n [0.8, 1.2, 0.8, 0.6, 0.4],\n [0.6, 0.8, 0.8, 0.8, 0.6],\n [0.4, 0.6, 0.8, 1.4, 0.8],\n [0.2, 0.4, 0.6, 0.8, 0.6]]\n)\n\ncov4 = np.array(\n [[1, 0.8, 0.6, 0.4, 0.2],\n [0.8, 1.2, 0.8, 0.6, 0.4],\n [0.6, 0.8, 0.8, 0.8, 0.6],\n [0.4, 0.6, 0.8, 1.4, 0.8],\n [0.2, 0.4, 0.6, 0.8, 0.6]]\n)\n\nsite1_data = create_data(cov1)\nsite2_data = create_data(cov2)\nsite3_data = create_data(cov3)\nsite4_data = create_data(cov4)\n\nobservations = {\n 'site1': site1_data[:, 0],\n 'site2': site2_data[:, 0],\n 'site3': site3_data[:, 0],\n 'site4': site4_data[:, 0],\n}\n\nsimulations = {\n \"site1\": {\"LSTM\": site1_data[:, 1],\n \"CNN\": site1_data[:, 2],\n \"TCN\": site1_data[:, 3],\n \"CNN-LSTM\": site1_data[:, 4]},\n\n \"site2\": {\"LSTM\": site2_data[:, 1],\n \"CNN\": site2_data[:, 2],\n \"TCN\": site2_data[:, 3],\n \"CNN-LSTM\": site2_data[:, 4]},\n\n \"site3\": {\"LSTM\": site3_data[:, 1],\n \"CNN\": site3_data[:, 2],\n \"TCN\": site3_data[:, 3],\n \"CNN-LSTM\": site3_data[:, 4]},\n\n \"site4\": {\"LSTM\": site4_data[:, 1],\n \"CNN\": site4_data[:, 2],\n \"TCN\": site4_data[:, 3],\n \"CNN-LSTM\": site4_data[:, 4]},\n}\n\n# define positions of subplots\n\nrects = dict(site1=221, site2=222, site3=223, site4=224)\n\n_ = taylor_plot(observations=observations,\n simulations=simulations,\n axis_locs=rects,\n plot_bias=True,\n cont_kws={'colors': 'blue', 'linewidths': 1.0, 'linestyles': 'dotted'},\n grid_kws={'axis': 'x', 'color': 'g', 'lw': 1.0},\n title=\"mutiple subplots\")\n#############################\n# using statistics instead of arrays\n\nobservations = {'std': 3.5}\npredictions = { # pbias is optional\n 'Model 1': {'std': 2.80068, 'corr_coeff': 0.49172, 'pbias': -8.85},\n 'Model 2': {'std': 3.8, 'corr_coeff': 0.67, 'pbias': -19.76},\n 'Model 3': {'std': 3.9, 'corr_coeff': 0.596, 'pbias': 7.81},\n 'Model 4': {'std': 2.36, 'corr_coeff': 0.27, 'pbias': -22.78},\n 'Model 5': {'std': 2.97, 'corr_coeff': 0.452, 'pbias': -7.99}}\n\n\n\n_ = taylor_plot(observations,\n predictions)\n\n#############################\n# with customized markers\n\n\ncov = np.array(\n [[1, 0.8, 0.6, 0.4, 0.2],\n [0.8, 1.2, 0.8, 0.6, 0.4],\n [0.6, 0.8, 0.8, 0.8, 0.6],\n [0.4, 0.6, 0.8, 1.4, 0.8],\n [0.2, 0.4, 0.6, 0.8, 0.6]]\n)\n\ndata = create_data(cov)\n\nobservations = data[:, 0]\nsimulations = {\"LSTM\": data[:, 1],\n \"CNN\": data[:, 2],\n \"TCN\": data[:, 3],\n \"CNN-LSTM\": data[:, 4]}\n_ = taylor_plot(observations=observations,\n simulations=simulations,\n marker_kws={'markersize': 10, 'markeredgewidth': 1.5,\n 'markeredgecolor': 'black', 'lw': 0.0})\n\n#############################\n# with customizing bbox\n\n_ = taylor_plot(observations=observations,\n simulations=simulations,\n title=\"custom_legend\",\n leg_kws={'facecolor': 'white',\n 'edgecolor': 'black','bbox_to_anchor':(0.80, 1.1),\n 'fontsize': 14, 'labelspacing': 1.0},\n marker_kws = {'ms':'20', 'markeredgecolor': 'k', 'lw': 0.0},\n )","repo_name":"Sara-Iftikhar/easy_mpl","sub_path":"examples/taylor_plot.py","file_name":"taylor_plot.py","file_ext":"py","file_size_in_byte":5021,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"43"} +{"seq_id":"12566169280","text":"from PyQt5.QtWidgets import QApplication , QWidget\nfrom ui_pages.ui_isci_duzenle import Ui_IsciDuzenleForm\n\n\nclass EditWorkerWindow(QWidget):\n def __init__(self):\n super().__init__()\n self.ui= Ui_IsciDuzenleForm()\n self.ui.setupUi(self)\n\n\nif __name__ == '__main__':\n import sys\n\n app = QApplication(sys.argv)\n app.setStyle(\"fusion\")\n isciduzen = EditWorkerWindow()\n isciduzen.show()\n sys.exit(app.exec_())\n","repo_name":"hhakangull/Yuz-Tanima-Guvenlik-Sistemi-MongoDB","sub_path":"Views/EditWorker.py","file_name":"EditWorker.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"6364172408","text":"with open(\"alphabet\", \"r\") as f:\n letters = f.read().split(\"\\n\")\nLETTER_HEIGHT = 7 # 7 represents the height of each letter from the file\n\nalphabet = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\", \"Y\", \"Z\", \" \"]\n\ndef fancify(name):\n word = \"\"\n for row_number in range(LETTER_HEIGHT): \n for letter in name.upper():\n if letter not in alphabet:\n letter = \" \"\n start = alphabet.index(letter)\n word += letters[start*LETTER_HEIGHT + row_number].strip()\n print(word)\n word = \"\"\n\n#fancify(input())\n\ndef start():\n temp = input(\"Enter some text (Press Enter twice to End):\\n\")\n user_input = [temp]\n while True:\n temp = input()\n if temp == \"\":\n break\n user_input += [temp]\n\n for words in user_input:\n fancify(words)\n\n\nif __name__ == __main__:\n start()\n","repo_name":"aperson2nice/Eastlake2017-2018","sub_path":"Alphabet/RunFancy.py","file_name":"RunFancy.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"26913725317","text":"class Solution:\n def maxPerformance(self, n: int, speed: List[int], efficiency: List[int], k: int) -> int:\n worker = []\n for i in range(n):\n worker.append([speed[i], efficiency[i]])\n worker.sort(key=lambda x:x[1], reverse=True)\n print(worker)\n \n queue = [] # speed 작은애부터 저장할\n maxVal = -pow(10, 5) # sp X eff 해서 최고값. 일단 젤 작은값으로 초기화\n totalSpeed = 0\n for sp, eff in worker:\n if len(queue) < k: # 아직 k만큼 안모였으면 추가\n heappush(queue, sp)\n totalSpeed += sp\n else:\n if sp > queue[0]: # eff가 계속 줄어들기때문에 적어도 speed라도 큐에있는애보단 커야 비교할이유가있음\n totalSpeed -= heappop(queue)\n heappush(queue, sp)\n totalSpeed += sp\n \n maxVal = max(maxVal, totalSpeed * eff)\n \n return maxVal %(pow(10, 9) + 7)\n \n \"\"\"\n efficiency로 내림차순 정렬하고 걔 돌면서 체크\n efficiency랑 짝지어진 speed가 큐에 저장된 애보다 작다면 어차피 바꿀 필요 없음. eff도 작고 speed도 작으니깐\n 그렇지않다면 새로운애를 큐에 추가하고 speed가 작은 원래애는 제거해서 계속 계산했던 값이랑 비교\n \"\"\"\n","repo_name":"yellyB/algorithm","sub_path":"MaximumPerformanceTeam.py","file_name":"MaximumPerformanceTeam.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"22506176458","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\n\nspaces_per_tab = 4\n\nimport os, sys\n\nfor dirpath, dirnames, filenames in os.walk('.'):\n\tfor filename in filenames:\n\t\tif filename[-4:]=='.hpp' or filename[-4:]=='.cpp' or filename[-4:]=='.ipp' or filename[-4:]=='.txt' or filename[-3:]=='.md':\n\t\t\tpath=os.path.join(dirpath, filename)\n\t\t\tif os.path.exists(path+'.orig'):\n\t\t\t\tos.remove(path+'.orig')\n\t\t\tos.rename(path, path+'.orig')\n\t\t\twith open(path, 'wb') as oh:\n\t\t\t\twith open(path+\".orig\", 'rb') as ih:\n\t\t\t\t\tprint(\"Expanding tabs in\", path, \"...\")\n\t\t\t\t\tfor line in ih:\n\t\t\t\t\t\toh.write(line.expandtabs(spaces_per_tab))\n","repo_name":"ned14/quickcpplib","sub_path":"scripts/TabsToSpaces.py","file_name":"TabsToSpaces.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"43"} +{"seq_id":"4536844740","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\nfrom __future__ import print_function\n\nfrom dolfin import (\n XDMFFile,\n Measure,\n FunctionSpace,\n SubMesh,\n project,\n Function,\n info,\n VectorFunctionSpace,\n norm,\n Constant,\n plot,\n SpatialCoordinate,\n grad,\n FiniteElement,\n DOLFIN_EPS,\n as_vector,\n)\nimport matplotlib.pyplot as plt\nimport numpy\nfrom numpy import pi\nfrom numpy import sin, cos\n\nimport maelstrom.maxwell as cmx\nfrom maelstrom.message import Message\n\nimport problems\n\n\ndef test(show=False):\n problem = problems.Crucible()\n # The voltage is defined as\n #\n # v(t) = Im(exp(i omega t) v)\n # = Im(exp(i (omega t + arg(v)))) |v|\n # = sin(omega t + arg(v)) |v|.\n #\n # Hence, for a lagging voltage, arg(v) needs to be negative.\n voltages = [\n 38.0 * numpy.exp(-1j * 2 * pi * 2 * 70.0 / 360.0),\n 38.0 * numpy.exp(-1j * 2 * pi * 1 * 70.0 / 360.0),\n 38.0 * numpy.exp(-1j * 2 * pi * 0 * 70.0 / 360.0),\n 25.0 * numpy.exp(-1j * 2 * pi * 0 * 70.0 / 360.0),\n 25.0 * numpy.exp(-1j * 2 * pi * 1 * 70.0 / 360.0),\n ]\n\n lorentz, joule, Phi = get_lorentz_joule(problem, voltages, show=show)\n\n # Some assertions\n ref = 1.4627674791126285e-05\n assert abs(norm(Phi[0], \"L2\") - ref) < 1.0e-3 * ref\n ref = 3.161363929287592e-05\n assert abs(norm(Phi[1], \"L2\") - ref) < 1.0e-3 * ref\n #\n ref = 12.115309575057681\n assert abs(norm(lorentz, \"L2\") - ref) < 1.0e-3 * ref\n #\n ref = 1406.336109054347\n V = FunctionSpace(problem.submesh_workpiece, \"CG\", 1)\n jp = project(joule, V)\n jp.rename(\"s\", \"Joule heat source\")\n assert abs(norm(jp, \"L2\") - ref) < 1.0e-3 * ref\n\n # check_currents = False\n # if check_currents:\n # r = SpatialCoordinate(problem.mesh)[0]\n # begin('Currents computed after the fact:')\n # k = 0\n # with XDMFFile('currents.xdmf') as xdmf_file:\n # for coil in coils:\n # for ii in coil['rings']:\n # J_r = sigma[ii] * (\n # voltages[k].real/(2*pi*r) + problem.omega * Phi[1]\n # )\n # J_i = sigma[ii] * (\n # voltages[k].imag/(2*pi*r) - problem.omega * Phi[0]\n # )\n # alpha = assemble(J_r * dx(ii))\n # beta = assemble(J_i * dx(ii))\n # info('J = {:e} + i {:e}'.format(alpha, beta))\n # info(\n # '|J|/sqrt(2) = {:e}'.format(\n # numpy.sqrt(0.5 * (alpha**2 + beta**2))\n # ))\n # submesh = SubMesh(problem.mesh, problem.subdomains, ii)\n # V1 = FunctionSpace(submesh, 'CG', 1)\n # # Those projections may take *very* long.\n # # TODO find out why\n # j_v1 = [\n # project(J_r, V1),\n # project(J_i, V1)\n # ]\n # # show=Trueplot(j_v1[0], title='j_r')\n # # plot(j_v1[1], title='j_i')\n # current = project(as_vector(j_v1), V1*V1)\n # current.rename('j{}'.format(ii), 'current {}'.format(ii))\n # xdmf_file.write(current)\n # k += 1\n # end()\n\n filename = \"./maxwell.xdmf\"\n with XDMFFile(filename) as xdmf_file:\n xdmf_file.parameters[\"flush_output\"] = True\n xdmf_file.parameters[\"rewrite_function_mesh\"] = False\n\n # Store phi\n info(\"Writing out Phi to {}...\".format(filename))\n V = FunctionSpace(problem.mesh, \"CG\", 1)\n phi = Function(V, name=\"phi\")\n Phi0 = project(Phi[0], V)\n Phi1 = project(Phi[1], V)\n omega = problem.omega\n for t in numpy.linspace(0.0, 2 * pi / omega, num=100, endpoint=False):\n # Im(Phi * exp(i*omega*t))\n phi.vector().zero()\n phi.vector().axpy(sin(problem.omega * t), Phi0.vector())\n phi.vector().axpy(cos(problem.omega * t), Phi1.vector())\n xdmf_file.write(phi, t)\n\n # Show the resulting magnetic field\n #\n # B_r = -dphi/dz,\n # B_z = 1/r d(rphi)/dr.\n #\n r = SpatialCoordinate(problem.mesh)[0]\n g = 1.0 / r * grad(r * Phi[0])\n V_element = FiniteElement(\"CG\", V.mesh().ufl_cell(), 1)\n VV = FunctionSpace(V.mesh(), V_element * V_element)\n\n B_r = project(as_vector((-g[1], g[0])), VV)\n g = 1 / r * grad(r * Phi[1])\n B_i = project(as_vector((-g[1], g[0])), VV)\n info(\"Writing out B to {}...\".format(filename))\n B = Function(VV)\n B.rename(\"B\", \"magnetic field\")\n if abs(problem.omega) < DOLFIN_EPS:\n B.assign(B_r)\n xdmf_file.write(B)\n # plot(B_r, title='Re(B)')\n # plot(B_i, title='Im(B)')\n else:\n # Write those out to a file.\n lspace = numpy.linspace(\n 0.0, 2 * pi / problem.omega, num=100, endpoint=False\n )\n for t in lspace:\n # Im(B * exp(i*omega*t))\n B.vector().zero()\n B.vector().axpy(sin(problem.omega * t), B_r.vector())\n B.vector().axpy(cos(problem.omega * t), B_i.vector())\n xdmf_file.write(B, t)\n\n filename = \"./lorentz-joule.xdmf\"\n info(\"Writing out Lorentz force and Joule heat source to {}...\".format(filename))\n with XDMFFile(filename) as xdmf_file:\n xdmf_file.write(lorentz, 0.0)\n # xdmf_file.write(jp, 0.0)\n\n return\n\n\ndef get_lorentz_joule(problem, input_voltages, show=False):\n submesh_workpiece = problem.W.mesh()\n\n subdomain_indices = problem.subdomain_materials.keys()\n\n info(\"Input voltages:\")\n info(repr(input_voltages))\n\n if input_voltages is None:\n return None, Constant(0.0)\n\n # Merge coil rings with voltages.\n coils = [\n {\"rings\": coil_domain, \"c_type\": \"voltage\", \"c_value\": voltage}\n for coil_domain, voltage in zip(problem.coil_domains, input_voltages)\n ]\n # Build subdomain parameter dictionaries for Maxwell\n mu_const = {\n i: problem.subdomain_materials[i].magnetic_permeability\n for i in subdomain_indices\n }\n sigma_const = {\n i: problem.subdomain_materials[i].electrical_conductivity\n for i in subdomain_indices\n }\n\n # Function space for magnetic scalar potential, Lorentz force etc.\n V = FunctionSpace(problem.mesh, \"CG\", 1)\n # Compute the magnetic field.\n # The Maxwell equations depend on two parameters that change during the\n # computation: (a) the temperature, and (b) the velocity field u0. We\n # assume though that changes in either of the two will only marginally\n # influence the magnetic field. Consequently, we precompute all associated\n # values.\n dx_subdomains = Measure(\"dx\", subdomain_data=problem.subdomains)\n with Message(\"Computing magnetic field...\"):\n Phi, voltages = cmx.compute_potential(\n coils,\n V,\n dx_subdomains,\n mu_const,\n sigma_const,\n problem.omega,\n convections={}\n # io_submesh=submesh_workpiece\n )\n # Get resulting Lorentz force.\n lorentz = cmx.compute_lorentz(Phi, problem.omega, sigma_const[problem.wpi])\n\n # Show the Lorentz force in the workpiece.\n # W_element = VectorElement('CG', submesh_workpiece.ufl_cell(), 1)\n # First project onto the entire mesh, then onto the submesh; see bug\n # .\n W = VectorFunctionSpace(problem.mesh, \"CG\", 1)\n pl = project(lorentz, W)\n W2 = VectorFunctionSpace(submesh_workpiece, \"CG\", 1)\n pl = project(pl, W2)\n pl.rename(\"Lorentz force\", \"Lorentz force\")\n with XDMFFile(submesh_workpiece.mpi_comm(), \"lorentz.xdmf\") as f:\n f.parameters[\"flush_output\"] = True\n f.write(pl)\n\n if show:\n tri = plot(pl, title=\"Lorentz force\")\n plt.colorbar(tri)\n plt.show()\n\n # Get Joule heat source.\n joule = cmx.compute_joule(\n Phi, voltages, problem.omega, sigma_const, mu_const, subdomain_indices\n )\n\n if show:\n # Show Joule heat source.\n submesh = SubMesh(problem.mesh, problem.subdomains, problem.wpi)\n W_submesh = FunctionSpace(submesh, \"CG\", 1)\n jp = Function(W_submesh, name=\"Joule heat source\")\n jp.assign(project(joule[problem.wpi], W_submesh))\n tri = plot(jp)\n plt.title(\"Joule heat source\")\n plt.colorbar(tri)\n plt.show()\n\n joule_wpi = joule[problem.wpi]\n\n # To work around bug\n # .\n # return the projection `pl` and not `lorentz` itself.\n # TODO remove this workaround\n return pl, joule_wpi, Phi\n\n\nif __name__ == \"__main__\":\n test(show=True)\n","repo_name":"nschloe/maelstrom","sub_path":"examples/test_maxwell.py","file_name":"test_maxwell.py","file_ext":"py","file_size_in_byte":9195,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"43"} +{"seq_id":"2678563180","text":"import pygame\n\n# Create a Dictionary of all the screen resolutions\nScreen_Resolution = {'480p': (854, 480), '720p': (1280, 720), '1080p': (1920, 1080), '1440p': (2560, 1440),\n '2160p': (3840, 2160)}\n\n\nclass GlobalSettings:\n \"\"\"\n The GlobalSettings class stores all the global settings for the Pong game.\n\n Parameters\n ----------\n initial_resolution: tuple\n A tuple representing the initial screen resolution. Defaults to (1280, 720).\n initial_music_on: A boolean indicating whether the music is initially on or off. Defaults to True.\n\n Attributes\n ----------\n MENU_TITLE: str\n Title of the main menu screen.\n SETTINGS_TITLE: str\n Title of the settings screen.\n CREDITS_TITLE: str\n Title of the credits screen.\n GAME_TITLE: str\n Title of the game window.\n GAME_TITLE_VANILLA: str\n Title of the vanilla game window.\n INSTRUCTIONS_TITLE: str\n Title of the instructions screen.\n INSTRUCTIONS_TITLE_VANILLA: str\n Title of the instructions screen for the vanilla game.\n BLACK: tuple\n Color black in RGB format.\n WHITE: tuple\n Color white in RGB format.\n BLUE: tuple\n Color blue in RGB format.\n LIGHT_BLUE: tuple\n Color light blue in RGB format.\n GOLDEN: tuple\n Color golden in RGB format.\n RED: tuple\n Color red in RGB format.\n GRAY: tuple\n Color gray in RGB format.\n FONT_TYPE_DEFAULT: str\n File path to the default font.\n FONT_TYPE_MENU: str\n File path for the font used in the menu screens.\n WIN_SCORE: int\n The score required to win the game.\n SCORE_ADDER_A: int\n Score added to player A when they score a point.\n SCORE_ADDER_B: int\n Score added to player B when they score a point.\n MIN_ADDITIONAL_BALLS: int\n Minimum number of additional balls that can be added to the game.\n MAX_ADDITIONAL_BALLS: int\n Maximum number of additional balls that can be added to the game.\n PADDLE_ROUND_CORNERS_A: int\n Border radius for player A's paddle.\n PADDLE_ROUND_CORNERS_B: int\n Border radius for player B's paddle.\n PADDLE_ROUND_CORNERS_SHIELD: int\n Border radius for the shield paddle.\n POWERUP_VISIBLE_TIME: int\n Time in seconds that a powerup is visible on the screen.\n POWERUP_NAME_VISIBLE_TIME: int\n Time in seconds that the name of the powerup is visible on the screen.\n \"\"\"\n\n # == Static Attributes ==\n # Titles\n MENU_TITLE: str = \"Main Menu\"\n SETTINGS_TITLE: str = \"Settings\"\n CREDITS_TITLE: str = \"Creators\"\n GAME_TITLE: str = \"The PongVerse\"\n GAME_TITLE_VANILLA: str = \"The PongVerse (Vanilla Edition)\"\n INSTRUCTIONS_TITLE: str = \"Instructions\"\n INSTRUCTIONS_TITLE_VANILLA: str = \"Instructions (Vanilla Edition)\"\n\n # Colors\n BLACK: tuple = (0, 0, 0)\n WHITE: tuple = (255, 255, 255)\n BLUE: tuple = (71, 94, 126)\n LIGHT_BLUE: tuple = (202, 230, 250)\n GOLDEN: tuple = (209, 165, 91)\n RED: tuple = (183, 39, 30)\n GRAY: tuple = (44, 44, 44)\n\n # Font Types\n FONT_TYPE_DEFAULT: str = \"font/default_font_pong.ttf\"\n FONT_TYPE_MENU: str = \"font/menu_font.ttf\"\n\n # Score to Win the Game\n WIN_SCORE: int = 10\n\n # Score Adder\n SCORE_ADDER_A: int = 1\n SCORE_ADDER_B: int = 1\n\n # Min and Max of Additional Balls\n MIN_ADDITIONAL_BALLS: int = 2\n MAX_ADDITIONAL_BALLS: int = 4\n\n # Paddle Round Corners\n PADDLE_ROUND_CORNERS_A: int = 5\n PADDLE_ROUND_CORNERS_B: int = 5\n PADDLE_ROUND_CORNERS_SHIELD: int = 0\n\n # Powerup Visible Time\n POWERUP_VISIBLE_TIME: int = 5\n\n # Powerup Name Visible Time\n POWERUP_NAME_VISIBLE_TIME: int = 2\n\n # == Constructor ==\n def __init__(self, initial_resolution: tuple = Screen_Resolution['720p'], initial_music_on: bool = True):\n \"\"\"\n Initialize the GlobalSettings class.\n\n Parameters\n ----------\n initial_resolution: tuple (default: (1280, 720))\n Width and height of the window.\n initial_music_on: bool (default: True)\n State of the music (on/off).\n\n Attributes\n ----------\n\n ---- General ----\n self.resolution: tuple\n Width and height of the window.\n self.width: int\n Width of the window.\n self.height: int\n Height of the window.\n self.font_size_default: int\n Font size of the default font.\n self.font_size_powerup: int\n Font size of the powerup font.\n self.font_size_small_powerup: int\n Font size of the small powerup font.\n self.font_size_menu: int\n Font size of the menu font.\n self.title_size: int\n Font size of the title.\n self.subtitle_size: int\n Font size of the subtitle.\n self.body_size: int\n Font size of the body.\n self.small_body_size: int\n Font size of the small body.\n self.music_on: bool\n State of the music (on/off).\n\n ---- Interface ----\n self.button_width: int\n Width of the buttons.\n self.button_height: int\n Height of the buttons.\n self.small_button_width: int\n Width of the small buttons.\n self.small_button_height: int\n Height of the small buttons.\n self.button_gap: int\n Gap between the buttons.\n self.novaims_icon_size: tuple\n Width and height of the NOVA IMS icon.\n self.novaims_img_load: pygame.Transform\n NOVA IMS icon loaded as a pygame Transform.\n self.sound_on_icon_size: tuple\n Width and height of the sound on icon.\n self.sound_on_img_load: pygame.Transform\n Sound on icon loaded as a pygame Transform.\n self.creator_icon_size: tuple\n Width and height of the creators icons.\n self.creator_1_img_load: pygame.Transform\n Creator 1 icon loaded as a pygame Transform.\n self.creator_2_img_load: pygame.Transform\n Creator 2 icon loaded as a pygame Transform.\n self.creator_3_img_load: pygame.Transform\n Creator 3 icon loaded as a pygame Transform.\n self.creator_4_img_load: pygame.Transform\n Creator 4 icon loaded as a pygame Transform.\n\n ---- Game ----\n self.player_icon_size: tuple\n Width and height of the player icons.\n self.player_a_icon_pos: tuple\n Position of the player A icon.\n self.player_b_icon_pos: tuple\n Position of the player B icon.\n self.pos_score_a: tuple\n Position of the score of player A.\n self.pos_score_b: tuple\n Position of the score of player B.\n self.field_divider_initial_pos: tuple\n Initial position of the field divider.\n self.field_divider_max_pos: tuple\n Maximum position of the field divider.\n\n ---- Win Screen ----\n self.winner_icon_size: tuple\n Width and height of the winner icon.\n\n ---- Instructions ----\n self.background_img: pygame.Transform\n Background image loaded as a pygame Transform.\n self.powerup_width: float\n Width of the powerup icon.\n self.powerup_height: float\n Height of the powerup icon.\n self.right_x_alignment: float\n Right x alignment of the powerup icon in Instructions.\n self.left_x_alignment: float\n Left x alignment of the powerup icon in Instructions.\n self.player_keys_width: float\n Width of the player keys icon.\n self.player_keys_height: float\n Height of the player keys icon.\n self.player_a_up: pygame.Transform\n Player A up key loaded as a pygame Transform.\n self.player_a_down: pygame.Transform\n Player A down key loaded as a pygame Transform.\n self.player_b_up: pygame.Transform\n Player B up key loaded as a pygame Transform.\n self.player_b_down: pygame.Transform\n Player B down key loaded as a pygame Transform.\n self.powerup_icon_pos_list: dict\n Dictionary with the positions of the powerup icons.\n self.escape_key_width: float\n Width of the escape key icon.\n self.escape_key_height: float\n Height of the escape key icon.\n self.escape_key: tuple\n Escape key icon loaded as a pygame Transform.\n\n ---- Ball ----\n self.ball_width: float\n Width of the ball.\n self.ball_height: float\n Height of the ball.\n self.initial_pos_x: float\n Initial x position of the ball.\n self.initial_pos_y: float\n Initial y position of the ball.\n\n ---- Paddles ----\n self.paddle_width_a: float\n Paddle width of player A.\n self.paddle_height_a: float\n Paddle height of player A.\n self.paddle_width_b: float\n Paddle width of player B.\n self.paddle_height_b: float\n Paddle height of player B.\n self.initial_pos_x_a: float\n Initial paddle x position of player A.\n self.initial_pos_y_a: float\n Initial paddle y position of player A.\n self.initial_pos_x_b: float\n Initial paddle x position of player B.\n self.initial_pos_y_b: float\n Initial paddle y position of player B.\n self.paddle_speed_a: float\n Paddle speed of player A.\n self.paddle_speed_b: float\n Paddle speed of player B.\n self.default_paddle_speed: float\n Default paddle speed.\n self.faster_paddle_speed: float\n Faster paddle speed.\n\n ---- Powerups ----\n self.powerup_width: float\n Powerup icon width.\n self.powerup_height: float\n Powerup icon height.\n self.powerup_field_width: tuple\n Set the width of the field where the powerups will appear.\n self.powerup_field_height: tuple\n Set the height of the field where the powerups will appear.\n \"\"\"\n\n # Set window size\n self.resolution: tuple = initial_resolution\n self.width: int = initial_resolution[0]\n self.height: int = initial_resolution[1]\n\n # Set Font Sizes\n self.font_size_default: int = int(self.width / 17)\n self.font_size_powerup: int = int(self.width / 23)\n self.font_size_small_powerup: int = int(self.width / 70)\n self.font_size_menu: int = int(self.width / 40)\n self.title_size: int = int(self.width / 28)\n self.subtitle_size: int = int(self.width / 46)\n self.body_size: int = int(self.width / 78)\n self.small_body_size: int = int(self.width / 90)\n\n # Music On/Off\n self.music_on: bool = initial_music_on\n\n # ---- Interface ----\n\n # Set Menu Buttons size\n self.button_width: int = int(self.width * 0.3)\n self.button_height: int = int(self.height * 0.06)\n self.small_button_width: int = int(self.width * 0.1)\n self.small_button_height: int = int(self.height * 0.06)\n self.button_gap: int = int(self.button_height * 2)\n\n # Set NovaIMS icon size and load in Creators screen\n self.novaims_icon_size: tuple = (self.width * 0.07, self.width * 0.07)\n self.novaims_img_load: pygame.transform = pygame.transform.smoothscale(\n pygame.image.load(\"img/creators/novaims_logo.png\"), self.novaims_icon_size)\n\n # Set Sound On/Off icon size and load in Settings screen\n self.sound_on_icon_size: tuple = (self.width * 0.03, self.width * 0.03)\n self.sound_on_img_load: pygame.transform = pygame.transform.smoothscale(\n pygame.image.load('img/icons/sound_icon.png'), self.sound_on_icon_size)\n\n # Set Creators icon size and load\n self.creator_icon_size: tuple = (self.width * 0.1, self.width * 0.1)\n self.creator_1_img_load: pygame.transform = pygame.transform.smoothscale(\n pygame.image.load(\"img/creators/creator_1.png\"),\n self.creator_icon_size)\n self.creator_2_img_load: pygame.transform = pygame.transform.smoothscale(\n pygame.image.load(\"img/creators/creator_2.png\"),\n self.creator_icon_size)\n self.creator_3_img_load: pygame.transform = pygame.transform.smoothscale(\n pygame.image.load(\"img/creators/creator_3.png\"),\n self.creator_icon_size)\n self.creator_4_img_load: pygame.transform = pygame.transform.smoothscale(\n pygame.image.load(\"img/creators/creator_4.png\"),\n self.creator_icon_size)\n\n # ---- Game ----\n\n # Set Player Team Icon size\n self.player_icon_size: tuple = (self.width / 17, self.width / 17)\n\n # Set PLayer Team Icon Position\n self.player_a_icon_pos: tuple = (self.width / 12, 20)\n self.player_b_icon_pos: tuple = (\n self.width - (self.width / 12 + self.player_icon_size[0]), 20)\n\n # Set Score Position\n self.pos_score_a: tuple = (self.width / 2 - self.font_size_default, 15)\n self.pos_score_b: tuple = (self.width / 2 + self.font_size_default / 1.7, 15)\n\n # Set the Field Divider Height\n self.field_divider_initial_pos: tuple = (self.width / 2, self.height * 0.03)\n self.field_divider_max_pos: tuple = (self.width / 2, self.height - self.height * 0.03)\n\n # ---- Win Screen ----\n\n # Set Winner Icon Size\n self.winner_icon_size: tuple = (self.width / 6, self.width / 6)\n\n # ---- Instructions ----\n\n # Set background Image\n self.background_img: pygame.transform = pygame.transform.scale(\n pygame.image.load(\"img/background/background_instructions.jpg\"), (self.width, self.height))\n\n # Set PowerUp icon Instructions size\n self.powerup_width: float = self.height / 11\n self.powerup_height: float = self.height / 11\n\n # Set Screen Alignments\n self.right_x_alignment: float = (self.width * 0.07)\n self.second_right_x_alignment: float = (self.width * 0.37)\n self.left_x_alignment: float = (self.width * 0.75)\n\n # Set Player keys icon size\n self.player_keys_width: float = self.height / 20\n self.player_keys_height: float = self.height / 20\n\n # Set Player keys icon and position\n self.player_a_up: pygame.transform = (\n pygame.transform.smoothscale(pygame.image.load(\"img/icons/playerA_up.png\"),\n (self.player_keys_width,\n self.player_keys_height)))\n self.player_a_down: pygame.transform = (\n pygame.transform.smoothscale(pygame.image.load(\"img/icons/playerA_down.png\"),\n (self.player_keys_width,\n self.player_keys_height)))\n self.player_b_up: pygame.transform = (\n pygame.transform.smoothscale(pygame.image.load(\"img/icons/playerB_up.png\"),\n (self.player_keys_width,\n self.player_keys_height)))\n self.player_b_down: pygame.transform = (\n pygame.transform.smoothscale(pygame.image.load(\"img/icons/playerB_down.png\"),\n (self.player_keys_width,\n self.player_keys_height)))\n\n # Set the position of a powerup icon in instructions\n self.powerup_icon_pos_list: dict = {'Ant-Man': (self.right_x_alignment, self.height * 0.3),\n 'Black Widow': (self.right_x_alignment, self.height * 0.5),\n 'Scarlet Witch': (self.right_x_alignment, self.height * 0.7),\n 'Quicksilver': (self.second_right_x_alignment, self.height * 0.3),\n 'Iron Man': (self.second_right_x_alignment, self.height * 0.5),\n 'Captain America': (self.second_right_x_alignment, self.height * 0.7)}\n\n # Set Escape key icon size\n self.escape_key_width: float = self.height / 23\n self.escape_key_height: float = self.height / 23\n\n # Set Escape key icon and position\n self.escape_key: tuple = (pygame.transform.smoothscale(pygame.image.load(\"img/icons/esc_key.png\"),\n (self.escape_key_width,\n self.escape_key_height)),\n (self.width * 0.96, self.height * 0.04))\n\n # ---- Ball ----\n\n # Set ball size\n self.ball_width: float = self.width / 20\n self.ball_height: float = self.width / 20\n\n # Set ball initial position\n self.initial_pos_x: float = self.width / 2 - self.ball_width / 2\n self.initial_pos_y: float = self.height / 2 - self.ball_height / 2\n\n # ---- Paddles ----\n\n # Set Paddle A size\n self.paddle_width_a: float = self.height / 50\n self.paddle_height_a: float = self.height / 5\n\n # Set Paddle B size\n self.paddle_width_b: float = self.height / 50\n self.paddle_height_b: float = self.height / 5\n\n # Set PaddleA initial position\n self.initial_pos_x_a: float = 0 + self.paddle_width_a * 2\n self.initial_pos_y_a: float = self.height / 2 - self.paddle_height_a / 2\n\n # Set PaddleB initial position\n self.initial_pos_x_b: float = self.width - self.paddle_width_b * 3\n self.initial_pos_y_b: float = self.height / 2 - self.paddle_height_b / 2\n\n # Paddle Speeds\n self.paddle_speed_a: float = self.height / 144\n self.paddle_speed_b: float = self.height / 144\n self.default_paddle_speed: float = self.height / 144\n self.faster_paddle_speed: float = self.height / 105\n\n # ---- Powerups ----\n\n # Set PowerUp icon size\n self.powerup_width: float = self.height / 8\n self.powerup_height: float = self.height / 8\n\n # Set PowerUp field of view size\n self.powerup_field_width: tuple = (int(self.width * 0.17), int(self.width - self.width * 0.17))\n self.powerup_field_height: tuple = (int(self.height * 0.17), int(self.height - self.height * 0.17))\n","repo_name":"TiagoValenteM/PongVerse","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":18494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"35064855839","text":"\"\"\"\nAssume you have a method isSubstring which checks if one word is a substring of another.\nGiven two string s1 and s2, write code to check if s2 is a rotation of s1 using only one call to isSubstring\n(e.g., \"waterbottle\" is a rotation of \"erbottlewat\")\n\"\"\"\n\n\nclass Solution:\n def stringRotation(self, s1, s2):\n if len(s1) != len(s2) or len(s1) < 1:\n return False\n\n return self.substring(s1 + s1, s2)\n\n def substring(self, s1s1, s2):\n\n i = 0\n j = len(s2)\n #print(s1s1, s2)\n\n while i <= len(s1s1)//2:\n\n if s1s1[i] == s2[0]:\n #print(s1s1[i: i+j])\n if s1s1[i: i+j] == s2:\n return True\n\n i += 1\n\n return False\n\n # letters = list(s1)\n # new_arr = []\n\n # for i in range(len(letters)):\n\n # new_arr = letters[i + 1:] + letters[: i + 1]\n\n # if self.match(new_arr, list(s2)):\n # return True\n\n # return False\n\n # def match(self, new_arr, target):\n\n # return new_arr == target # O(n)\n\n\nsol = Solution()\ns1 = \"waterbottle\"\ns2 = \"erbottlewat\"\nprint(sol.stringRotation(s1, s2))\n","repo_name":"Sen2k9/Algorithm-and-Problem-Solving","sub_path":"CTCI/1.9_String_Rotation.py","file_name":"1.9_String_Rotation.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"21078765705","text":"import pytz\nfrom django.utils import timezone\n\n\nclass BaseEvent:\n def __init__(self, api, github_event):\n self.api = api\n self.created_at = timezone.localtime(pytz.utc.localize(github_event.created_at))\n self.repo = github_event.repo\n self.pull_request = github_event.payload[\"pull_request\"]\n\n def unique_key(self):\n \"\"\"\n Identifier used for uniqueness among other events.\n\n ie. PullRequestReview events should be unique by date,\n even if multiple comments are made on the same PR in the same day\n so these events are considered to have the same identity.\n \"\"\"\n return (\n self.__class__,\n self.created_at.date(),\n self.repo.id,\n self.pull_request[\"id\"],\n )\n\n def to_json(self):\n repo = self.api.get_repo(self.repo.id)\n pull_request_author = self.api.get_user(self.pull_request[\"user\"][\"login\"])\n\n return {\n \"created_at\": self.created_at,\n \"activity_type\": self.subheader,\n \"pull_request\": {\n \"repo\": {\"name\": repo.name, \"url\": repo.html_url},\n \"title\": self.pull_request[\"title\"],\n \"url\": self.pull_request[\"html_url\"],\n \"author\": pull_request_author.name or pull_request_author.login,\n },\n }\n\n\nclass PullRequestEvent(BaseEvent):\n api_type = \"PullRequestEvent\"\n action = \"opened\"\n subheader = \"Pull Requests\"\n\n\nclass PullRequestReviewEvent(BaseEvent):\n api_type = \"PullRequestReviewCommentEvent\"\n action = \"created\"\n subheader = \"PR Reviews\"\n\n\nEVENT_CLASSES = [PullRequestEvent, PullRequestReviewEvent]\n","repo_name":"RevolutionTech/rooster","sub_path":"githubapi/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"42347522430","text":"import pandas as pd\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\ndef indeed_job_scrape(keyword, search_location, no_page, job_type='None', exp_lvl='None'):\r\n ### 'keyword' transformation to fit in with url\r\n keyword = keyword.replace(' ','+')\r\n ### exp_level number convert to query arguement\r\n if exp_lvl == 1:\r\n exp_lvl_str = 'entry_level'\r\n elif exp_lvl == 2:\r\n exp_lvl_str = 'mid_level'\r\n elif exp_lvl == 3:\r\n exp_lvl_str = 'senior_level'\r\n else:\r\n raise ValueError('exp_lvl only accpets 1, 2, or 3')\r\n \r\n ### Data to scrape\r\n # Job title\r\n j_title = []\r\n # Company name\r\n company_name = []\r\n # Salary\r\n salary = []\r\n # Location\r\n location = []\r\n # Rating\r\n company_rating = []\r\n # Posting link\r\n hyperlink = []\r\n # Posting description\r\n j_desc = []\r\n \r\n ### Main scraping loop\r\n for page_index in range(0, no_page*10, 10):\r\n page = 'https://www.indeed.com/jobs?q=' + keyword + '&l=' + search_location + '&jt=' + job_type + '&explvl=' + exp_lvl_str + '&start=' + str(page_index)\r\n print(page)\r\n page_response = requests.get(page, timeout=5)\r\n main_soup = BeautifulSoup(page_response.text, 'html5lib')\r\n for i in main_soup.find_all('div', {'class':'jobsearch-SerpJobCard'}):\r\n # Position title\r\n j_title.append(i.find('a', {'class':'jobtitle'})['title']) \r\n # Company name \r\n company_name.append(i.find('span', {'class':'company'}).text)\r\n # Salary (if information available, 'None' otherwise) \r\n salary.append(i.find('span', {'class':'salaryText'}).text if i.find('span', {'class':'salaryText'}) else 'None') \r\n # Job location \r\n location.append(i.find(attrs={'class':'location'}).text)\r\n # Comapny rating\r\n company_rating.append(i.find('span', {'class':'ratingsContent'}).text if i.find('span', {'class':'ratingsContent'}) else 'None')\r\n # Link to detailed job posting\r\n hyperlink.append('https://www.indeed.com/' + str(i.find('a', {'class':'jobtitle'})['href']))\r\n # Fulljob description\r\n url = 'https://www.indeed.com/' + str(i.find('a', {'class':'jobtitle'})['href'])\r\n url_response = requests.get(url, timeout=5)\r\n soupy_soup = BeautifulSoup(url_response.text, 'html5lib')\r\n j_desc.append(soupy_soup.find('div', {'id':'jobDescriptionText'}).text)\r\n \r\n ### Save to pandas dataframe \r\n df_local = pd.DataFrame({'job_title' : j_title,\r\n 'company_name' : company_name,\r\n 'salary' : salary,\r\n 'job_location' : location,\r\n 'direct_link' : hyperlink,\r\n 'full_description' : j_desc})\r\n return df_local\r\n\r\n# Scraping , first arguement is keyword, second location, thrid number of pages (~19 postings per pages)\r\n# job type and experience level optional\r\n# 1 for entry level jobs, 2 for mid level, and 3 for senior level\r\ndf = indeed_job_scrape('information technology', 'Ohio', no_page=20, exp_lvl=2)\r\n\r\npd.options.display.max_columns = 50\r\ndf.head()\r\n\r\n# Make a copy for each exp level, change the variable accordingly\r\ndf_mid = df.copy()\r\n\r\n# Export csv to current working directory\r\ndf_entry.to_csv('indeed_jobs_entry.csv', index=False)\r\ndf_mid.to_csv('indeed_jobs_mid.csv', index=False)\r\ndf_senior.to_csv('indeed_jobs_senior.csv', index=False)\r\n","repo_name":"ndrwhoang/is4030","sub_path":"mainscraping.py","file_name":"mainscraping.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"75041437248","text":"\nfrom flask_restx import Namespace, Resource, fields as fields_rest\n\nfrom src.util.http_codes import Status\nfrom src.dto.dto import DTOError, DTOBase\n\n\napi_ping = Namespace('ping', description='ping-pong service')\n\n\n@api_ping.route('/')\nclass Ping(Resource):\n @api_ping.response(Status.HTTP_200_OK, 'pong', \n api_ping.model('DTOPing', {\n 'msg': fields_rest.String(\"pong\"),\n })\n )\n def get(self):\n return DTOBase(Status.HTTP_200_OK, {\n \"msg\": \"pong\"\n }).to_response()\n","repo_name":"davidalvarezcastro/TFM_IRRIAPP","sub_path":"software/server/auth/src/controller/ping.py","file_name":"ping.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"74094761409","text":"# Copyright (C) 2011-2012 Mitchell Stokes and Daniel Stokes\r\n\r\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\r\n# this software and associated documentation files (the \"Software\"), to deal in\r\n# the Software without restriction, including without limitation the rights to\r\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\r\n# of the Software, and to permit persons to whom the Software is furnished to do\r\n# so, subject to the following conditions:\r\n\r\n# The above copyright notice and this permission notice shall be included in all\r\n# copies or substantial portions of the Software.\r\n\r\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\n# SOFTWARE.\r\n\r\nfrom .base_state import BaseState\r\n\r\nclass TitleState(BaseState):\r\n\t\"\"\"A state for the title screen\"\"\"\r\n\t\r\n\tui_layout = \"title\"\r\n\t\r\n\tdef client_init(self, main):\r\n\t\t\"\"\"Intialize the client state\"\"\"\r\n\t\tmain['action'] = ''\r\n\t\tmain['ui_system'].load_layout(\"title\", self)\r\n\t\t\r\n\t\tself.current_overlay = \"\"\r\n\t\tmain['start_game'] = False\r\n\t\tmain['overlay_done'] = False\r\n\t\t\r\n\t\tmain['engine'].play_bgm('Heroic Age')\r\n\t\r\n\tdef client_run(self, main):\r\n\t\t\"\"\"Client-side run method\"\"\"\r\n\t\t\r\n\t\tif main['action']:\r\n\t\t\taction = main['action']\r\n\t\t\t\r\n\t\t\tif self.current_overlay:\r\n\t\t\t\tmain['ui_system'].remove_overlay(self.current_overlay)\r\n\t\t\t\tself.current_overlay = \"\"\r\n\t\t\t\r\n\t\t\tif action == 'start':\r\n\t\t\t\tmain['is_host'] = True\r\n\t\t\t\tself.current_overlay = \"start_game_overlay\"\r\n\t\t\telif action == 'join':\r\n\t\t\t\tmain['is_host'] = False\r\n\t\t\t\tself.current_overlay = \"start_game_overlay\"\r\n\t\t\telif action == 'options':\r\n\t\t\t\tprint(\"Options menu isn't implemented yet\")\r\n\t\t\telif action == 'credits':\r\n\t\t\t\tself.current_overlay=\"credits_overlay\"\r\n\t\t\telif action == 'exit':\r\n\t\t\t\tmain['exit'] = True\r\n\t\t\telse:\r\n\t\t\t\t# Sanity check, should never happen\r\n\t\t\t\tprint(\"Unsupported action:\", action)\r\n\t\t\t\t\r\n\t\t\tif self.current_overlay:\r\n\t\t\t\tmain['ui_system'].add_overlay(self.current_overlay, self)\r\n\r\n\t\t\tmain['action'] = ''\r\n\t\t\t\r\n\t\tif main['start_game']:\r\n\t\t\tif self.current_overlay:\r\n\t\t\t\tmain['ui_system'].remove_overlay(self.current_overlay)\r\n\t\t\t\tself.current_overlay = \"\"\r\n\t\t\treturn (\"NetworkSetup\", \"SWITCH\")\r\n\t\t\t\r\n\t\tif main['overlay_done']:\r\n\t\t\tmain['ui_system'].remove_overlay(self.current_overlay)\r\n\t\t\tself.current_overlay = \"\"\r\n\t\t\tmain['overlay_done'] = False\r\n\r\n\t\t\r\n\tdef client_cleanup(self, main):\r\n\t\t\"\"\"Cleanup the client state\"\"\"\r\n\t\tdel main['action']\r\n\t\tdel main['start_game']\r\n\t\tdel main['overlay_done']\r\n","repo_name":"griusfux/conceptrpg2","sub_path":"Data/Scripts/gamestates/title_state.py","file_name":"title_state.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"25185115266","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n# This code is written by Shad Ahammed, \n# Purpose for this kernel is to make exploratory data analysis and prediction modelling of Bike Sharing Dataset\n# The dataset was taken from UCI Machine Learning Repository\n# The dataset contains the hourly and daily count of rental bikes between years 2011 and 2012 in Capital bikeshare system\n# with the corresponding weather and seasonal information.\n# Only the hourly data is considered\n\n\n# Importing the libraries\n\nimport numpy as np\nimport statistics as stat\nimport pandas as pd\nimport matplotlib.pyplot as plt\nget_ipython().magic('matplotlib inline')\nimport seaborn as sn\n\nfrom scipy import stats\nfrom numpy import median\nfrom statsmodels.graphics.gofplots import qqplot\n\nfrom sklearn import model_selection\nfrom sklearn.metrics import mean_squared_log_error, r2_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression, Ridge, HuberRegressor, ElasticNetCV\nfrom sklearn.ensemble import BaggingRegressor, ExtraTreesRegressor, GradientBoostingRegressor, RandomForestRegressor,AdaBoostRegressor\n\n\n# In[21]:\n\n\n# Reading data from the local storage\n\nfilename = 'C:\\\\Users\\\\lenovo\\\\Desktop\\\\Bike-Sharing-Dataset\\\\hour.csv' \ndata = pd.read_csv(filename)\ndata.head(2)\n\n\n# In[3]:\n\n\n# Checking existence of null value in the dataset\n\ndata.isnull().sum()\n\n# No null value is present in the dataset\n\n\n# In[4]:\n\n\n# Changing column name for a nice precise reading\n\ndata.rename(columns={'weathersit':'weather',\n 'mnth':'month',\n 'hr':'hour',\n 'yr':'year',\n 'hum': 'humidity',\n 'cnt':'count'},inplace=True)\n\n\n# In[5]:\n\n\n# Checking data type for each column\n\ndata.dtypes\n\n\n# In[6]:\n\n\n# Some columns need to be deleted because they are ambiguous and add no importance to the analysis\n\ndata = data.drop(['instant','dteday'], axis=1)\n\n# Some data types need to be changed from numerical to categorical\n\ndata['year'] = data.year.astype('category')\ndata['season'] = data.season.astype('category')\ndata['month'] = data.month.astype('category')\ndata['hour'] = data.hour.astype('category')\ndata['holiday'] = data.holiday.astype('category')\ndata['weekday'] = data.weekday.astype('category')\ndata['workingday'] = data.workingday.astype('category')\ndata['weather'] = data.weather.astype('category')\n\n# Confirming the converted datatype\ndata.dtypes\n\n\n# In[7]:\n\n\n## Exploratory Data Analysis\n\n\n# Analyzing the change in bike sharing pattern('count' variable in dataset) with categorical variables\n\nfig,[ax1,ax2,ax3,ax4,ax5,ax6,ax7,ax8] = plt.subplots(nrows=8, figsize=(15,25))\nsn.barplot(x = data['weekday'], y = data['count'],ax = ax1)\nsn.barplot(x = data['season'], y = data['count'],ax = ax2)\nsn.barplot(x = data['month'], y = data['count'],ax = ax3)\nsn.barplot(x = data['holiday'], y = data['count'],ax = ax4)\nsn.barplot(x = data['hour'], y = data['count'],ax = ax5)\nsn.barplot(x = data['weather'], y = data['count'],ax = ax6)\nsn.barplot(x = data['workingday'], y = data['count'],ax = ax7)\nsn.barplot(x = data['year'], y = data['count'],ax = ax8)\n\n# It is evident that each of the above categorical variable has impacts on 'count' variable\n\n\n# In[8]:\n\n\n# Total bike users(count) is sum of registered and casual users. Need to analyze how they vary individually with hour\n# The variation is observed in different circumstances to check how those impact the bike users\n\nfig,axes = plt.subplots(nrows = 3,ncols = 3, figsize=(25,30))\n\nsn.pointplot(x = 'hour', y = 'registered', hue = 'month',data = data,ax = axes[0][0])\nsn.pointplot(x = 'hour', y = 'casual', hue = 'month', data = data,ax = axes[0][1])\nsn.pointplot(x = 'hour', y = 'count', hue = 'month', size = 7, data = data,ax = axes[0][2])\n\nsn.pointplot(x = 'hour', y = 'registered', hue = 'season',data = data,ax = axes[1][0])\nsn.pointplot(x = 'hour', y = 'casual', hue = 'season', data = data,ax = axes[1][1])\nsn.pointplot(x = 'hour', y = 'count', hue = 'season', size = 7, data = data,ax = axes[1][2])\n\nsn.pointplot(x = 'hour', y = 'registered', hue = 'weather',data = data,ax = axes[2][0])\nsn.pointplot(x = 'hour', y = 'casual', hue = 'weather', data = data,ax = axes[2][1])\nsn.pointplot(x = 'hour', y = 'count', hue = 'weather', size = 7, data = data,ax = axes[2][2])\n\n# It is evident from the patterns that number of registered users is dominant in the count of total users\n\n\n# In[9]:\n\n\n# Analyzing the change in bike sharing pattern with numerical variables\n# Regression plot is used to verify if a pattern can be observed between 'count' and numerical variables\n\nfig,[ax1,ax2,ax3] = plt.subplots(ncols = 3, figsize = (20,8))\nplt.rc('xtick', labelsize=10) \nplt.rc('ytick', labelsize=10) \n\nsn.regplot(x = 'temp', y = 'count',data = data,ax = ax1)\nax1.set(title=\"Relation between temperature and count\")\nsn.regplot(x = 'humidity', y = 'count',data = data,ax = ax2)\nax2.set(title=\"Relation between humidity and total count\")\nsn.regplot(x = 'windspeed', y = 'count',data = data,ax = ax3)\nax3.set(title=\"Relation between Windspeed and total count\")\n\n\n# In[10]:\n\n\n# From the regression plot, it is not very clear how the data fit with the regression line\n# To understand the central tendecy, bins can be used in regression plot\n\nax1 = sn.jointplot(x = 'temp', y = 'count',data = data,kind = 'reg', x_bins = 100,x_estimator=np.mean,size = 5)\nax1.fig.suptitle('Relation between Temperature and total count')\nax2 = sn.jointplot(x = 'humidity', y = 'count',data = data,kind = 'reg', x_bins = 100,x_estimator=np.mean,size = 5)\nax2.fig.suptitle('Relation between Humidity and total count')\nax3 = sn.jointplot(x = 'windspeed', y = 'count',data = data,kind = 'reg', x_bins = 100,x_estimator=np.mean,size = 5)\nax3.fig.suptitle('Relation between Windspeed and total count')\n\n# From the plot it is evident there are strong relationship betweek temperature and humidity with 'count' variable\n# It's also evident that windspeed has no significant effect on 'count'\n\n\n# In[11]:\n\n\n# To see how variables are connected with each other, data correlation can be checked \n\ndata_corr = data[['temp', 'atemp', 'casual', 'registered', 'humidity', 'windspeed', 'count']].corr()\nmask = np.array(data_corr)\nmask[np.tril_indices_from(mask)] = False\nfig = plt.subplots(figsize=(15,10))\nsn.heatmap(data_corr, mask=mask, vmax=1, square=True, annot=True,cmap=\"YlGnBu\")\n\n# It is evident that temp and atemp variables are highly correlated\n# temp has positive correlation and humidity has negative correlation with 'count'\n# Again it can be observed that windspeed has little correlation with count\n\n\n# In[12]:\n\n\n# Checking the outliers with boxplot\n\nfig, axes = plt.subplots(nrows=2,ncols=2,figsize=(17,15))\nplt.rc('xtick', labelsize=10) \nplt.rc('ytick', labelsize=10) \n\nsn.boxplot(data=data,y=\"count\",ax=axes[0][0])\nsn.boxplot(data=data,y=\"count\",x=\"season\",hue = \"workingday\",ax=axes[0][1])\nsn.boxplot(data=data,y=\"count\",x=\"month\",hue = \"workingday\",ax=axes[1][0])\nsn.boxplot(data=data,y=\"count\",x=\"hour\",ax=axes[1][1])\n\n\n# In[13]:\n\n\n# To check the skewness of distribution for 'count' variable, Q-Q plot can be drawn\n# Q-Q plot can also verify whether a normal distribution is possible\n\nfig, (ax1,ax2) = plt.subplots(nrows=2, figsize=(12,12))\nsn.distplot(data['count'], ax=ax1)\nax1.set(title=\"Distribution of count\")\nqqplot(data['count'], line='s', ax=ax2)\nax2.set(title=\"Q-Q plot of Count\")\n\n# It is evident that the distribution is not normal as the quantile plot does not fit with the straight line\n\n\n# In[14]:\n\n\n# 'count' variable is the decomposition of 'casual' and 'registered variable'. These 2 variables can be deleted\n# 'atemp' and 'temp' variables are similar almost. Can get rid of these\n# 'windspeed' has not much correlation with 'count'. Can skip it too\n\ndata = data.drop(['atemp', 'casual', 'registered', 'windspeed'], axis=1)\n\n\n# In[15]:\n\n\n# Numbers in the categorical variable are non-binary which can impact wrongly the prediction model\n# One hot encoding is used to convert those variables in binary by creating dummy data\n# To avoid multicolinearity, the first variable in the dummydata is dropped\n\ndata_dummy = data\n\ndef dummify_dataset(dataframe, col):\n dummy_column = pd.get_dummies(dataframe[col], prefix = col, drop_first = True)\n new_data = pd.concat([dataframe,dummy_column],axis = 1)\n new_data = new_data.drop([col], axis=1)\n return new_data\n\ndcol = ['season', 'month', 'hour', 'holiday', 'weekday', 'workingday', 'weather','year']\n\nfor i in range(0,8):\n data_dummy = dummify_dataset(data_dummy,dcol[i])\n \n\n\n# In[16]:\n\n\n# Training and test data is created by splitting the main data. 33% of test data is considered\n\ny = data_dummy['count']\nX = data_dummy.drop(['count'], axis=1)\n\nX_train, X_test, y_train, y_test = train_test_split(X,y,\n test_size=0.33,\n random_state=42)\n\n\n# In[17]:\n\n\n# Comparing performance of the regression models\n\nmodels = [LinearRegression(),\n AdaBoostRegressor(),\n Ridge(),\n HuberRegressor(),\n ElasticNetCV(),\n DecisionTreeRegressor(), \n ExtraTreesRegressor(),\n GradientBoostingRegressor(),\n RandomForestRegressor(),\n BaggingRegressor()]\n\n# A function is wrtten to find out the cross validation score based on mean absolute error\n\ndef test_algorithms(model):\n kfold = model_selection.KFold(n_splits=10, random_state=0)\n mean_dev_scores = model_selection.cross_val_score(model, X_train, y_train, cv=kfold, scoring='neg_mean_absolute_error')\n r2_scores = model_selection.cross_val_score(model, X_train, y_train, cv=kfold, scoring='r2')\n Scores= pd.DataFrame({'Mean deviation':[np.mean(mean_dev_scores)],'R Square':[np.mean(r2_scores)]})\n print(Scores)\n \nfor model in models:\n test_algorithms(model)\n\n\n# In[18]:\n\n\n# It is evident that the ExtraTreeRegressor() has the lowest error rating\n# To find out the best parameters from a list, a function 'GridSearchCV' from Scikit library is used \n\nparameters={'n_estimators': (50,100,500),\n 'max_features': (20,40,50),\n 'min_samples_leaf': (1,5,10),\n 'min_samples_split': (5,10,20)}\n\nclf = GridSearchCV(ExtraTreesRegressor(), parameters,scoring = 'r2')\nclf.fit(X_train,y_train)\n\nprint(clf.best_score_)\nprint(clf.best_params_)\nprint(clf.best_estimator_)\n\n# The r2 score is very reasonable for this dataset which has such huge number of outliers\n\n\n# In[22]:\n\n\n## Performance of the prediction model\n\n# 'count' variables for test data is predicted with the chosen model and parameters\n\nclf = ExtraTreesRegressor(max_features= 40, min_samples_leaf= 1, min_samples_split= 5, n_estimators= 500)\nclf.fit(X_train,y_train)\ny_pred = clf.predict(X_test)\n\n# A regression plot can be drawn between actual and predicted data to understand the performance of the model\n# Bins are used to make the pattern more meaningful\n\nax = sn.regplot(y_test,y_pred,x_bins = 200)\nax.set(title = \"Comparison between the actual vs prediction\")\n\n\n# In[34]:\n\n\n# Another regression plot to understand the error residuals from actual test data\n\ny_res = y_test - y_pred\nax = sn.regplot(y_test,y_res)\nax.set(title = \"Comparison between the actual vs residual\")\n\n# From the plot it is visible that the deviations from actual test data are not very high and restricted in a limit\n# It is another proof for the preciseness of the prediction model\n\n","repo_name":"ShadAhammed/BikeSharing-Prediction-Model-in-Python","sub_path":"Bike-Sharing-Data.py","file_name":"Bike-Sharing-Data.py","file_ext":"py","file_size_in_byte":11577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"26602024381","text":"# DHT11\n'''\nSteps for using DHT11\n- create library folder on desktop of RasPi\n- git clone https://github.com/adafruit/Adafruit_Python_DHT\n- from the cloned folder\n\n- sensor = Adafruit_DHT.DHT11\n'''\nimport Adafruit_DHT\nimport time\n\n# Set up the sensor\nDHT_SENSOR = Adafruit_DHT.DHT11\nDHT_PIN = 4 #pin 7 on pi\n\nwhile True:\n # Try to get a reading from the sensor\n humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)\n\n # If the reading was successful, print the values\n if humidity is not None and temperature is not None:\n print(f\"Temperature: {temperature:.1f}°C, Humidity: {humidity:.1f}%\")\n else:\n print(\"Failed to read sensor data\")\n\n # Wait a little bit before taking the next reading\n time.sleep(2)\n\n# RFID\n'''\nEnable SPI in RasPi\n- sudo raspi-config\n- select “P4 SPI\"\n- restart RasPi\n- checking if SPI is enabled or not\n\ngettting RasPi python ready\n- sudo apt-get update\n- sudo apt-get upgrade\n- sudo apt-get install python3-dev python3-pip\n- sudo pip3 install spidev\n- sudo pip3 install mfrc522\n- \n'''\n# RFID Read\nimport RPi.GPIO as GPIO\nfrom mfrc522 import SimpleMFRC522\n\nreader = SimpleMFRC522()\n\ntry:\n id, text = reader.read()\n print(id)\n print(text)\nfinally:\n GPIO.cleanup()\n\n# RFID Write\nimport RPi.GPIO as GPIO\nfrom mfrc522 import SimpleMFRC522\n\nreader = SimpleMFRC522()\n\ntry:\n text = input('New data:')\n print(\"Now place your tag to write\")\n reader.write(text)\n print(\"Written\")\nfinally:\n GPIO.cleanup()\n\n# BLE \n'''\nSetting Up BLE\n- sudo apt-get install bluemanbluez Bluetooth\n'''","repo_name":"mathur-exe/IoT","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"71937432140","text":"class ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n dummy = cur = ListNode(0)\n carry = 0\n while l1 or l2 or carry:\n if l1:\n carry += l1.val\n l1 = l1.next\n if l2:\n carry += l2.val\n l2 = l2.next\n cur.next = ListNode(carry % 10)\n cur = cur.next\n carry //= 10\n return dummy.next\n\n\nif __name__ == '__main__':\n s = Solution()\n lst1 = ListNode(2)\n lst1.next = ListNode(4)\n lst1.next.next = ListNode(3)\n lst2 = ListNode(5)\n lst2.next = ListNode(6)\n lst2.next.next = ListNode(4)\n res = s.addTwoNumbers(lst1, lst2)\n assert res.val == 7\n assert res.next.val == 0\n assert res.next.next.val == 8\n","repo_name":"SmirnovVN/leetcode","sub_path":"medium/add_two_numbers/shorter.py","file_name":"shorter.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"26495817970","text":"from time import time\n\n\ndef prime_fact(n):\n pf_lst = []\n d = 2\n while n > 1:\n while n % d == 0:\n pf_lst.append(d)\n n //= d\n if d * d > n and n > 1:\n pf_lst.append(n)\n break\n d += 1\n return pf_lst\n\n\ndef div_func(n):\n pf_lst = prime_fact(n)\n pf_dict = {}\n for i in pf_lst:\n pf_dict[i] = pf_dict.get(i, 0) + 1\n result = 1\n for i in pf_dict:\n result *= pf_dict[i] + 1\n return result\n\n\nstart_time = time()\ni = 1\nwhile div_func(i * (i + 1) / 2) <= 500:\n i += 1\n\nend_time = time()\n\nprint('{time:.4f} seconds spent'.format(time=end_time - start_time))\nprint(i * (i + 1) / 2)\nprint(sum(range(i + 1)))\n\n# 76576500\n# 3.5862 seconds spent\n","repo_name":"oleksandr-shanin/python-qa-lab","sub_path":"project_euler/012.py","file_name":"012.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"31703509873","text":"#!/usr/bin/env python\nimport os, operator, itertools\nfrom credo.systest import *\nfrom credo.modelrun import ModelRun, SimParams\nfrom credo.modelsuite import StgXMLVariant\nimport credo.modelsuite as msuite\nimport credo.jobrunner\nimport credo.io.stgfreq as stgfreq\nimport credo.reporting.standardReports as sReps\nfrom credo.reporting import getGenerators\n\ntestSuite = SysTestSuite(\"Underworld\", \"SciBench-ThermalConv-Scaling\")\nsciBTest = SciBenchmarkTest(\"ThermalConvScalingBenchmark\")\nsciBTest.description = \"\"\"Tests Underworld can perform thermal convection\n with key input parameters scaled across a wide range of values. See\n the file scalingSuite_MathsExplanation.[tex|pdf] for a full explanation.\"\"\"\ntestSuite.sysTests.append(sciBTest)\n## Configure the model and suite to use for this benchmark\nmRun = ModelRun(\"ThermalConvection_Scaling\", \n \"ThermalConvectionBenchmark_Dim.xml\",\n simParams=SimParams(nsteps=2000, dumpevery=100))\nmRun.paramOverrides[\"steadySteps\"] = 100\nmRun.paramOverrides[\"tolerance\"] = 0.0005\nsciBTest.mSuite.templateMRun=mRun\n# A set of scaled parameters we will iterate through in a series of runs.\nmSuite = sciBTest.mSuite\n# Parameters: boxSize, visc, alpha, gravity, diffusion, B.C. temp\nparamSets = [\n (1.0e8, 2.5e19, 2.5e-5, 10, 1.0, 1000),\n (1.0, 2.5e19, 2.5e-5, 10, 1.0e-6, 1.0e21),\n (1.0e6, 1.0e24, 1.0, 10, 1.0e-6, 1000),\n (1.0e6, 2.5e19, 2.5e-4, 1, 1.0e-6, 1000),\n (1.0e6, 2.5e19, 2.5e-5, 10, 1.0e-6, 1000),\n (1.0e6, 1.0, 2.5e-5, 10, 2.5e+13,1000),\n (1.0e6, 2.5e19, 2.5e-5, 1.0e4, 1.0e-6, 1)\n ]\n# The last run has very high gravity, which would require an incompressible\n# formulation\n\nBoxSize = map(operator.itemgetter(0), paramSets)\nviscRange = map(operator.itemgetter(1), paramSets)\nalphaRange = map(operator.itemgetter(2), paramSets)\ngravityRange = map(operator.itemgetter(3), paramSets)\ndiffRange = map(operator.itemgetter(4), paramSets)\nBCtempRange = map(operator.itemgetter(5), paramSets)\n\nmSuite.addVariant(\"X\", StgXMLVariant(\"maxX\", BoxSize))\nmSuite.addVariant(\"Y\", StgXMLVariant(\"maxY\", BoxSize))\nmSuite.addVariant(\"viscosity\", StgXMLVariant(\"components.viscosity.eta0\",\n viscRange))\nmSuite.addVariant(\"alpha\", StgXMLVariant(\"components.material.alpha\",\n alphaRange))\nmSuite.addVariant(\"gravity\", StgXMLVariant(\"gravity\", gravityRange))\nmSuite.addVariant(\"diffusion\", StgXMLVariant(\"defaultDiffusivity\", diffRange))\n#This is a derived parameter based on the BCtempRange\nICpertAmpRange = [bcMax * 0.1 for bcMax in BCtempRange]\nmSuite.addVariant(\"BCcoord\",\n StgXMLVariant(\"SinusoidalTempIC_TopLayerCoord\", BoxSize))\nmSuite.addVariant(\"BCtempBot\",\n StgXMLVariant(\"SinusoidalTempIC_BottomLayerBC\", BCtempRange))\nmSuite.addVariant(\"ICpertAmp\",\n StgXMLVariant(\"SinusoidalTempIC_PerturbationAmplitude\", ICpertAmpRange))\nmSuite.addVariant(\"tempBCval\",\n StgXMLVariant(\"temperatureBCs.vcList[0].variables[0].value\", BCtempRange))\nsciBTest.mSuite.generateRuns(iterGen=itertools.izip)\n#Visualisation customisation - don't set as a 'variant' since it's a derived\n # parameter, just adjust directly.\nfor mRun, tempRange in zip(mSuite.runs, BCtempRange):\n tInt = tempRange/10.0\n mRun.paramOverrides[\"components.temperatureContours.interval\"] = tInt\n\n## Configure tests to apply\n# Need this scaling factor array to do the Vrms within Range check:\nvrmsScalingFactors = [1.0e-8, 1.0e-6, 1.0e-12, 1.0e-12, 1.0e-12,\n 2.5e7, 1.0e-12]\nsciBTest.setupEmptyTestCompsList()\nfor runI, mRun in enumerate(sciBTest.mSuite.runs):\n vrmsMin = 42.0*vrmsScalingFactors[runI]\n vrmsMax = 45.0*vrmsScalingFactors[runI]\t\n if mSuite.modelVariants['gravity'].paramRange[runI] < 10.1:\n sciBTest.addTestComp(runI, \"Scaled VRMS\",\n OutputWithinRangeTC(\"Vrms\", stgfreq.lastOp, (vrmsMin, vrmsMax)))\n else:\n mSuite.runDescrips[runI] += \" (Not applying test for runs with\"\\\n \" Gravity > 10, as this requires a compressible formulation.)\"\n\ndef customReporting(sciBTest, mResults): \n #Plotting/CSV writing\n for mRes in mResults: mRes.readFrequentOutput()\n vrmsTCs, vrmsResults = sciBTest.getTCRes(\"Scaled VRMS\")\n recSteps = [mRes.freqOutput.finalStep() for mRes in mResults]\n vrmsActuals = [mRes.freqOutput.getValueAtStep(\"Nusselt\", ns) \\\n for mRes, ns in zip(mResults, recSteps)]\n nusseltActuals = [mRes.freqOutput.getValueAtStep(\"Nusselt\", ns) \\\n for mRes, ns in zip(mResults, recSteps)]\n for mRes in mResults: \n mRes.freqOutput.plotOverTime('Vrms', depName='Time', show=False,\n path=mRes.outputPath)\n mRes.freqOutput.plotOverTime('Nusselt', depName='Time', show=False,\n path=mRes.outputPath)\n observables = {'Vrms':vrmsActuals, 'Vrms Pass':vrmsResults,\n 'Nusselt':nusseltActuals, 'nSteps':recSteps,\n 'ScalingFac':vrmsScalingFactors}\n msuite.writeInputsOutputsToCSV(sciBTest.mSuite, observables,\n \"scalingResults.csv\")\n # Actually for this benchmark, we want to show the VRMS and Nusselt\n # images generated in _each run_\n sciBTest.mSuite.analysisImages = None\n #sciBTest.mSuite.analysisImages = [\n # 'VrmsAndNusseltValues.png',\n # 'Nusselt-multiRunTimeSeries.png',\n # 'Vrms-multiRunTimeSeries.png']\n sciBTest.mSuite.modelImagesToDisplay = [[] for runI in \\\n range(len(sciBTest.mSuite.runs))]\n lastImgSteps = []\n for finalStep, mRun in zip(recSteps, sciBTest.mSuite.runs):\n simParams = mRun.getSimParams()\n lastImgSteps.append(simParams.nearestDumpStep(finalStep, finalStep))\n for runI in range(len(mResults)):\n sciBTest.mSuite.modelImagesToDisplay[runI] = [\n (0, \"initial\"),\n (lastImgSteps[runI], \"final\")]\n for rGen in getGenerators([\"RST\", \"ReportLab\"], sciBTest.outputPathBase):\n sReps.makeSciBenchReport(sciBTest, mResults, rGen,\n os.path.join(sciBTest.outputPathBase, \"%s-report.%s\" %\\\n (sciBTest.testName, rGen.stdExt)), imgPerRow=2)\n\nsciBTest.setCustomReporting(customReporting)\n\ndef suite():\n return testSuite\n\nif __name__ == \"__main__\":\n postProcFromExisting = True\n jobRunner = credo.jobrunner.defaultRunner()\n testResult, mResults = sciBTest.runTest(jobRunner, postProcFromExisting,\n createReports=True)\n","repo_name":"underworldcode/underworld1","sub_path":"Underworld/SysTest/ScienceBenchmarks/credo_thermalScalingSuite.py","file_name":"credo_thermalScalingSuite.py","file_ext":"py","file_size_in_byte":6309,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"40539387841","text":"\nimport numpy as npy\nnombre = \"\"\nhora = \"\"\nsistole = ''\ndiastole = ''\ndia = []\nsem = []\nperiodo = []\n\nclass MatrizPresion(object):\n \"\"\" Clase que define como funciona\"\"\"\n def __init__(self):\n self.periodo = \"\"\n \n \n def diario(self, datodia): \n x = self.datodia[\"nombre\", \"hora\",]\n dia = x\n print (dia)\n return dia\n\n def semanal(self, datosemana):\n a = self.datosemana.append(diario)\n sem = a\n print (sem)\n return sem\n \n \n def periodico(self, datoperiodo): \n b = self.datoperiodo.append(semanal)\n per = b\n print(per)\n return per\n \n def analisis(self, analisis):\n x = self.datoperiodo\n ord = npy.array([x])# convertido el array a numpy podemos realizar los calculos que deseemos\n \n return ord\n print (ord)\n","repo_name":"FrankGalanDev/arterial_pressure_data","sub_path":"arterial_pressure analisys class.py","file_name":"arterial_pressure analisys class.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"25693046650","text":"_base_ = [\n '../../../configs/_base_/models/bisenetv2.py',\n '../../../configs/_base_/datasets/mmotu.py', '../../../configs/_base_/default_runtime.py',\n '../../../configs/_base_/schedules/schedule_80k.py'\n]\nnorm_cfg = dict(type='SyncBN', requires_grad=True)\nlr_config = dict(warmup='linear', warmup_iters=1000)\noptimizer = dict(lr=0.05)\nmodel = dict(\n decode_head=dict(\n num_classes=2,\n ),\n auxiliary_head=[\n dict(\n type='FCNHead',\n in_channels=16,\n channels=16,\n num_convs=2,\n num_classes=2,\n in_index=1,\n norm_cfg=norm_cfg,\n concat_input=False,\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n dict(\n type='FCNHead',\n in_channels=32,\n channels=64,\n num_convs=2,\n num_classes=2,\n in_index=2,\n norm_cfg=norm_cfg,\n concat_input=False,\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n dict(\n type='FCNHead',\n in_channels=64,\n channels=256,\n num_convs=2,\n num_classes=2,\n in_index=3,\n norm_cfg=norm_cfg,\n concat_input=False,\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n dict(\n type='FCNHead',\n in_channels=128,\n channels=1024,\n num_convs=2,\n num_classes=2,\n in_index=4,\n norm_cfg=norm_cfg,\n concat_input=False,\n align_corners=False,\n loss_decode=dict(\n type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)),\n ])\nwork_dir = './experiments/bisenetv2_fcn_769x769_80k_MMOTU/results/'\nworkflow = [('train', 1)]\n","repo_name":"cv516Buaa/MMOTU_DS2Net","sub_path":"experiments/bisenetv2_fcn_769x769_80k_MMOTU/config/bisenetv2_fcn_769x769_80k_MMOTU.py","file_name":"bisenetv2_fcn_769x769_80k_MMOTU.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"46"} +{"seq_id":"2700653477","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 18 19:03:12 2017\n\n@author: Mitja Jancic\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io\nimport pandas as pd\n\nsilverbox_data = scipy.io.loadmat('C:/Users/mitja/Documents/magisterij/sinteticni/sb.mat')\n#training and test data\nsb_train = silverbox_data['data_train']\nsb_test = silverbox_data['data_test']\n\nfig = plt.figure(figsize=(6,5))\nplt.subplot(2,1,1)\nplt.plot(sb_train[:300,0],'k-o',label='u(k)',markersize=3)\nplt.xlabel('k')\nplt.grid()\nplt.legend(shadow=True)\nplt.xlim(0,300)\nplt.subplot(2,1,2)\nplt.plot(sb_train[:300,1],'k-o',label='y(k)',markersize=3)\nplt.xlabel('k')\nplt.legend(shadow=True)\nplt.xlim(0,300)\nplt.grid()\nplt.show()\nplt.tight_layout()\nfig.savefig('C:/Users/mitja/Documents/magisterij/latex/sinteticni/vhod_izhod.pdf',fig)","repo_name":"distractor/magisterij","sub_path":"magisterij/python check/izris_SB_vhodni_izhodni_podatki.py","file_name":"izris_SB_vhodni_izhodni_podatki.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"72257425101","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 14 19:03:32 2018\n\n@author: My family\n\"\"\"\ndef main():\n list_1 = []\n list_2 = []\n \n list_1_count = int(input(\"Enter the total amount of numbers in set A: \"))\n \n for i in range(1,list_1_count + 1):\n number = int(input(\"Enter: \"))\n list_1.append(number)\n \n list_2_count = int(input(\"Enter the total amount of numbers in set B: \"))\n \n for i in range(1,list_2_count + 1):\n number = int(input(\"Enter: \"))\n list_2.append(number)\n \n print(\"Set A: \",list_1)\n print(\"Set B: \",list_2)\n print(\"The intersection of A and B: \" ,intersection(list_1,list_2))\n print(\"The union of A and B: \" ,union(list_1,list_2))\n print(\"The difference of A and B: \" ,difference(list_1,list_2))\n print(\"The Cartesian Product of A and B: {(\" , end=\"\")\n cartesian(list_1,list_2)\n \ndef union(list_1, list_2,):\n union_A_B = list(set(list_1 + list_2))\n return union_A_B\n\ndef difference(list_1,list_2):\n difference_A_B = list(set(list_1) - set(list_2))\n return difference_A_B\n\ndef intersection(list_1,list_2):\n intersection_ = set(list_1).intersection(list_2)\n return intersection_\n\ndef cartesian(list_1,list_2):\n for a in list_1:\n for b in list_2:\n print(a,\", \", b , sep=\"\" , end=\"\")\n if a==list_1[-1] and b==list_2[-1]:\n print(\")}\")\n else:\n print(\"), (\", end = \"\")\nmain()","repo_name":"k3vin-garcia/ENGR350-section-2","sub_path":"Lab2_Kevin_Garcia.py","file_name":"Lab2_Kevin_Garcia.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"26655334969","text":"import torch\nfrom typing import List, Tuple\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom src.architectures.spectral.spectral_norm_fc import spectral_norm_fc\nfrom src.architectures.spectral.spectral_batchnorm import SpectralBatchNorm1d\n\n\nclass TabularEncoder(nn.Module):\n \"\"\"\n Encoder for tabular data with bi-Lipschitz property using residual connections and spectral normalization.\n \"\"\"\n\n def __init__(\n self,\n input_dim: int,\n hidden_dims: List[int],\n output_dim: int,\n *,\n residual: bool = False,\n spectral: Tuple[bool, bool, bool] = (False, False, False), # (spectral_fc, spectral_conv, spectral_bn)\n lipschitz_constant: float = 1.0,\n n_power_iterations: int = 1,\n bn_out: bool = False,\n reconst_out: bool = False,\n ):\n \"\"\"\n Args:\n input_dim: The dimension of the inputs.\n hidden_dims: The dimensions of the hidden layers.\n output_dim: The dimension of the output, i.e. the latent space.\n spectral: Use the spectral normalization \n residual: Use residual shortcut connection\n lipschitz_constant: The lipschitz constant constraint\n n_power_iterations: Number of iterations for the spectral normalization\n bn_out: Add batch normalization to the output\n reconst_out: Act as the decoder: forward() will output a single value instead of a tuple\n \"\"\"\n super(TabularEncoder, self).__init__()\n\n def wrapper_fc(in_dim, out_dim):\n if spectral[0]:\n return spectral_norm_fc(nn.Linear(in_dim, out_dim), lipschitz_constant, n_power_iterations)\n return nn.Linear(in_dim, out_dim)\n\n def wrapped_bn(num_features):\n if spectral[2]:\n return SpectralBatchNorm1d(num_features, lipschitz_constant) \n return nn.BatchNorm1d(num_features)\n\n # Define the architecture\n self.linear_in = wrapper_fc(input_dim, hidden_dims[0])\n self.layers = nn.ModuleList([\n _TabularBlock(wrapper_fc, hidden_dims[0], residual) for _ in hidden_dims\n ])\n self.linear_out = wrapper_fc(hidden_dims[0], output_dim)\n\n # Add BN at the end to stabilize the training: It facilitates the match between the \n # latent positions output by the encoder and non-zero density regions learned by the normalizing flows. \n self.bn_out = wrapped_bn(output_dim) if bn_out else None\n\n # Is this used as a decoder\n self.reconst_out = reconst_out\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n out = self.linear_in(x)\n for layer in self.layers:\n out = layer(out)\n out = self.linear_out(out)\n\n # Add BN to the output\n if self.bn_out:\n out = self.bn_out(out)\n\n # Return the input for the reconstruction decoder\n if self.reconst_out and self.training:\n return out, out\n\n return out\n\n\nclass _TabularBlock(nn.Module):\n \"\"\"\n Linear layer with bi-Lipschitz property using residual connections and spectral normalization.\n \"\"\"\n\n def __init__(self, wrapper_fc, dim: int, residual: bool = False):\n super(_TabularBlock, self).__init__()\n self.linear = wrapper_fc(dim, dim)\n self.residual = residual\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n identity = x\n\n out = self.linear(x)\n if self.residual:\n out += identity\n out = F.relu(out)\n\n return out\n","repo_name":"orientino/dum-components","sub_path":"src/architectures/encoder/tabular.py","file_name":"tabular.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"46"} +{"seq_id":"34911999299","text":"import os\nimport sys\nimport json\nfrom json.decoder import JSONDecodeError\nimport spotipy\nimport spotipy.util as util\nimport requests\nimport re\nfrom itunesLibrary import library\n#6si8blnqlfxm2ddj5ysr6mu8v\nclientID = \"80b8f78731794ffcbd85198c5d794938\"\nsecretID = \"d9c3c2b0fe514a888187744f7dbdb797\"\nredirect = \"http://localhost:8888\"\nuserID = sys.argv[1]\noAuthToken = util.prompt_for_user_token(userID, scope = \"playlist-modify-public\",client_id=clientID, client_secret=secretID,redirect_uri=redirect)\n#print(\"oAuth Token is: \"+oAuthToken)\nif (oAuthToken):\n sp=spotipy.Spotify(auth=oAuthToken)\nelse:\n print(\"bad authentication\")\n\ndef makePlayList(nameOfPlaylist):\n url = \"https://api.spotify.com/v1/users/{}/playlists\".format(userID)\n body = json.dumps({ \"name\":nameOfPlaylist, \"public\":True, \"collaborative\":False, \"description\":\"playlist made using python by ken\"} )\n tempVar = \"Bearer {}\".format(oAuthToken)\n header = { \"Content-Type\":\"application/json\",\"Authorization\":tempVar}\n toString = requests.post(url,data=body, headers=header)\n theString = toString.json()\n return theString[\"id\"]\ndef searchSong(n):\n song = n\n result = sp.search(song,limit = 1,offset=0,type='track')\n toString = json.dumps(result,sort_keys=True,indent=3)\n f = re.findall('external_urls(.+?)}',toString)\n s=result['tracks']['items'][0][\"external_urls\"]['spotify']\n #print(s)\n return s\n \ndef addSongToPlayList(playlistID,theSong):\n temp = theSong\n song=searchSong(temp)\n songList = []\n songList.append(song)\n sp.user_playlist_add_tracks(user=userID,playlist_id=playlistID,tracks=songList,position=None)\n#searchSong(\"J. Cole 2014 Forest Hills Drive Wet Dreamz\")\n\n#location = input(\"what is the location of the xml file?\")\n #for future users, this could be inputted so that this doesn't only work on my laptop\n\n#some Apple Music Songs don't exist or we pulled a local file from the computer and will return failed songs\nlocation = '/Users/kenichimatsuo/Desktop/XMLFiles/Library.xml'\nlib = library.parse(location)\nfor i in lib.playlists:\n length = len(str(i))\n playlistTitle = str(i)[2:length]\n index = 0\n for j in range(len(playlistTitle)):\n if (playlistTitle[j]==\"'\"):\n index = j\n actualPlaylistTitle = playlistTitle[0:index]\n if(actualPlaylistTitle!=\"Library\" and actualPlaylistTitle != \"Downloaded\" and actualPlaylistTitle != \"Music\"):\n identification=makePlayList(actualPlaylistTitle)\n #print(\"identification is \"+identification+\" playlist name is \"+actualPlaylistTitle)\n for z in i.items:\n ken = str(z)\n try:\n #print(\"song added is \"+ken)\n addSongToPlayList(identification,ken)\n except:\n print(ken+\" was not added to \"+actualPlaylistTitle+\" playlist\")\n\n\n\n\n\n\n\n\n","repo_name":"KenMatsuoHacks/resumeRepository","sub_path":"appleToSpotifyBot/spotipyCode.py","file_name":"spotipyCode.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"74722143818","text":"class Singleton:\r\n _instance = None\r\n\r\n def __new__(cls):\r\n if cls._instance is None:\r\n cls._instance = super(Singleton, cls).__new__(cls)\r\n cls._instance.value = None\r\n return cls._instance\r\n\r\n def set_value(self, value):\r\n self.value = value\r\n\r\n def get_value(self):\r\n return self.value\r\n\r\n\r\nif __name__ == \"__main__\":\r\n s1 = Singleton()\r\n s1.set_value(\"Значение из s1\")\r\n\r\n s2 = Singleton()\r\n print(f\"Значение в s2: {s2.get_value()}\")\r\n\r\n print(s1 is s2)\r\n","repo_name":"awexeoz/singleton","sub_path":"Singleton.py","file_name":"Singleton.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"41510052818","text":"import http.client\nimport json\nfrom api_shell import get_json\n\n\ndef player_profile(id):\n json_data = get_json(\"/tennis-t2/en/players/{}/profile.json?api_key=8vfgwpuch3rpnauqm9cbzp7d\".format(id))\n profile = [json_data[\"player\"][\"id\"], json_data[\"player\"][\"name\"], surface_stats(json_data)]\n\n return profile\n\n\ndef surface_stats(data):\n stats = data[\"statistics\"][\"periods\"]\n surfaces = {\"Red clay\": [0, 0], \"Grass\": [0, 0], \"Hardcourt outdoor\": [0, 0], \"Hardcourt indoor\": [0, 0]}\n\n for i in range(5):\n for surface in stats[i][\"surfaces\"]:\n surfaces[surface[\"type\"]][0] += surface[\"statistics\"][\"matches_played\"]\n surfaces[surface[\"type\"]][1] += surface[\"statistics\"][\"matches_won\"]\n\n for surface in surfaces:\n surfaces[surface] = round(surfaces[surface][1] / surfaces[surface][0], 3)\n\n return surfaces\n\n\ndata = player_profile(\"sr:competitor:14342\")\nprint(data)\n# print(json.dumps(data, indent=2))\n\n","repo_name":"H4wking/kursach","sub_path":"player_profile.py","file_name":"player_profile.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"17331074049","text":"import math\n#s_list = []\ndef encryption(s):\n global s_list\n s = s.replace(' ', '')\n k = len(s)\n u = math.ceil(math.sqrt(k))\n l = math.floor(math.sqrt(k))\n if(u*l < k):\n l = l+1\n if (k < u*l):\n i = k\n while(i < (u*l)):\n s = s + \" \"\n i = i + 1\n s_list = []\n temp = []\n k = 0\n for i in range(l):\n\t for j in range(u):\n\t\t temp.append(s[k])\n\t\t k = k + 1\n\t s_list.append(temp)\n\t temp = []\n s_list = list(map(list, zip(*s_list)))\n #print(s_list)\n op = ''\n for i in s_list:\n for j in i:\n if(j != \" \"):\n op = op + j\n op = op + ' '\n print(op)\n\nencryption(\"chiilout\")\n\n","repo_name":"abhimanyudas747/hackerrank-submissions","sub_path":"algo-1-med.py","file_name":"algo-1-med.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"23530706135","text":"#!/usr/bin/env python3\nimport logging\nimport socket\nimport sys\nimport threading\nimport time\nimport traceback\n\nimport yaml\n\n\nclass Cli:\n def __init__(self, conf):\n self._logger = logging.getLogger()\n self._conf = conf\n self._app_conns = []\n self._trans_conns = []\n try:\n self._server_host = self._conf[\"server\"][\"host\"]\n except Exception as e:\n raise SystemExit(e)\n try:\n self._server_port = self._conf[\"server\"][\"port\"]\n except Exception as e:\n raise SystemExit(e)\n try:\n self._local_port = self._conf[\"local\"][\"port\"]\n except Exception as e:\n raise SystemExit(e)\n try:\n self._local_host = self._conf[\"local\"][\"host\"]\n except Exception as e:\n raise SystemExit(e)\n\n def __str__(self):\n return str(self._conf)\n\n def start(self):\n self._logger.info(\"start client\")\n listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n listen.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n listen.bind((self._local_host, self._local_port))\n listen.listen()\n self._logger.info(\n \"listen app conn {}:{}\".format(self._local_host, self._local_port))\n try:\n while 1:\n app_conn, addr = listen.accept()\n self._app_conns.append(app_conn)\n threading.Thread(target=self._handle_app_conn, args=(app_conn,)).start()\n except BaseException as e:\n self._logger.error(\n \"closing listen app conn {}:{}, {}\".format(self._local_host, self._local_port, e))\n try:\n listen.shutdown(socket.SHUT_RDWR)\n listen.close()\n except BaseException as ee:\n ...\n self._when_listen_close()\n raise e\n\n def _when_listen_close(self):\n for app_conn in self._app_conns:\n try:\n app_conn.shutdown(socket.SHUT_RDWR)\n app_conn.close()\n except BaseException as e:\n ...\n self._app_conns = []\n for trans_conn in self._trans_conns:\n try:\n trans_conn.shutdown(socket.SHUT_RDWR)\n trans_conn.close()\n except BaseException as e:\n ...\n self._trans_conns = []\n\n def _handle_app_conn(self, app_conn: socket.socket):\n app_conn_addr = app_conn.getpeername()\n trans_conn = socket.socket()\n try:\n trans_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n trans_conn.connect((self._server_host, self._server_port))\n trans_conn_addr = trans_conn.getsockname()\n self._trans_conns.append(trans_conn)\n self._logger.info(\n \"accept {}:{} <-> {}:{}\".format(app_conn_addr[0], app_conn_addr[1], self._local_host, self._local_port))\n self._logger.info(\"relay {}:{} <-> {}:{}\".format(trans_conn_addr[0], trans_conn_addr[1], self._server_host,\n self._server_port))\n threading.Thread(target=self._handle_trans_conn, args=(app_conn, trans_conn)).start()\n while 1:\n bs = app_conn.recv(40960)\n if len(bs) == 0:\n raise Exception(\"EOF\")\n trans_conn.send(bs)\n except BaseException as e:\n self._logger.error(\n \"closing accept {}:{} <-> {}:{}, {}\".format(app_conn_addr[0], app_conn_addr[1], self._local_host,\n self._local_port, e))\n try:\n self._logger.error(\n \"closing relay {}:{} <-> {}:{}, {}\".format(trans_conn_addr[0], trans_conn_addr[1],\n self._server_host,\n self._server_port, e))\n except BaseException as ee:\n ...\n try:\n app_conn.shutdown(socket.SHUT_RDWR)\n app_conn.close()\n except BaseException as e:\n ...\n try:\n trans_conn.shutdown(socket.SHUT_RDWR)\n trans_conn.close()\n except BaseException as e:\n ...\n\n def _handle_trans_conn(self, app_conn: socket.socket, trans_conn: socket.socket):\n try:\n while 1:\n bs = trans_conn.recv(40960)\n if len(bs) == 0:\n raise Exception(\"EOF\")\n app_conn.send(bs)\n except BaseException as e:\n try:\n app_conn.shutdown(socket.SHUT_RDWR)\n app_conn.close()\n except BaseException as e:\n ...\n try:\n trans_conn.shutdown(socket.SHUT_RDWR)\n trans_conn.close()\n except BaseException as e:\n ...\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n config_file = \"./cli.yaml\"\n else:\n config_file = sys.argv[1]\n with open(config_file, 'r') as f:\n conf = yaml.safe_load(f)\n lev = logging.INFO\n try:\n debug = conf['debug']\n except BaseException as e:\n debug = False\n if debug:\n lev = logging.DEBUG\n logging.basicConfig(level=lev,\n format='%(asctime)s %(levelname)s %(pathname)s:%(lineno)d %(thread)s %(message)s')\n logger = logging.getLogger()\n cli = Cli(conf)\n logger.info(\"cli info: {0}\".format(cli))\n while 1:\n try:\n cli.start()\n except (SystemExit, KeyboardInterrupt) as e:\n raise e\n except BaseException as e:\n logger.info(\"cli err: {0}\".format(traceback.format_exc()))\n logger.info(\"cli will start in 5s...\")\n time.sleep(5)\n","repo_name":"godaner/pyt","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"30054574988","text":"#fix the error\nimport os\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport utils as ut\nfrom IPython.display import display\nfrom tqdm import tqdm\nimport utils\n\ndef gaussian(x, mu, sigma):\n # broadcast sigma to match the shape of x and mu\n sigma = np.tile(sigma, (x.shape[0], 1))\n \n # compute the exponent\n exponent = -((x[:, None] - mu)**2) / (2 * sigma**2)\n \n # compute the Gaussian values\n gaussians = np.exp(exponent)\n \n return gaussians\n\n# Load df\npath = os.path.join(os.path.dirname(__file__), \"..\", \"_DATA_\", \"Iris.csv\")\ndf = pd.read_csv(path)\ndf = ut.fn_cat_onehot(df)\n# add bias column\ndisplay(df.head())\n\n# select the feature columns\nfeatures = df[\n [\"SepalLengthCm\", \"SepalWidthCm\", \"PetalLengthCm\", \"PetalWidthCm\"]\n]\nfeatures_array = np.array(features)\n\n# select the label columns\nlabels = df[\n [\"Species_Iris-setosa\", \"Species_Iris-versicolor\", \"Species_Iris-virginica\"]\n]\nlabels_array = np.array(labels)\n\n# mu and sigma\nmu = ut.get_kmeans_centers_for_rbf(df=features, n_clusters=5)#5x4\n\n\n\n\n\nprint(gaussian(x=features.values, mu=mu, sigma=sigma))","repo_name":"Birunda3000/Disciplina-Redes-Neurais-Artificiais","sub_path":"Primeiro/old/gaussian.py","file_name":"gaussian.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"41260719411","text":"import sys\nimport re\nimport os\nimport xml.etree.cElementTree as et\nfrom otapackage.lib import base, ini, log, image\nfrom otapackage import config\n\nclass Device(object):\n\n printer = None\n partition_cnt = 0\n @base.struct('devinfo', 'partition')\n def __init__(self, *value):\n pass\n\n class Devinfo(object):\n\n @base.struct('devtype', 'devsize')\n def __init__(self, *value):\n pass\n\n def get_nand_reserved_size(self):\n pebs = self.devsize / config.nandflash_block_size\n reserved_unit = config.ubi_mtd_ubi_beb_limit_per1024\n denum = 1024\n quot = pebs / denum\n rem = pebs % denum\n reserved = (quot * (reserved_unit)) + \\\n ((rem * (reserved_unit)) / (denum))\n if reserved < self.devsize:\n reserved += 1\n return reserved * config.nandflash_block_size\n\n class Partition(object):\n\n @base.struct('name', 'offset', 'size', 'type')\n def __init__(self, *value):\n pass\n\n def judge(self):\n Device.printer.debug(\"judge on partition \\'%s\\'\" %(self.name))\n if (self.offset < 0) or (self.size <= 0):\n Device.printer.error(\n 'error while getting offset or size on partition \\'%s\\'' % (\n self.name))\n return False\n return True\n\n def get_available_mapped_content_size(self, ftype):\n pagesize = config.nandflash_page_size\n blksize = pagesize * config.nandflash_pages_per_block\n size = self.size\n if ftype == 'normal':\n return size\n elif ftype == 'ubifs':\n ubi_reserved_blks = config.ubi_layout_volume_ebs + \\\n config.ubi_wl_reserved_pebs + config.ubi_eba_reserved_pebs\n ubi_reserved = ubi_reserved_blks * blksize\n return size - ubi_reserved\n elif ftype == 'jffs2':\n return size\n elif ftype == 'cramfs':\n return size\n elif ftype == 'yaffs2':\n yaffs_max = size / pagesize * \\\n (pagesize + config.yaffs2_tagsize_per_page)\n return yaffs_max\n else:\n return -1\n\n def is_mmaped_in(self, start, size):\n pstart = self.offset\n pend = self.size + pstart\n if start >= pstart and start < pend:\n return True\n return False\n\n def generate_config(self, element):\n Device.printer.debug(\"generate partition[\\'%s\\'] config\" %(self.name))\n eroot = et.SubElement(element, 'item')\n element_name = et.SubElement(eroot, 'name')\n element_name.attrib = {\"type\": config.xml_data_type_string}\n element_name.text = self.name\n element_type = et.SubElement(eroot, 'offset')\n element_type.text = '0x%x' % self.offset\n element_offset = et.SubElement(eroot, 'size')\n element_offset.text = '0x%x' % self.size\n element_size = et.SubElement(eroot, 'blockname')\n element_size.attrib = {\"type\": config.xml_data_type_string}\n element_size.text = self.type\n return eroot\n\n # interact with image info, persume image is mapped in partition\n def judge_partititon_mapped(self, map_start, map_size, ftype):\n partitions = self.partition\n devinfo = self.devinfo\n\n for i in range(0, len(partitions)):\n if partitions[i].is_mmaped_in(map_start, map_size):\n break\n\n if i == (len(partitions) + 1):\n self.printer.error(\n 'can not get image at offset 0x%x' % (map_start))\n return False\n\n mapped_max = partitions[i].get_available_mapped_content_size(ftype)\n if mapped_max <= 0:\n self.printer.error(\n '%s: can not get available map size at partition 0x%x' % (\n partitions[i].offset))\n\n return False\n\n if devinfo.devtype == 'nand' and ftype == 'ubifs':\n mapped_max -= devinfo.get_nand_reserved_size()\n\n if (map_start + map_size) > (partitions[i].offset + mapped_max):\n self.printer.error(\n 'image 0x%x can not mapped in partition 0x%x' % (\n map_start, partitions[i].offset))\n return False\n return True\n\n @classmethod\n def get_object_from_file(cls):\n cls.printer = log.Logger.get_logger(config.log_console)\n cls.printer.debug(\"dev customization parser is starting\")\n pathdev = os.path.join(\n config.Config.get_image_cfg_path(),\n \"%s\" %(config.Config.make_customer_files_fullname(config.partition_file)))\n ini_parser = ini.ParserIni(pathdev)\n section = 'storageinfo'\n devtype = ini_parser.get(section, 'mediumtype')\n devsize = ini_parser.get(section, 'capacity')\n if devtype == '' or devsize == '':\n cls.printer.error('section %s is wrong or lost items' % (section))\n return None\n devinfo = cls.Devinfo(devtype, base.human2bytes(devsize))\n plist = ini_parser.get_options('partition')\n partitions = []\n section = 'partition'\n cls.partition_cnt = len(plist)\n for i in range(0, len(plist)):\n item = ini_parser.get(section, plist[i])\n if plist[i] != \"item%d\"%(i+1):\n cls.printer.error(\n '%s is named wrong' % (plist[i]))\n return None\n fields = item.split(',')\n for field in fields:\n if field == '':\n cls.printer.error(\n 'item %s[%d] has empty field' % (section, i))\n return None\n p = cls.Partition(fields[0], base.str2int(fields[1]),\n base.str2int(fields[2]), fields[3])\n partitions.append(p)\n device = cls(devinfo, partitions)\n if not device.judge():\n return None\n return device\n\n def judge(self):\n self.printer.debug(\"dev judgement is starting\")\n if self.devinfo.devtype not in config.device_types:\n self.printer.error(\"devtype \\'%s\\' is not in %s\", \n self.devinfo.devtype, config.device_types)\n return False\n totalsize = self.devinfo.devsize\n if totalsize == -1:\n self.printer.error(\"devsize can not be recognised\")\n return False\n\n for i in range(0, len(self.partition)):\n\n p = self.partition[i]\n if not p.judge():\n self.printer.error(\n 'error while judging partition item %d' % (i))\n return False\n co = p.offset\n cs = p.size\n if co >= totalsize or cs > totalsize:\n self.printer.error(\n 'partition offset 0x%x or size 0x%x is overlow' % (co, cs))\n return False\n if (co + cs) > totalsize:\n self.printer.error(\n '''partition offset 0x%x plus size 0x%x is overlow''' % (co, cs))\n return False\n\n if (i < len(self.partition)-1):\n pnext = self.partition[i+1]\n if not pnext.judge():\n self.printer.error(\n 'error while judging partition item %d' % (i+1))\n return False\n no = pnext.offset\n if (co + cs) > no:\n self.printer.error(\n '''partition offset 0x%x plus size 0x%x is overlap with the next item''' % (co, cs))\n return False\n # print 'create device success'\n return True\n\n def generate(self):\n self.printer.debug(\"dev generation is starting\")\n default_config_dir = \"%s/%s/%s\" % (config.Config.get_outputdir_path(),\n config.Config.get_customer_files_suffix(),\n config.output_pack_config_dir)\n\n default_config = \"%s/%s\" % (default_config_dir,\n config.output_partition_name)\n\n if not os.path.exists(default_config_dir):\n os.makedirs(default_config_dir)\n\n # devinfo_root = et.Element('devinfo')\n # devinfo_type_root = et.SubElement(devinfo_root, 'type')\n # devinfo_type_root.attrib = {\"type\": config.xml_data_type_string}\n # devinfo_type_root.text = self.devinfo.devtype\n # devinfo_size_root = et.SubElement(devinfo_root, 'capacity')\n # devinfo_size_root.text = '0x%x' % self.devinfo.devsize\n\n partition_root = et.Element('partition')\n partition_root.attrib = {\"count\": \"%s\" %self.partition_cnt}\n for partition in self.partition:\n partition.generate_config(partition_root)\n\n root = et.Element('device')\n root.attrib = {\"type\": \"%s\" %self.devinfo.devtype, \"capacity\":\"0x%x\" %self.devinfo.devsize}\n # root_element_list = [devinfo_root,partition_root]\n root_element_list = [partition_root]\n root.extend(root_element_list)\n tree = et.ElementTree(root)\n path = default_config\n target = open(path, 'w')\n tree.write(target, encoding=config.xml_encoding,\n xml_declaration=config.xml_declaration)\n return True\n","repo_name":"YuanhuanLiang/X1000","sub_path":"external/recovery/server-side/otapackage/lib/dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":9507,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"46"} +{"seq_id":"7153609608","text":"buah = {'apel' : 5000, 'jeruk' : 8500, 'mangga' : 7800, 'duku' : 6500}\r\nprint('Diketahui list buah dengan harganya sebagai berikut:')\r\nprint(buah)\r\n\r\ndef hargaTermahal(buah):\r\n termahal=max(buah.values())\r\n keys = list(buah.keys())\r\n valus = list(buah.values())\r\n print('Dari list buah-buahan tersebut diketahui harga buah dengan harga paling mahal adalah:', keys[valus.index(termahal)])\r\n \r\n\r\nhargaTermahal(buah)\r\n\r\ndef rataHargaBuah(buah):\r\n hargaBuah= list(buah.values())\r\n return sum(hargaBuah)/len(hargaBuah)\r\n\r\nprint('Rata-rata harga buah yang di beli adalah:', rataHargaBuah(buah))\r\n","repo_name":"AldyFaturrohman/Aldy-Pemrograman-Terstruktur","sub_path":"Chapter 8/project08.py","file_name":"project08.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"6969912191","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 12 11:55:58 2023\n\n@author: antona\n\nLink: https://huggingface.co/docs/accelerate/package_reference/big_modeling\n\nThis version is automatic and it does not require separate manual download of the weights.\n\nThis version of the code uses Accelerate library and can be loaded in both CPU and GPU RAM.\n\nYou might need to close all your programs and restart python to free up enough memory.\n\n\"\"\"\n\nfrom accelerate import init_empty_weights, load_checkpoint_and_dispatch\nfrom huggingface_hub import hf_hub_download\nfrom transformers import AutoConfig, AutoModelForCausalLM\nfrom transformers import AutoTokenizer\n\ncheckpoint = \"EleutherAI/gpt-j-6B\"\nconfig = AutoConfig.from_pretrained(checkpoint)\n\nwith init_empty_weights():\n model = AutoModelForCausalLM.from_config(config)\n\nmodel.tie_weights()\n\nprint(\"Loading the sharded version of GPT-J ...\")\n\n# Download the Weights\ncheckpoint2 = \"sgugger/sharded-gpt-j-6B\"\nweights_location = hf_hub_download(checkpoint2,\"pytorch_model-00001-of-00002.bin\")\n\nprint(\"Weights location of the sharded version:\", weights_location)\n\n# Load the checkpoint and dispatch it to the right devices\nmodel = load_checkpoint_and_dispatch(\n model, \n weights_location, \n device_map=\"auto\", \n no_split_module_classes=[\"GPTJBlock\"],\n offload_folder=\"offload\"\n)\n\nprint(\"Processing prompt ...\")\n\nprompt = \"\"\"This is a discussion between a [human] and a [robot]. \nThe [robot] is very nice and empathetic. The name of the [robot] is John. The [robot] is male.\nThe [humans]'s name is Peter. The age of the [robot] is 31.\n\n[human]: Hello nice to meet you.\n[robot]: Nice to meet you too.\n###\n[human]: How is it going today?\n[robot]: Not so bad, thank you! How about you?\n###\n[human]: What is your name?\n[robot]:\"\"\"\n\ntokenizer = AutoTokenizer.from_pretrained(checkpoint)\ninputs = tokenizer(prompt, return_tensors=\"pt\")\n#inputs = inputs.to(0)\noutput = model.generate(inputs[\"input_ids\"], temperature = 0.1)\nprint(tokenizer.decode(output[0].tolist()))","repo_name":"toncho11/ML_examples","sub_path":"Transformers/HuggingFace/ChatBots/ChatBotGPT_J_Human_Bot_With_Accelerate_Automatic.py","file_name":"ChatBotGPT_J_Human_Bot_With_Accelerate_Automatic.py","file_ext":"py","file_size_in_byte":2015,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"46"} +{"seq_id":"31668865426","text":"import http.client\n\nconn = http.client.HTTPConnection(\"127.0.0.1\", port=8888)\n\npayload = \"abcdddddEEEE\"\n\nheaders = {\n 'Content-Type': \"text/plain\",\n 'User-Agent': \"PostmanRuntime/7.15.0\",\n 'Accept': \"*/*\",\n 'Cache-Control': \"no-cache\",\n 'Postman-Token': \"b695333f-e7e4-4926-8824-aea76482402b,48e619a9-f5a1-4898-9184-57cde4d72d89\",\n 'Host': \"192.168.1.108:8080\",\n 'accept-encoding': \"gzip, deflate\",\n 'content-length': \"24\",\n 'Connection': \"keep-alive\",\n 'cache-control': \"no-cache\"\n }\n\nconn.request(\"POST\", \"TestServer\", payload, headers)\n\nres = conn.getresponse()\ndata = res.read()\n\nprint(data.decode(\"utf-8\"))\n","repo_name":"hanhiver/mycpp11","sub_path":"libs/curl/POST_upload_file/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"28864766467","text":"from torch.utils.data import Dataset, DataLoader\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom PIL import Image\nimport os\n\n\nclass LWFDataset(Dataset):\n def __init__(self, data_dir, split='pairsDevTrain', transform=None, target_transform=None):\n img_dir = os.path.join(data_dir, 'lfw/')\n txt_path = os.path.join(data_dir, '{0}.txt'.format(split))\n fh = open(txt_path, 'r')\n imgs0 = []\n imgs1 = []\n label = []\n pos_num = 0\n neg_num = 0\n line_index = 1\n for line in fh:\n # print(line_index)\n line = line.rstrip()\n words = line.split()\n if line_index == 1:\n pos_num = int(words[0])\n neg_num = pos_num\n elif line_index <= pos_num+1: # positive pairs\n img_file_path0 = os.path.join(img_dir, words[0], words[0] + \"_%0*d.jpg\" % (4, int(words[1])))\n # print(img_file_path0)\n imgs0.append(img_file_path0)\n img_file_path1 = os.path.join(img_dir, words[0], words[0] + \"_%0*d.jpg\" % (4, int(words[2])))\n # print(img_file_path1)\n imgs1.append(img_file_path1)\n value = 0\n label.append(value)\n else: # negative pairs\n img_file_path0 = os.path.join(img_dir, words[0], words[0] + \"_%0*d.jpg\" % (4, int(words[1])))\n # print(img_file_path0)\n imgs0.append(img_file_path0)\n img_file_path1 = os.path.join(img_dir, words[2], words[2] + \"_%0*d.jpg\" % (4, int(words[3])))\n # print(img_file_path1)\n imgs1.append(img_file_path1)\n value = 1\n label.append(value)\n line_index += 1\n\n self.imgs0 = imgs0 # 最主要就是要生成这个list, 然后DataLoader中给index,通过getitem读取图片数据\n self.imgs1 = imgs1 # 最主要就是要生成这个list, 然后DataLoader中给index,通过getitem读取图片数据\n self.label = label\n self.transform = transform\n self.target_transform = target_transform\n\n def __getitem__(self, index):\n fn0 = self.imgs0[index]\n fn1 = self.imgs1[index]\n img0 = Image.open(fn0).convert('RGB') # 像素值 0~255,在transfrom.totensor会除以255,使像素值变成 0~1\n img1 = Image.open(fn1).convert('RGB') # 像素值 0~255,在transfrom.totensor会除以255,使像素值变成 0~1\n label = self.label[index]\n\n if self.transform is not None:\n img0 = self.transform(img0) # 在这里做transform,转为tensor等等\n img1 = self.transform(img1) # 在这里做transform,转为tensor等等\n\n return img0, img1, label\n\n def __len__(self):\n return len(self.imgs0)\n\n\nclass SiameseNetworkSimple(nn.Module):\n def __init__(self):\n super(SiameseNetworkSimple, self).__init__()\n self.cnn = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(3, 5, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(5),\n nn.Dropout2d(p=0.2),\n\n nn.ReflectionPad2d(1),\n nn.Conv2d(5, 7, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(7),\n nn.Dropout2d(p=0.2),\n )\n\n self.fc = nn.Sequential(\n nn.Linear(7 * 100 * 100, 500),\n nn.ReLU(inplace=True),\n\n nn.Linear(500, 100),\n nn.ReLU(inplace=True),\n\n nn.Linear(100, 100)\n )\n\n def forward_once(self, x):\n output = self.cnn(x)\n output = output.view(output.size()[0], -1)\n output = self.fc(output)\n return output\n\n def forward(self, input1, input2):\n output1 = self.forward_once(input1)\n output2 = self.forward_once(input2)\n return output1, output2\n\n\nclass SiameseNetworkWED(nn.Module):\n def __init__(self):\n super(SiameseNetworkWED, self).__init__()\n self.cnn = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(3, 4, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(4),\n\n nn.ReflectionPad2d(1),\n nn.Conv2d(4, 5, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(5),\n )\n\n self.fc = nn.Sequential(\n nn.Linear(5 * 100 * 100, 500),\n nn.ReLU(inplace=True),\n nn.Dropout(p=0.5),\n\n nn.Linear(500, 100),\n nn.ReLU(inplace=True),\n nn.Dropout2d(p=0.5),\n\n nn.Linear(100, 100)\n )\n\n self.classifier = nn.Sequential(\n nn.Linear(100, 1),\n )\n\n def forward_once(self, x):\n output = self.cnn(x)\n output = output.view(output.size()[0], -1)\n output = self.fc(output)\n return output\n\n def forward(self, input1, input2):\n output1 = self.forward_once(input1)\n output2 = self.forward_once(input2)\n output = self.classifier(torch.abs(output2-output1))\n return output\n\n\nclass SiameseNetwork(nn.Module):\n def __init__(self):\n super(SiameseNetwork, self).__init__()\n self.cnn = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(3, 6, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(6),\n nn.Dropout2d(p=0.2),\n\n nn.ReflectionPad2d(1),\n nn.Conv2d(6, 12, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(12),\n nn.Dropout2d(p=0.2),\n\n nn.ReflectionPad2d(1),\n nn.Conv2d(12, 12, kernel_size=3),\n nn.ReLU(inplace=True),\n nn.BatchNorm2d(12),\n nn.Dropout2d(p=0.2),\n )\n\n self.fc = nn.Sequential(\n nn.Linear(12 * 200 * 200, 500),\n nn.ReLU(inplace=True),\n\n nn.Linear(500, 500),\n nn.ReLU(inplace=True),\n\n nn.Linear(500, 12)\n )\n\n def forward_once(self, x):\n output = self.cnn(x)\n output = output.view(output.size()[0], -1)\n output = self.fc(output)\n return output\n\n def forward(self, input1, input2):\n output1 = self.forward_once(input1)\n output2 = self.forward_once(input2)\n return output1, output2\n\n\nclass ContrastiveLoss(torch.nn.Module):\n \"\"\"\n Contrastive loss function.\n Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf\n \"\"\"\n\n def __init__(self, margin=2):\n super(ContrastiveLoss, self).__init__()\n self.margin = margin\n\n def forward(self, output1, output2, label):\n euclidean_distance = F.pairwise_distance(output1, output2)\n loss_contrastive = torch.mean((1 - label) * torch.pow(euclidean_distance, 2) +\n label * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0),\n 2))\n\n return loss_contrastive\n","repo_name":"kevincao91/SiameseNet_Demo","sub_path":"my_class.py","file_name":"my_class.py","file_ext":"py","file_size_in_byte":7053,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"18406030242","text":"import docx,os\n\ndef useDocFile(file):\n \n doc = docx.Document(file)\n i = len(doc.paragraphs)\n print(i)\n print(doc.paragraphs[0].text)\n #Showing content of a doc file\n for par in doc.paragraphs:\n print(par.text)\n print('Enter an integer')\n h = input()\n if h.isdigit():\n print('Showing content by smaller parts')\n for par in doc.paragraphs:\n for run in par.runs:\n print('************************')\n print(run.text)\n else:\n print('Showing shit')\n\ndef getFullText(filename):\n \n doc = docx.Document(filename)\n fullText = []\n print('************************')\n print('Showing whole text')\n for par in doc.paragraphs:\n fullText.append(par.text)\n return '\\n'.join(fullText)\n\n\ndef writeNewWordDocumentFromSomething(filename,pics):\n \n doc = docx.Document(filename)\n doc1 = docx.Document()\n doc1.add_heading('Header 0', 0)\n doc1.add_paragraph('First line of Zbi')\n doc1.add_paragraph('************************************')\n doc1.add_paragraph('\\n')\n for par in doc.paragraphs:\n doc1.add_paragraph(par.text)\n print('************************************')\n doc1.add_paragraph('************************************')\n doc1.add_paragraph('End of line of Zbi')\n for pic in pics:\n print(pic)\n par = doc1.add_paragraph()\n run = par.add_run()\n #doc.add_picture(os.path.realpath(pic), width=docx.shared.Inches(1),height=docx.shared.Cm(4))\n run.add_picture(pic)\n run.add_text('\\nRoger and Rayleigh')\n print('pics being added')\n doc1.save('helloWorldOfZbi8.docx')\n \nos.chdir('C:\\\\Users\\\\HP\\\\Desktop\\\\titiza')\n#useDocFile('VPNApplication.docx')\n#print(getFullText('VPNApplication.docx'))\n#print('All text of '+os.path.realpath('VPNApplication.docx')+' shown')\npics = []\npics.append('rogerRayleigh.jpg')\nwriteNewWordDocumentFromSomething('VPNApplication.docx',pics)\n\n","repo_name":"prizrakbeckman/python_sniffer_","sub_path":"other_programs/UseDocWordFile.py","file_name":"UseDocWordFile.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"30424745805","text":"#Code Author: José Carlos del Castillo Estrada\n\n#Excercise solved from the book \"Python for Everybody\" by Dr. Charles R. Severance\n#Following the Coursera program \"Using Python to access Web Data\" by the University of Michigan\n\n'''\nFollowing the given URL, find the link in the position given, and repeat the given number of times,\nthe answer is the last name that you retrieve\n\nExample: http://py4e-data.dr-chuck.net/known_by_Fikret.html\nSequence of names: Fikret - Montgomery - Mhairade - Butchi --> Anayah\n'''\n\nimport urllib.request, urllib.parse, urllib.error\nfrom bs4 import BeautifulSoup\nimport ssl\n\n# Ignore SSL certificate errors\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nhold = input(\"Enter URL: \")\nposition = int(input(\"Enter position\"))\ncount = int(input(\"Enter count\"))\n\nnewUrl = None\nfor i in range(count): \n if i == 0:\n url = hold\n else:\n url = newUrl\n print(\"Current URL: \", url)\n\n #This segment captures all the \"href\" that starts with the tag using BEAUTIFUL SOUP\n html = urllib.request.urlopen(url, context=ctx).read()\n soup = BeautifulSoup(html, 'html.parser')\n #Store all the tags as a list\n tags = soup('a')\n #This gets the desired URL to iterate until finding the last one\n newUrl = tags[position-1].get('href', None)\n\n#This get just the name of the subject in the URL\nprint('The person in question is:', tags[position-1].contents[0])","repo_name":"Jcarlos0828/py4eCourses-excercisesCode-solved","sub_path":"Using Python to access Web Data/Week 4/Urllib_FollowingLinks.py","file_name":"Urllib_FollowingLinks.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"28763977464","text":"def get_suitable_date_for_daily_extract(self, date=None, ut=False):\n \"\"\"\n Parameters\n ----------\n date : str\n ut : bool\n Whether to return the date as a string or as a an int (seconds after epoch).\n\n Returns\n -------\n Selects suitable date for daily extract\n Iterates trough the available dates forward and backward from the download date accepting the first day that has\n at least 90 percent of the number of trips of the maximum date. The condition can be changed to something else.\n If the download date is out of range, the process will look through the dates from first to last.\n \"\"\"\n daily_trips = self.get_trip_counts_per_day()\n max_daily_trips = daily_trips[u'trip_counts'].max(axis=0)\n if date in daily_trips[u'date_str']:\n start_index = daily_trips[daily_trips[u'date_str'] == date].index.tolist()[0]\n daily_trips[u'old_index'] = daily_trips.index\n daily_trips[u'date_dist'] = abs(start_index - daily_trips.index)\n daily_trips = daily_trips.sort_values(by=[u'date_dist', u'old_index']).reindex()\n for row in daily_trips.itertuples():\n if row.trip_counts >= 0.9 * max_daily_trips:\n if ut:\n return self.get_day_start_ut(row.date_str)\n else:\n return row.date_str","repo_name":"MichaelFu1998-create/security_scanning","sub_path":"codesearchnet/codesearchnet_9783.py","file_name":"codesearchnet_9783.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"35101932192","text":"from django.conf import settings\nfrom ninja import NinjaAPI\nfrom ninja.responses import Response\nfrom ninja.errors import ValidationError, AuthenticationError\nfrom apps.common.exceptions import RequestError, request_errors, validation_errors\nfrom apps.general.views import general_router\nfrom apps.accounts.views import auth_router\nfrom apps.listings.views import listings_router\nfrom apps.auctioneer.views import auctioneer_router\n\napi = NinjaAPI(\n title=settings.SITE_NAME,\n description=\"A simple bidding API built with Django Ninja Rest Framework\",\n version=\"5.0.0\",\n docs_url=\"/\",\n)\n\napi.add_router(\"/api/v5/general/\", general_router)\napi.add_router(\"/api/v5/auth/\", auth_router)\napi.add_router(\"/api/v5/listings/\", listings_router)\napi.add_router(\"/api/v5/auctioneer/\", auctioneer_router)\n\n\n@api.get(\n \"/api/v5/healthcheck/\",\n summary=\"API Health Check\",\n description=\"This endpoint checks the health of the API\",\n tags=[\"HealthCheck\"],\n)\nasync def get(request):\n return {\"message\": \"pong\"}\n\n\n@api.exception_handler(ValidationError)\ndef validation_exc_handler(request, exc):\n return validation_errors(exc)\n\n\n@api.exception_handler(RequestError)\ndef request_exc_handler(request, exc):\n return request_errors(exc)\n\n\n@api.exception_handler(AuthenticationError)\ndef request_exc_handler(request, exc):\n return Response({\"status\": \"failure\", \"message\": \"Unauthourized User\"}, status=401)\n","repo_name":"kayprogrammer/bidout-auction-v5","sub_path":"apps/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1423,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"46"} +{"seq_id":"33280291175","text":"import numpy as np\nimport os\nimport shutil\nimport glob\nimport cv2\n\ndir_dst = \"/home/omari/Datasets/Dukes_modified/results/robot_\"\n\ncount = 0\nth = 200\nfor d in [\"8\",\"14\",\"121\"]:\n\n img = cv2.imread(dir_dst+d+\".png\")\n img2 = img[-th:,:,:]*0+255\n if count == 0:\n img_final = img\n img_final = np.concatenate((img_final, img2), axis=0)\n else:\n img_final = np.concatenate((img_final, img), axis=0)\n img_final = np.concatenate((img_final, img2), axis=0)\n count+=1\n\n# img_final = img_final[:,:-th,:]\ncv2.imwrite(\"/home/omari/Dropbox/Thesis/writing/Chapter7/Chapter7Figs/PNG/Dukes-dataset.png\",img_final)\n","repo_name":"sc17rhr/Final-project","sub_path":"MusaddiqExtRenshaw/Alomari Code/image_dataset_example.py","file_name":"image_dataset_example.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"12931788721","text":"'''\nauthor : pH, radsn23\ndate : 09.02.2019\n'''\n\nfrom scipy.spatial import distance\nfrom imutils import face_utils\nimport xml.dom.minidom\nimport requests\nimport imutils\nimport random\nimport time\nimport dlib\nimport cv2\n\n\ndef eye_aspect_ratio(eye):\n A = distance.euclidean(eye[1], eye[5])\n B = distance.euclidean(eye[2], eye[4])\n C = distance.euclidean(eye[0], eye[3])\n ear = (A + B) / (2.0 * C)\n return ear\n\nthresh = 0.25\nframe_check = 20\ndetect = dlib.get_frontal_face_detector()\n\n# to identify facial landmarks\npredict = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n\n(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS[\"right_eye\"]\ncap = cv2.VideoCapture(0)\nflag = 0\n\n# blaster songs\nsongs = ['pink.mp3', 'imagine_dragons.mp3', 'the_nights.mp3']\n\n# speaker's IP\nipaddr = \"192.168.1.174\"\nservice = \"testing\"\nreason = \"this\"\nmessage = \"method.\"\n# API key\nKey = \"ku1IYMERCz8iqwNsMFDMSJJZ1kfYyOhA\"\n\n# volume of speaker\nvolumeVal = \"25\"\n\nwhile True:\n ret, frame = cap.read()\n frame = imutils.resize(frame, width=450)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n subjects = detect(gray, 0)\n for subject in subjects:\n shape = predict(gray, subject)\n shape = face_utils.shape_to_np(shape) # converting to NumPy Array\n leftEye = shape[lStart:lEnd]\n rightEye = shape[rStart:rEnd]\n leftEAR = eye_aspect_ratio(leftEye)\n rightEAR = eye_aspect_ratio(rightEye)\n ear = (leftEAR + rightEAR) / 2.0\n leftEyeHull = cv2.convexHull(leftEye)\n rightEyeHull = cv2.convexHull(rightEye)\n cv2.drawContours(frame, [leftEyeHull], -1, (0, 0, 139), 1)\n cv2.drawContours(frame, [rightEyeHull], -1, (0, 0, 139), 1)\n if ear < thresh:\n flag += 1\n print(flag)\n if flag >= frame_check: \n # print ALERT on screen upon drowsy detection\n cv2.putText(frame, \"****************ALERT!****************\", (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n cv2.putText(frame, \"****************ALERT!****************\", (10, 325),\n cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)\n # random song selected and song url formed\n song = random.choice(songs)\n url = 'https://radsn23.github.io/' + song\n \n sendXML = \"\" + Key + \"\" + url + \"\" + service + \"\" + reason + \"\" + message + \"\" + volumeVal + \"\"\n # form and send the /speaker POST request to start song\n send = requests.post('http://' + ipaddr + ':8090/speaker', data=sendXML)\n \n else:\n flag = 0\n # form and send the /speaker GET request to stop song\n stop = requests.get('http://' + ipaddr + ':8090/standby')\n\n cv2.imshow(\"Frame\", frame)\n key = cv2.waitKey(1) & 0xFF\n if key == ord(\"q\"):\n break\ncv2.destroyAllWindows()\ncap.stop()\n","repo_name":"UTpH/staywoke","sub_path":"drowsiness_detection.py","file_name":"drowsiness_detection.py","file_ext":"py","file_size_in_byte":3155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"5381846483","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef to_categorical (y, num_classes=None):\n y = np.array(y, dtype='int').ravel()\n if not num_classes: num_classes = np.max(y) + 1\n n = y.shape[0]\n categorical = np.zeros((n, num_classes))\n categorical[np.arange(n), y] = 1\n return categorical\n\n\ndef load_datasets (files_path: str):\n\tfrom pandas import read_csv\n\ttrain_x = read_csv(\"{}csvTrainImages 13440x1024.csv\".format(files_path), header=None).values.astype('float32').reshape([-1, 32, 32, 1]) / 255.0\n\ttrain_y = read_csv(\"{}csvTrainLabel 13440x1.csv\".format(files_path), header=None).values.astype('int32') - 1\n\ttest_x = read_csv(\"{}csvTestImages 3360x1024.csv\".format(files_path), header=None).values.astype('float32').reshape([-1, 32, 32, 1]) / 255.0\n\ttest_y = read_csv(\"{}csvTestLabel 3360x1.csv\".format(files_path), header=None).values.astype('int32') - 1\n\treturn train_x, train_y, test_x, test_y\n\n\ndef accuracy (y_true: np.ndarray, y_pred: np.ndarray):\n\t# ======= Just some sanity checks ========\n\tassert isinstance(y_true, np.ndarray)\n\tassert isinstance(y_pred, np.ndarray)\n\tassert len(y_true.shape) == 2\n\tassert len(y_pred.shape) == 2\n\tassert y_true.shape[0] == 28\n\tassert y_pred.shape[0] == 28\n\tassert y_true.shape[1] == y_pred.shape[1]\n\t# ======= All systems are go! ============\n\n\tresults = np.zeros((28,))\n\tfor i in range(y_true.shape[1]):\n\t\tresults += np.logical_and(y_true[:, i] > 0.5, y_pred[:, i] > 0.5)\n\n\tsummation = np.sum(y_true, axis=1)\n\tassert summation.shape[0] == 28\n\n\taccuracy_per_class = (results / summation) * 100.0\n\toverall_accuracy = np.mean(accuracy_per_class)\n\n\treturn overall_accuracy, accuracy_per_class\n\n\ndef plot_randomly (training_set: np.ndarray, training_labels: np.ndarray, testing_set: np.ndarray, testing_labels: np.ndarray):\n\tfrom random import randint\n\n\tarabic_labels = [\n\t\t'alef', 'beh', 'teh', 'theh', 'jeem', 'hah', 'khah', 'dal', 'thal',\n\t\t'reh', 'zah', 'seen', 'sheen', 'sad', 'dad', 'tah', 'zah', 'ain',\n\t\t'ghain', 'feh', 'qaf', 'kaf', 'lam', 'meem', 'noon', 'heh', 'waw', 'yeh',\n\t]\n\n\tf, axarr = plt.subplots(4, 4)\n\tsubplots = []\n\tfor i in range(axarr.shape[0]):\n\t\tfor j in range(axarr.shape[1]):\n\t\t\tsubplots.append(axarr[i, j])\n\n\tfor sp_index, subplot in enumerate(subplots):\n\t\tif sp_index < int(len(subplots) / 2):\n\t\t\tsubplot_dataset = \"training\"\n\t\t\trandom_index = randint(0, training_set.shape[0] - 1)\n\t\t\tsubplot_image = training_set[random_index]\n\t\t\tsubplot_class = training_labels[random_index][0]\n\t\telse:\n\t\t\tsubplot_dataset = \"testing\"\n\t\t\trandom_index = randint(0, testing_set.shape[0] - 1)\n\t\t\tsubplot_image = testing_set[random_index]\n\t\t\tsubplot_class = testing_labels[random_index][0]\n\n\t\tsubplot_title = \"Image #{}, {} set, class {}\".format(random_index, subplot_dataset, arabic_labels[subplot_class])\n\t\tsubplot.imshow(subplot_image.squeeze().T, cmap='gray')\n\t\tsubplot.axis('off')\n\t\tsubplot.set_title(subplot_title, size=8)\n\n\tplt.show()\n\n\ndef train_model (training_set: np.ndarray, training_labels: np.ndarray, testing_set: np.ndarray, testing_labels: np.ndarray):\n\tpass\n\n\nif __name__ == \"__main__\":\n\t'''\n\tWelcome to the JOSA Deep Learning study groups first homework! In this homework, we'll be\n\tclassifying handwritten Arabic letters (all 28 of them) using whatever neural network you want to build.\n\n\tStart by loading in your training + testing datasets using the load_datasets function. The\n\tload_datasets function takes a path as its argument. In the folder located by the path, Python should find\n\tfour CSV files with their original names.\n\t'''\n\ttrain, train_labels, test, test_labels = load_datasets(\"path/to/your/datasets\")\n\n\t'''\n\tAlways make sure the shape of your dataset is correct! Your output should look like this:\n\n\t\t(13440, 32, 32, 1)\n\t\t(13440, 1)\n\t\t(3360, 32, 32, 1)\n\t\t(3360, 1)\n\t'''\n\tprint(*[x.shape for x in [train, train_labels, test, test_labels]], sep=\"\\n\")\n\n\t'''\n\tWhat does our dataset look like? The plot_randomly function will do some matplotlib magic to randomly\n\tdisplay 4 images from the training set, and 4 images from the testing set. Above each image, you will\n\tsee the index of that image, the set it was taken from (training or testing), and most importantly the\n\tclass of the set. Our alphabet will be sorted by the \"Hijā’ī\" sorting, so \"alef\" will come first and\n\t\"yeh\" will come last.\n\t'''\n\tplot_randomly(train, train_labels, test, test_labels)\n\n\t'''\n\tFor reference, here's the naming we will use for each letter. The class numbers are therefore the\n\tindices of this list. For example, \"alef\" belongs to class 0, and \"yeh\" belongs to class 27.\n\t'''\n\tarabic_labels = [\n\t\t'alef', 'beh', 'teh', 'theh', 'jeem', 'hah', 'khah', 'dal', 'thal',\n\t\t'reh', 'zah', 'seen', 'sheen', 'sad', 'dad', 'tah', 'zah', 'ain',\n\t\t'ghain', 'feh', 'qaf', 'kaf', 'lam', 'meem', 'noon', 'heh', 'waw', 'yeh',\n\t]\n\n\t'''\n\tMore basic exploratory analysis of our datasets. Let's count the number of unique train/test labels. We\n\tshould get exactly 28. This is useful later when we build the output layer of our neural network.\n\t'''\n\tunique_classes = list(set(train_labels.squeeze().tolist() + test_labels.squeeze().tolist()))\n\tnumber_of_outputs = len(unique_classes)\n\tassert number_of_outputs == 28\n\n\t'''\n\tOne last important step: converting our output into a big binary vector. Remember that for classification\n\tproblems, we will output the probability that an input belongs to one specific class. When we have multiple\n\tclasses, we need an output for each class probability. The to_categorical function simply takes each\n\tlabel and converts it into a binary vector, something like [0, 0, ... 1, 0, 0]. The 1 in that vector is in\n\tthe same index as the corresponding label is in the arabic_labels list. You can check that out for yourself\n\tby printing train_labels[0].\n\t'''\n\ttrain_labels, test_labels = to_categorical(train_labels, number_of_outputs), to_categorical(test_labels, number_of_outputs)\n\n\t'''\n\tShow me what you got! I've left the train_model function empty for you, so you can experiment with\n\tthe train set, build your neural network, and try it out on the test set. Our only condition is that you\n\tuse the accuracy(y_true, y_pred) function to measure your accuracy on the train/test sets. Check that function\n\tout to see what it takes as input and what it returns as output. Happy coding!\n\t'''\n\ttrain_model(train, train_labels, test, test_labels)\n","repo_name":"jordanopensource/arabic-ocr-studygroup","sub_path":"starting-code.py","file_name":"starting-code.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"46"} +{"seq_id":"14931437883","text":"import libtcodpy as libtcod\nimport math\nfrom enum import Enum\nfrom game_states import GameStates\nfrom menus import inventory_menu, level_up_menu, character_screen\n\nclass RenderOrder(Enum):\n STAIRS = 1\n CORPSE = 2\n EFFECT = 2\n ITEM = 3\n ACTOR = 4\n\ndef get_names_under_mouse(mouse, entities, fov_map):\n (x, y) = (mouse.cx, mouse.cy)\n\n names = [entity.name for entity in entities\n if entity.x == x and entity.y == y and libtcod.map_is_in_fov(fov_map, entity.x, entity.y)]\n names = ', '.join(names)\n\n return names.capitalize()\n\ndef render_bar(panel, x, y, total_width, name, value, maximum, bar_color, back_color):\n bar_width = int(float(value) / maximum * total_width)\n\n libtcod.console_set_default_background(panel, back_color)\n libtcod.console_rect(panel, x, y, total_width, 1, False, libtcod.BKGND_SCREEN)\n\n libtcod.console_set_default_background(panel, bar_color)\n if bar_width > 0:\n libtcod.console_rect(panel, x, y, bar_width, 1, False, libtcod.BKGND_SCREEN)\n\n libtcod.console_set_default_foreground(panel, libtcod.white)\n libtcod.console_print_ex(panel, int(x + total_width * 1)-1, y+1, libtcod.BKGND_NONE, libtcod.RIGHT,\n '{0}: {1}/{2}'.format(name, value, maximum))\n\ndef render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, screen_width, screen_height, colors, fov_radius, bar_width,\n panel_height, panel_y, mouse, game_state, menu_position):\n # Draw all the tiles in the game map /in sight range\n if fov_recompute:\n for y in range(game_map.height):\n for x in range(game_map.width):\n visible = libtcod.map_is_in_fov(fov_map, x, y)\n wall = game_map.tiles[x][y].block_sight\n dist = math.sqrt( math.pow(x - entities[0].x,2) + math.pow(y - entities[0].y,2) )\n # 'light_wall': libtcod.Color(30, 30, 100)\n # 'light_ground': libtcod.Color(20, 20, 0)\n\n if visible:\n if wall:\n # if dist > 4:\n # libtcod.console_set_char_background(con, x, y, colors.get('medium_wall'), libtcod.BKGND_SET)\n # else:\n # libtcod.console_set_char_background(con, x, y, colors.get('light_wall'), libtcod.BKGND_SET)\n if game_state != GameStates.PLAYERS_TURN:\n clr = math.floor(11-((10*dist)/(fov_radius+1)))\n libtcod.console_set_char_background(con, x, y, libtcod.Color(clr, clr, 30), libtcod.BKGND_SET)\n else:\n clr = math.floor(31-((30*dist)/(fov_radius+1)))\n libtcod.console_set_char_background(con, x, y, libtcod.Color(clr, clr, 100), libtcod.BKGND_SET)\n else:\n # if dist > 4:\n # libtcod.console_set_char_background(con, x, y, colors.get('medium_ground'), libtcod.BKGND_SET)\n # else:\n # libtcod.console_set_char_background(con, x, y, colors.get('light_ground'), libtcod.BKGND_SET)\n if game_state != GameStates.PLAYERS_TURN:\n clr = math.floor(7-((6*dist)/(fov_radius+1)))\n libtcod.console_set_char_background(con, x, y, libtcod.Color(clr, clr, 0), libtcod.BKGND_SET)\n else:\n clr = math.floor(21-((20*dist)/(fov_radius+1)))\n libtcod.console_set_char_background(con, x, y, libtcod.Color(clr, clr, 0), libtcod.BKGND_SET)\n game_map.tiles[x][y].explored = True\n elif game_map.tiles[x][y].explored:\n if wall:\n libtcod.console_set_char_background(con, x, y, colors.get('explored_wall'), libtcod.BKGND_SET)\n else:\n libtcod.console_set_default_foreground(con, libtcod.darker_grey)\n libtcod.console_set_char_background(con, x, y, colors.get('explored_ground'), libtcod.BKGND_SET)\n\n # Draw all entities in the list\n entities_in_render_order = sorted(entities, key=lambda x: x.render_order.value)\n\n for entity in entities_in_render_order:\n draw_entity(con, entity, fov_map)\n\n libtcod.console_set_default_foreground(con, libtcod.white)\n libtcod.console_print_ex(con, 1, screen_height -2, libtcod.BKGND_NONE, libtcod.LEFT, ' {0:02}/{1:02}'.format(player.fighter.hp, player.fighter.max_hp))\n\n libtcod.console_blit(con, 0, 0, screen_width, screen_height, 0, 0, 0)\n\n libtcod.console_set_default_background(panel, libtcod.black)\n libtcod.console_clear(panel)\n\n # print messages\n y = 1\n for message in message_log.messages:\n libtcod.console_set_default_foreground(panel, message.color)\n libtcod.console_print_ex(panel, message_log.x, y, libtcod.BKGND_NONE, libtcod.LEFT, message.text.upper())\n y += 1\n\n render_bar(panel, 1, 1, bar_width, 'HP', round(player.fighter.hp), player.fighter.max_hp,\n libtcod.light_red, libtcod.darker_red)\n\n render_bar(panel, 1, 3, bar_width, 'ST', player.cooldown, player.maxCooldown, libtcod.light_gray, libtcod.dark_gray)\n\n libtcod.console_set_default_foreground(panel, libtcod.light_gray)\n libtcod.console_print_ex(panel, bar_width, 5, libtcod.BKGND_NONE, libtcod.RIGHT,\n 'Andar: {0}/{1}'.format(game_map.dungeon_level, '?'))\n\n libtcod.console_set_default_foreground(panel, libtcod.light_gray)\n libtcod.console_print_ex(panel, 1, 0, libtcod.BKGND_NONE, libtcod.LEFT,\n get_names_under_mouse(mouse, entities, fov_map))\n\n libtcod.console_blit(panel, 0, 0, screen_width, panel_height, 0, 0, panel_y)\n\n if game_state == GameStates.SHOW_INVENTORY:\n inventory_menu(con, 'Itens:\\n',\n player, 50, screen_width, screen_height, menu_position)\n \n if game_state == GameStates.LEVEL_UP:\n level_up_menu(con, 'Fortaleca:\\n', player, 40, screen_width, screen_height, menu_position)\n \n if game_state == GameStates.CHARACTER_SCREEN:\n character_screen(player, 30, 14, screen_width, screen_height)\n\n\ndef clear_all(con, entities):\n for entity in entities:\n clear_entity(con, entity)\n\n\ndef draw_entity(con, entity, fov_map):\n if libtcod.map_is_in_fov(fov_map, entity.x, entity.y):# or entity.stairs or entity.item:\n libtcod.console_set_default_foreground(con, entity.color)\n libtcod.console_put_char(con, entity.x, entity.y, entity.char, libtcod.BKGND_NONE)\n\n\ndef clear_entity(con, entity):\n # erase the character that represents this object\n libtcod.console_put_char(con, entity.x, entity.y, ' ', libtcod.BKGND_NONE)","repo_name":"one-two/at-the-abyss","sub_path":"render_functions.py","file_name":"render_functions.py","file_ext":"py","file_size_in_byte":6870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"70113870219","text":"from __future__ import absolute_import, division, print_function\nimport scitbx.math\nimport scitbx.linalg\nfrom scitbx import matrix\nfrom scitbx.array_family import flex\nfrom libtbx.test_utils import approx_equal\nimport random\nfrom six.moves import range\n\ndef exercise_cholesky_decomposition():\n from scitbx.examples import immoptibox_ports\n immoptibox_ports.py_cholesky_decomposition \\\n = immoptibox_ports.cholesky_decomposition\n immoptibox_ports.cholesky_decomposition \\\n = exercise_scitbx_cholesky_decomposition\n immoptibox_ports.tst_flex_counts = 0\n immoptibox_ports.exercise_cholesky()\n immoptibox_ports.cholesky_decomposition \\\n = immoptibox_ports.py_cholesky_decomposition\n assert immoptibox_ports.tst_flex_counts == 299\n del immoptibox_ports.tst_flex_counts\n\ndef exercise_scitbx_cholesky_decomposition(a):\n from scitbx.examples import immoptibox_ports\n c = immoptibox_ports.py_cholesky_decomposition(a)\n al = a.matrix_symmetric_as_packed_l()\n chol = scitbx.linalg.l_l_transpose_cholesky_decomposition_in_place(al)\n cl = al\n if (c is None):\n assert chol.failure\n else:\n assert approx_equal(cl, c.matrix_lower_triangle_as_packed_l())\n for i_trial in range(10):\n b = flex.random_double(size=a.focus()[0], factor=2)-1\n x = chol.solve(b)\n assert approx_equal(a.matrix_multiply(x), b)\n immoptibox_ports.tst_flex_counts += 1\n return c\n\n\ndef exercise_gill_murray_wright_cholesky_decomposition():\n\n def p_as_mx(p):\n n = len(p)\n m = flex.double(flex.grid(n,n))\n m.matrix_diagonal_set_in_place(1)\n for i in range(n):\n if p[i] != i:\n m.matrix_swap_rows_in_place(i, p[i])\n return matrix.sqr(m)\n\n def core(a):\n c = flex.double(a)\n c.resize(flex.grid(a.n))\n u = c.matrix_upper_triangle_as_packed_u()\n gwm = scitbx.linalg.gill_murray_wright_cholesky_decomposition_in_place(\n u,\n epsilon=1.e-8)\n assert gwm.epsilon == 1.e-8\n u = c.matrix_upper_triangle_as_packed_u()\n gwm = scitbx.linalg.gill_murray_wright_cholesky_decomposition_in_place(u)\n assert gwm.epsilon == scitbx.math.floating_point_epsilon_double_get()\n assert gwm.packed_u.id() == u.id()\n p, e = gwm.pivots, gwm.e\n r = matrix.sqr(u.matrix_packed_u_as_upper_triangle())\n if a.n != (0,0):\n rtr = r.transpose() * r\n pm = p_as_mx(p)\n papt = pm * a * pm.transpose()\n paept = papt + matrix.diag(e)\n delta_decomposition = scitbx.linalg.matrix_equality_ratio(paept, rtr)\n assert delta_decomposition < 10, delta_decomposition\n b = flex.random_double(size=a.n[0], factor=2)-1\n x = gwm.solve(b=b)\n px = pm * matrix.col(x)\n pb = pm * matrix.col(b)\n if 0:\n eigen = scitbx.linalg.eigensystem.real_symmetric(\n paept.as_flex_double_matrix())\n lambda_ = eigen.values()\n print(\"condition number: \", lambda_[0]/lambda_[-1])\n delta_solve = scitbx.linalg.matrix_cholesky_test_ratio(\n a=paept.as_flex_double_matrix(),\n x=flex.double(px),\n b=flex.double(pb),\n epsilon=gwm.epsilon)\n assert delta_solve < 10, delta_solve\n return p, e, r\n # empty matrix\n a = matrix.sqr([])\n p, e, r = core(a)\n assert p.size() == 0\n assert e.size() == 0\n assert len(r) == 0\n n_max = 15\n n_trials_per_n = 10\n # identity matrices\n for n in range(1,n_max+1):\n a = matrix.diag([1]*n)\n p, e, r = core(a)\n assert list(p) == list(range(n))\n assert approx_equal(e, [0]*n)\n assert approx_equal(r, a)\n # null matrices\n for n in range(1,n_max+1):\n a = matrix.sqr([0]*n*n)\n p, e, r = core(a)\n assert list(p) == list(range(n))\n assert list(e) == [scitbx.math.floating_point_epsilon_double_get()]*n\n for i in range(n):\n for j in range(n):\n if (i != j): r(i,j) == 0\n else: r(i,j) == r(0,0)\n # random semi-positive diagonal matrices\n for n in range(1,n_max+1):\n for i_trial in range(n_trials_per_n):\n a = matrix.diag(flex.random_double(size=n))\n p, e, r = core(a)\n assert approx_equal(e, [0]*n)\n for i in range(n):\n for j in range(n):\n if (i != j): approx_equal(r(i,j), 0)\n # random diagonal matrices\n for n in range(1,n_max+1):\n for i_trial in range(n_trials_per_n):\n a = matrix.diag(flex.random_double(size=n, factor=2)-1)\n p, e, r = core(a)\n for i in range(n):\n for j in range(n):\n if (i != j): approx_equal(r(i,j), 0)\n # random semi-positive definite matrices\n for n in range(1,n_max+1):\n for i_trial in range(n_trials_per_n):\n m = matrix.sqr(flex.random_double(size=n*n, factor=2)-1)\n a = m.transpose_multiply()\n p, e, r = core(a)\n assert approx_equal(e, [0]*n)\n # random matrices\n for n in range(1,n_max+1):\n size = n*(n+1)//2\n for i_trial in range(n_trials_per_n):\n a = (flex.random_double(size=size, factor=2)-1) \\\n .matrix_packed_u_as_symmetric()\n core(matrix.sqr(a))\n a.matrix_diagonal_set_in_place(0)\n core(matrix.sqr(a))\n # J. Nocedal and S. Wright:\n # Numerical Optimization.\n # Springer, New York, 1999, pp. 145-150.\n for i in range(3):\n for j in range(3):\n a = flex.double([[4,2,1],[2,6,3],[1,3,-0.004]])\n a.matrix_swap_rows_in_place(i=i, j=j)\n a.matrix_swap_columns_in_place(i=i, j=j)\n p, e, r = core(matrix.sqr(a))\n if (i == 0 and j == 0):\n assert list(p) == [1,1,2] # swap row 0 and 1 and nothing else\n assert approx_equal(e, [0.0, 0.0, 3.008])\n assert approx_equal(r,\n [2.4494897427831779, 0.81649658092772592, 1.2247448713915889,\n 0.0, 1.8257418583505538, 0.0,\n 0.0, 0.0, 1.2263767773404712])\n\ndef run():\n exercise_cholesky_decomposition()\n exercise_gill_murray_wright_cholesky_decomposition()\n print('OK')\n\nif __name__ == '__main__':\n run()\n","repo_name":"cctbx/cctbx_project","sub_path":"scitbx/linalg/tests/tst_cholesky.py","file_name":"tst_cholesky.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","stars":193,"dataset":"github-code","pt":"46"} +{"seq_id":"28560374053","text":"from itertools import combinations\n\n\ndef read_input():\n with open('input/day1.txt', 'r') as reader:\n entries = [int(entry) for entry in reader.read().splitlines()]\n return entries\n\n\ndef find_two(entries):\n for entry in entries:\n if 2020-entry in entries:\n return entry*(2020-entry)\n\n\ndef find_three(entries):\n for group in combinations(entries, 3):\n if sum(group) == 2020:\n return group[0]*group[1]*group[2]\n\n\nif __name__ == '__main__':\n report = read_input()\n print(find_two(report))\n print(find_three(report))\n\n","repo_name":"xmachak/aoc2020","sub_path":"day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"17756457199","text":"\"\"\"\n Created by howie.hu at 2022-01-21.\n Description: 执行分发动作\n - 执行命令: PIPENV_DOTENV_LOCATION=./online.env pipenv run python src/sender/action.py\n Changelog: all notable changes to this file will be documented\n\"\"\"\nimport time\n\nfrom src.common.doc_utils import get_bak_doc_link\nfrom src.config import Config\nfrom src.databases import MongodbManager\nfrom src.sender.send_factory import send_factory\nfrom src.utils.log import LOGGER\n\n\ndef send_doc(sender_conf: dict):\n \"\"\"\n 对文章进行分发\n Args:\n sender_conf (dict): 分发配置\n \"\"\"\n sender_list = sender_conf[\"sender_list\"]\n query_days = sender_conf.get(\"query_days\", 2)\n delta_time = sender_conf.get(\"delta_time\", 3)\n link_source = sender_conf.get(\"link_source\", \"self\")\n basic_filter = sender_conf.get(\"basic_filter\", {})\n ignore_doc_source_name = sender_conf.get(\"ignore_doc_source_name\", [])\n skip_ads = sender_conf.get(\"skip_ads\", False)\n if sender_list:\n # 是否启用分发器\n mongodb_base = MongodbManager.get_mongo_base(\n mongodb_config=Config.LL_MONGODB_CONFIG\n )\n coll = mongodb_base.get_collection(coll_name=\"liuli_articles\")\n\n # 分别分发给各个目标\n for send_type in sender_list:\n # 构建查询条件\n cur_ts = int(time.time())\n custom_filter = sender_conf.get(\"custom_filter\", {}).get(send_type, {})\n query_days = custom_filter.get(\"query_days\", query_days)\n delta_time = custom_filter.get(\"delta_time\", delta_time)\n link_source = custom_filter.get(\"link_source\", link_source)\n skip_ads = custom_filter.get(\"skip_ads\", skip_ads)\n ignore_doc_source_name = custom_filter.get(\n \"ignore_doc_source_name\", ignore_doc_source_name\n )\n filter_dict = {\n **basic_filter,\n **{\n # 时间范围,除第一次外后面其实可以去掉\n \"doc_ts\": {\n \"$gte\": cur_ts - (query_days * 24 * 60 * 60),\n \"$lte\": cur_ts,\n },\n # 过滤文档源名称\n \"doc_source_name\": {\"$nin\": ignore_doc_source_name},\n },\n }\n if skip_ads:\n filter_dict.update(\n {\n # 至少打上一个模型标签\n \"cos_model\": {\"$exists\": True},\n # 判定结果为非广告\n \"cos_model.result\": 1,\n }\n )\n # 查找所有可分发文章\n for each_data in coll.find(filter_dict):\n # 暂时固定,测试\n init_config = sender_conf.get(f\"{send_type}_init_config\", {})\n cos_model_resp = each_data.get(\"cos_model\", {})\n doc_cus_des = \"\"\n if cos_model_resp and skip_ads:\n # 经过模型判断\n if cos_model_resp[\"result\"] == 1:\n # 广告标记\n doc_cus_des = f\"👿广告[概率:{cos_model_resp['probability']}]\"\n else:\n doc_cus_des = \"🤓非广告\"\n\n each_data[\"doc_cus_des\"] = doc_cus_des\n each_data[\"doc_link\"] = get_bak_doc_link(\n link_source=link_source, doc_data=each_data\n )\n # 每次分发休眠一定时间\n time.sleep(delta_time)\n send_factory(\n send_type=send_type, init_config=init_config, send_data=each_data\n )\n else:\n LOGGER.error()(\"未配置分发器!\")\n\n\nif __name__ == \"__main__\":\n send_config = {\n \"basic_filter\": {\"doc_source\": \"liuli_wechat\"},\n \"sender_list\": [\"wecom\"],\n \"query_days\": 5,\n \"skip_ads\": False,\n \"delta_time\": 3,\n \"custom_filter\": {\n \"wecom\": {\"delta_time\": 1, \"ignore_doc_source_name\": [\"老胡的储物柜\"]}\n },\n }\n send_doc(send_config)\n","repo_name":"howie6879/liuli","sub_path":"src/sender/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":4175,"program_lang":"python","lang":"en","doc_type":"code","stars":824,"dataset":"github-code","pt":"46"} +{"seq_id":"7868912967","text":"import sys\nsys.path.append(\"../..\")\nsys.path.append(\"..\")\n\nfrom limits.limits import *\nfrom hypothesis.strategies import *\nfrom hypothesis import given\nfrom timeout import run_with_timeout\nfrom typing import *\n \nn = integers(min_value=1, max_value=MAX_INT)\nstrategy = n\nif not isinstance(strategy, tuple):\n strategy = (strategy,)\n\ndef get_ludic(n):\n\tludics = []\n\tfor i in range(1, n + 1):\n\t\tludics.append(i)\n\tindex = 1\n\twhile(index != len(ludics)):\n\t\tfirst_ludic = ludics[index]\n\t\tremove_index = index + first_ludic\n\t\twhile(remove_index < len(ludics)):\n\t\t\tludics.remove(ludics[remove_index])\n\t\t\tremove_index = remove_index + first_ludic - 1\n\t\tindex += 1\n\treturn ludics\n\n@given(tuples(*strategy))\ndef test_fuzz(args):\n run_with_timeout(0.3, get_ludic, *args)\n","repo_name":"mrigankpawagi/PropertyEval","sub_path":"autogen/tests/test_get_ludic_603.py","file_name":"test_get_ludic_603.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"32988606256","text":"from flask_app.config.mysqlconnection import connectToMySQL\nfrom flask import flash\nfrom flask_app.models.user_model import User\n\nclass Car:\n def __init__(self,data):\n self.id = data ['id']\n self.price = data ['price']\n self.model = data ['model']\n self.make = data ['make']\n self.year = data ['year']\n self.description = data ['description']\n self.user_id = data ['user_id']\n self.created_at = data ['created_at']\n self.updated_at = data ['updated_at']\n\n\n @classmethod\n def insert_car(cls,data):\n query=\"INSERT INTO cars (price,model,make,year,description,user_id) VALUES (%(price)s,%(model)s,%(make)s,%(year)s,%(description)s,%(user_id)s)\" \n return connectToMySQL(\"dealership_project\").query_db(query,data)\n\n\n @classmethod\n def get_cars(cls):\n query=\"SELECT * FROM users JOIN cars ON users.id = cars.user_id\"\n results = connectToMySQL(\"dealership_project\").query_db(query)\n users_cars = []\n\n for uc in results:\n user_instance = User(uc)\n car_data = {\n \"id\":uc[\"cars.id\"],\n \"price\":uc[\"price\"],\n \"model\":uc[\"model\"],\n \"make\":uc[\"make\"],\n \"year\":uc[\"year\"],\n \"description\":uc[\"description\"],\n \"user_id\":uc[\"user_id\"],\n \"created_at\":uc[\"cars.created_at\"],\n \"updated_at\":uc[\"cars.updated_at\"]\n }\n user_instance.car = Car(car_data)\n users_cars.append(user_instance)\n \n return users_cars\n\n\n\n @classmethod\n def get_car(cls,data):\n query=\"SELECT * FROM users JOIN cars ON users.id = cars.user_id WHERE cars.id = %(car_id)s\"\n results = connectToMySQL(\"dealership_project\").query_db(query,data)\n user_instance = User(results[0])\n for uc in results:\n car_data = {\n \"id\":uc[\"cars.id\"],\n \"price\":uc[\"price\"],\n \"model\":uc[\"model\"],\n \"make\":uc[\"make\"],\n \"year\":uc[\"year\"],\n \"description\":uc[\"description\"],\n \"user_id\":uc[\"user_id\"],\n \"created_at\":uc[\"cars.created_at\"],\n \"updated_at\":uc[\"cars.updated_at\"]\n }\n user_instance.car = Car(car_data)\n return user_instance\n\n\n\n @classmethod\n def edit_car(cls,data):\n query = \"SELECT * FROM cars WHERE id = %(car_id)s\";\n result = connectToMySQL('dealership_project').query_db(query,data)\n return cls(result[0])\n\n\n @classmethod\n def update_car(cls,data):\n query = \"UPDATE cars SET price=%(price)s,model=%(model)s,make=%(make)s,year=%(year)s,description=%(description)s WHERE id = %(car_id)s\";\n return connectToMySQL(\"dealership_project\").query_db(query,data)\n\n\n @classmethod\n def delete_car(cls,data):\n query=\"DELETE FROM cars WHERE id = %(id)s\" \n return connectToMySQL(\"dealership_project\").query_db(query,data)\n\n\n @staticmethod\n def validate_car(car):\n is_valid = True\n if len(car[\"make\"]) < 1 or len(car[\"make\"]) > 20:\n flash(\"Make must contain 2 to 20 characters\")\n is_valid = False\n if len(car[\"model\"]) < 1 or len(car[\"model\"]) > 20:\n flash(\"Model must contain 2 to 20 characters\")\n is_valid = False\n if len(car[\"year\"]) < 1 or len(car[\"year\"]) > 4:\n flash(\"Please enter valid year\")\n is_valid = False\n if len(car[\"price\"]) < 1:\n flash(\"Price must be greater than 1\")\n is_valid = False\n if len(car[\"description\"]) < 1 or len(car[\"description\"]) > 255:\n flash(\"Description must contain 2 to 255 characters\")\n is_valid = False\n \n return is_valid\n\n\n @staticmethod\n def validate_update(car):\n is_valid = True\n if len(car[\"make\"]) < 1 or len(car[\"make\"]) > 20:\n flash(\"Make must contain 2 to 20 characters\")\n is_valid = False\n if len(car[\"model\"]) < 1 or len(car[\"model\"]) > 20:\n flash(\"Model must contain 2 to 20 characters\")\n is_valid = False\n if len(car[\"year\"]) < 1 or len(car[\"year\"]) > 4:\n flash(\"Please enter valid year\")\n is_valid = False\n if len(car[\"price\"]) < 1:\n flash(\"Price must be greater than 1\")\n is_valid = False\n if len(car[\"description\"]) < 1 or len(car[\"description\"]) > 255:\n flash(\"Description must contain 2 to 255 characters\")\n is_valid = False\n \n return is_valid\n","repo_name":"jmalone801/dealership","sub_path":"flask_app/models/car_model.py","file_name":"car_model.py","file_ext":"py","file_size_in_byte":4664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"1038510554","text":"#Exercício 32\n\nimport datetime\n\nano = int(input('Insira o ano: '))\nif ano == 0:\n ano = datetime.date.today().year\nif ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:\n print(f'O ano {ano} é bissexto')\nelse: \n print(f'O ano {ano} não é bissexto')\n","repo_name":"SamuelWoszak/Learning","sub_path":"Curso Em Vídeo Python/Mundo 1/Exercício 032.py","file_name":"Exercício 032.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"5613544255","text":"from django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom datetime import datetime\nfrom django.utils.timezone import now\n\nclass User(AbstractUser):\n projects = models.ManyToManyField('Project', blank=True, related_name=\"projects\")\n user_color = models.CharField(max_length=6, default=None, null=True, blank=True)\n\nclass Project(models.Model):\n title = models.CharField(max_length=280, default=None, null=True, blank=True)\n project_logo = models.ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, default=None, null=True, blank=True)\n admin = models.ForeignKey(User, related_name=\"admin\", default=None, null=True, blank=True, on_delete=models.CASCADE)\n project_users = models.ManyToManyField(User, blank=True, related_name=\"project_users\")\n\nclass Phase(models.Model):\n name = models.CharField(max_length=280, default=None, null=True, blank=True)\n start_date = models.DateField(auto_now=False, auto_now_add=False)\n end_date = models.DateField(auto_now=False, auto_now_add=False)\n completed = models.BooleanField(default=None, null=True, blank=True)\n project = models.ForeignKey(Project, related_name=\"project\", default=None, null=True, blank=True, on_delete=models.CASCADE)\n","repo_name":"SergiOca87/capstone","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"73227102538","text":"\"\"\"added Zoom account model\n\nRevision ID: 33fe086c0a14\nRevises: 54678b08648e\nCreate Date: 2020-03-31 15:37:11.765465\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '33fe086c0a14'\ndown_revision = '54678b08648e'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('smartclass_scheduler_zoom_accounts',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('smartclass_scheduler_zoom_accounts')\n # ### end Alembic commands ###\n","repo_name":"MUMT-IT/mis2018","sub_path":"migrations/versions/33fe086c0a14_added_zoom_account_model.py","file_name":"33fe086c0a14_added_zoom_account_model.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"46"} +{"seq_id":"14122743175","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.ListCompanies.as_view(), name='listCompanies'),\n path('addCompany/', views.AddCompany.as_view(), name='addCompany'),\n path('listCompanies/', views.ListCompanies.as_view(), name='listCompanies'),\n # path('detailsCompany//', views.DetailsCompany.as_view(), name='detailsCompany'),\n path('updateCompany//', views.UpdateCompany.as_view(), name='updateCompany'),\n path('companyBranchList/', views.companyBranchList.as_view(), name=\"companyBranchList\"),\n path('validateCompanyName', views.validatCompanyName, name='validateCompanyName'),\n path('listCompanyBranches//', views.ListCompanyBranches.as_view(), name='listCompanyBranches'),\n path('saveCompany', views.save_company, name='saveCompany'),\n path('saveCompanyUpdate', views.save_company_update, name='saveCompanyUpdate'),\n\n path('addDepartment/', views.AddDepartment.as_view(), name='addDepartment'),\n path('listDepartments/', views.ListDepartments.as_view(), name='listDepartments'),\n path('detailsDepartment//', views.DetailsDepartment.as_view(), name='detailsDepartment'),\n path('updateDepartment//', views.UpdateDepartment.as_view(), name='updateDepartment'),\n\n path('addBranch/', views.create_branch, name='addBranch'),\n path('listBranches/', views.ListBranches.as_view(), name='listBranches'),\n path('detailsBranch//', views.DetailsBranch.as_view(), name='detailsBranch'),\n path('updateBranch//', views.branch_update, name='updateBranch'),\n\n path('addBranchContacts/', views.AddBranchContacts.as_view(), name='addBranchContacts'),\n path('listBranchContactaddCompanys/', views.ListBranchContacts.as_view(), name='listBranchContacts'),\n path('detailBranchContacts//', views.DetailBranchContacts.as_view(), name='detailBranchContacts'),\n path('updateBranchContacts//', views.UpdateBranchContacts.as_view(), name='updateBranchContacts'),\n\n path('addBranchEmails/', views.AddBranchEmails.as_view(), name='addBranchEmails'),\n path('listBranchEmails/', views.ListBranchEmails.as_view(), name='listBranchEmails'),\n path('detailBranchEmails//', views.DetailBranchEmails.as_view(), name='detailBranchEmails'),\n path('updateBranchEmails//', views.UpdateBranchEmails.as_view(), name='updateBranchEmails'),\n\n path('listDomains/', views.ListCompanyDomains.as_view(), name='listDomains'),\n path('addDomain/', views.AddCompanyDomain.as_view(), name='addDomain'),\n path('addDomain2/', views.add_select_company_domain, name='addDomains2'),\n path('updateDomain//', views.UpdateDomain.as_view(), name='updateDomain'),\n path('deleteDomain/', views.DeleteDomain.as_view(), name=\"deleteDomain\"),\n path('companies/', views.DomainCompanyList.as_view(), name=\"companies\"),\n path('validateDomainName', views.validateDomainName, name='validateDomainName'),\n path('fetchDomainList/', views.fetch_domain_list, name='fetchDomainList'),\n\n path('listCategories/', views.ListCompanyCategories.as_view(), name='listCategories'),\n path('addCategory/', views.AddCompanyCategory.as_view(), name='addCategory'),\n path('updateCategory//', views.UpdateCategory.as_view(), name='updateCategory'),\n path('deleteCategory/', views.DeleteCategory.as_view(), name=\"deleteCategory\"),\n path('categoryCompany/', views.CompanyCategoryList.as_view(), name=\"categoryCompany\"),\n path('validateCategoryName', views.validateCategoryName, name='validateCategoryName'),\n\n path('listSlaContracts/', views.customer_sla_list, name='listSlaContracts'),\n\n path('addSLA/', views.AddSla.as_view(), name='addSla'),\n path('saveSLA/', views.save_sla, name='saveSLA'),\n path('updateSLA//', views.UpdateSLA.as_view(), name='updateSLA'),\n path('update2SLA/', views.save_sla_update, name='saveSLAupdate'),\n path('listCustomers/', views.list_customers, name='listCustomers'),\n path('addCustomer/', views.add_customer, name='addCustomer'),\n path('saveCustomer', views.save_customer, name='saveCustomer'),\n path('returnCustomer/', views.return_client_company, name='returnCustomer'),\n path('listCustomerPane/', views.customer_list_pane, name='listCustomerPane'),\n path('updateCustomer//', views.UpdateCustomer.as_view(), name='updateCustomer'),\n path('saveCustomerUpdate', views.save_customer_update, name='saveCustomerUpdate'),\n path('detailsCustomer/', views.DetailCustomer.as_view(), name='detailsCustomer'),\n \n]\n","repo_name":"wambozaAllan/Sybyl-Service-Desk-Web","sub_path":"company_management/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4608,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"39343806576","text":"import numpy as np\n\nclass Environment:\n\n state = []\n goal = []\n boundary = []\n action_map = {\n 0: [0, 0],\n 1: [0, 1],\n 2: [0, -1],\n 3: [1, 0],\n 4: [-1, 0],\n }\n\n \n # Init function: I added the possibility to build some unsurmountable walls\n # inside the grid (if wall_penal is specified, walls become surmountable but\n # if the agent decides to do so it will penalized with that value as a reward)\n def __init__(self, x, y, initial, goal, walls=None, wall_penal=None):\n self.boundary = np.asarray([x, y])\n self.state = np.asarray(initial)\n self.goal = goal\n self.walls = walls\n self.wall_penal = wall_penal\n \n\n # the agent makes an action (0 is stay, 1 is up, 2 is down, 3 is right, 4 is left)\n def move(self, action):\n \n # start by default move\n reward = 0\n movement = self.action_map[action]\n \n # check if it is a goal\n if (action == 0 and (self.state == self.goal).all()):\n reward = 1\n next_state = self.state + np.asarray(movement)\n \n # Check if position is allowed or if the agent has to be penalized\n # (First if: check boundaries and unsurmountable walls\n # Second if: check surmountable walls )\n if (self.check_boundaries(next_state)):\n reward = -1\n elif (self.wall_penal!=None) and (self.check_walls(next_state)):\n reward = self.wall_penal\n self.state = next_state\n else:\n self.state = next_state\n \n return [self.state, reward]\n\n\n # map action index to movement and check that new position is allowed\n def check_boundaries(self, state):\n out = len([num for num in state if num < 0])\n out += len([num for num in (self.boundary - np.asarray(state)) if num <= 0])\n if self.walls!=None and self.wall_penal==None:\n out += self.check_walls(state)\n return out > 0\n\n # Function that checks if the position is the same of a wall\n def check_walls(self, state):\n return np.any(np.all(np.asarray(state)==np.asarray(self.walls),axis=1)) ","repo_name":"francescovidaich964/Neural_Network_and_Deep_Learning_Projects","sub_path":"Lab_06/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"12129808410","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: gustavo\n\"\"\"\n\nimport random\nimport matplotlib.pyplot as plt\n\n\np = 0.5\ndx = 1\nt = 10000\nx = [t]\nx[0] = 0\n\nfor i in range(1, t-1):\n if random.random() < p:\n x.append(x[i-1] + dx)\n else:\n x.append(x[i-1] - dx)\n\nplt.plot(x)\n# plt.savefig('plot_caminata_aleatoria_01.eps', format='eps')\n# plt.savefig('plot_caminata_aleatoria_01.png', format='png')\nplt.show()\n","repo_name":"guxtux/FComputacional","sub_path":"Tema 5 - Metodos Monte Carlo/Codigos Python/caminata_aleatoria_01.py","file_name":"caminata_aleatoria_01.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"23206445465","text":"from parse import write_input_file, read_input_file, write_output_file\nfrom random import randrange\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nV = 100\nG = nx.Graph()\nedges = []\nfor i in range(V):\n for j in range(i + 1, V):\n length = randrange(100000) / 1000\n edge = (i, j, length)\n if j == i + 1 or j == i + randrange(V - i - 1):\n edges.append(edge)\n elif randrange(100000) % 2 == 0:\n edges.append(edge)\n\n\nG.add_weighted_edges_from(edges)\nfileName = str(V) + '.in'\nwrite_input_file(G, fileName)\n\nnx.draw(G, with_labels=True, font_weight='bold')\nplt.show()\n\n","repo_name":"pran21/cs170-project","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"43930111315","text":"from pylint.checkers import BaseChecker\nfrom pylint.interfaces import IAstroidChecker\nfrom astroid import nodes, Const, AssignName\n\n\nclass NoPackageName(BaseChecker):\n \"\"\"\n Conanfile used for testing a package should NOT provide a name\n \"\"\"\n\n __implements__ = IAstroidChecker\n\n name = \"conan-test-package-name\"\n msgs = {\n \"E9007\": (\n \"No 'name' attribute in test_package conanfile\",\n \"conan-test-no-name\",\n \"No 'name' attribute in test_package conanfile.\"\n )\n }\n\n def visit_classdef(self, node: nodes) -> None:\n if node.basenames == ['ConanFile']:\n for attr in node.body:\n children = list(attr.get_children())\n if len(children) == 2 and \\\n isinstance(children[0], AssignName) and \\\n children[0].name == \"name\" and \\\n isinstance(children[1], Const):\n self.add_message(\"conan-test-no-name\", node=attr, line=attr.lineno)\n","repo_name":"AnotherFoxGuy/ror-conan-recipes","sub_path":"linter/check_no_test_package_name.py","file_name":"check_no_test_package_name.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"25456660123","text":"\"\"\"Provides a basic example of retrieving a message from StockTwits.\"\"\"\n\nimport pytwits\n\n\ndef main():\n\n access_token = 'TOKEN' # This would also work without passing token.\n stocktwits = pytwits.StockTwits(access_token=access_token)\n\n message = stocktwits.messages(path='show', id=125712744)\n print('Message text: {}\\n\\n'.format(message.body))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tbienias/PyTwits","sub_path":"docs/examples/retrieve_message.py","file_name":"retrieve_message.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"46"} +{"seq_id":"43403393175","text":"#!/usr/bin/env python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\nimport heapq\n\n#\n# Complete the 'cookies' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts following parameters:\n# 1. INTEGER k\n# 2. INTEGER_ARRAY A\n#\n\ndef cookies(k, A):\n # Write your code here\n heapq.heapify(A)\n\n ans = 0\n while True:\n first = heapq.heappop(A)\n\n if first >= k:\n return ans\n\n if len(A) == 0:\n return -1\n\n second = heapq.heappop(A)\n element = first + 2 * second\n heapq.heappush(A, element)\n\n ans += 1\n\n return ans\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n k = int(first_multiple_input[1])\n\n A = list(map(int, input().rstrip().split()))\n\n result = cookies(k, A)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n\n","repo_name":"xuedong/hacker-rank","sub_path":"Interview Preparation Kits/1 Week Preparation Kit/Day 6/Jesse and Cookies/cookies2.py","file_name":"cookies2.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"10105682786","text":"import json\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport datetime as dt\r\nfrom tqdm import tqdm\r\nfrom src.base_requests import BaseRequests\r\n\r\n\r\nHOST = \"https://www.pararius.com\"\r\n\r\n\r\nclass Pararius(BaseRequests):\r\n\r\n def __init__(self):\r\n super(Pararius, self).__init__(HOST)\r\n self.host = HOST\r\n\r\n\r\n def get_listings(self, endpoint=\"/apartments/amsterdam/1500-2200/\", page=1):\r\n endpoint = endpoint + \"page-\" + str(page)\r\n header = {\r\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:105.0) Gecko/20100101 Firefox/105.0\"\r\n }\r\n r = self.get(endpoint, headers=header)\r\n soup = BeautifulSoup(r.text, features=\"html.parser\")\r\n listings = [x.find(\"a\")[\"href\"] for x in soup.find_all(\"h2\", {\r\n \"class\": \"listing-search-item__title\"\r\n })]\r\n return listings\r\n\r\n \r\nif __name__ == \"__main__\":\r\n pararius = Pararius()\r\n r = pararius.get_listings(page=1)\r\n print(r)\r\n","repo_name":"davidconalrobinson/nl-house-search","sub_path":"src/pararius.py","file_name":"pararius.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"28760733324","text":"def paginated_list(object_list, page, page_size=25):\n \"\"\"\n Returns paginated list.\n\n Arguments:\n object_list (QuerySet): A list of records to be paginated.\n page (int): Current page number.\n page_size (int): Number of records displayed in each paginated set.\n show_all (bool): Whether to show all records.\n\n Adopted from django/contrib/admin/templatetags/admin_list.py\n https://github.com/django/django/blob/1.11.1/django/contrib/admin/templatetags/admin_list.py#L50\n \"\"\"\n paginator = CustomPaginator(object_list, page_size)\n try:\n object_list = paginator.page(page)\n except PageNotAnInteger:\n object_list = paginator.page(1)\n except EmptyPage:\n object_list = paginator.page(paginator.num_pages)\n\n page_range = []\n page_num = object_list.number\n\n # If there are 10 or fewer pages, display links to every page.\n # Otherwise, do some fancy\n if paginator.num_pages <= 10:\n page_range = range(paginator.num_pages)\n else:\n # Insert \"smart\" pagination links, so that there are always ON_ENDS\n # links at either end of the list of pages, and there are always\n # ON_EACH_SIDE links at either end of the \"current page\" link.\n if page_num > (PAGES_ON_EACH_SIDE + PAGES_ON_ENDS + 1):\n page_range.extend(range(1, PAGES_ON_ENDS + 1))\n page_range.append(DOT)\n page_range.extend(range(page_num - PAGES_ON_EACH_SIDE, page_num + 1))\n else:\n page_range.extend(range(1, page_num + 1))\n if page_num < (paginator.num_pages - PAGES_ON_EACH_SIDE - PAGES_ON_ENDS):\n page_range.extend(range(page_num + 1, page_num + PAGES_ON_EACH_SIDE + 1))\n page_range.append(DOT)\n page_range.extend(range(paginator.num_pages + 1 - PAGES_ON_ENDS, paginator.num_pages + 1))\n else:\n page_range.extend(range(page_num + 1, paginator.num_pages + 1))\n\n # Override page range to implement custom smart links.\n object_list.paginator.page_range = page_range\n\n return object_list","repo_name":"MichaelFu1998-create/security_scanning","sub_path":"codesearchnet/codesearchnet_8698.py","file_name":"codesearchnet_8698.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"524863180","text":"from django import forms\nfrom django.utils.translation import ugettext_lazy as _, ugettext\nfrom crispy_forms.layout import Layout, Row, HTML, Field\n\nfrom server.forms import FormBase\n\n\nclass PhotoDrawForm(FormBase):\n number_of_results = forms.IntegerField(label=_(\"Number of points\"),\n required=True, initial=1)\n photo_url = forms.URLField(label=_(\"Photo URL\"),\n required=True)\n\n DEFAULT_TITLE = _(\"Random selection in image\")\n\n def __init__(self, *args, **kwargs):\n super(PhotoDrawForm, self).__init__(*args, **kwargs)\n\n # Add \"protected\" class to the input that will be read-only when the draw is shared\n self.fields['number_of_results'].widget.attrs.update({'class': 'protected', 'min': 1})\n self.fields['photo_url'].widget.attrs.update({'class': 'protected'})\n\n self.helper.label_class = 'col-xs-6 text-right'\n self.helper.field_class = 'col-xs-6'\n self.helper.layout = Layout(\n Row(\n Row('number_of_results'),\n Field('photo_url', wrapper_class=\"protected-hidden clearfix\"),\n HTML('
'.format(ugettext('Use a picture from Facebook')))\n ),\n Row(\n HTML(\"\"\"\"\"\"\n \"\"\"\"\"\", )\n )\n )\n","repo_name":"etcaterva/echaloasuerte","sub_path":"server/forms/photo_form.py","file_name":"photo_form.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"46"} +{"seq_id":"13423146873","text":"import os\nimport io\nimport uris\nimport logging\nimport lsp\nfrom text import PublishDiagnosticParams\n\n\nlog = logging.getLogger(__name__)\n\n\n\nclass Document(object):\n\n def __init__(self, uri, source=None, version=None):\n self.uri = uri\n self.version = version\n self.filename = os.path.basename(self.uri)\n self.path = uris.to_fs_path(uri)\n log.info(\"self.path: %s\", self.path)\n self._source = source\n\n @property\n def lines(self):\n return self.source.splitlines(True)\n\n @property\n def source(self):\n if self._source is None:\n with io.open(self.path, 'r', encoding='utf-8') as f:\n return f.read()\n return self._source\n\n def apply_change(self, change):\n text = change['text']\n change_range = change.get('range')\n\n if not change_range:\n self._source = text\n return\n\n start_line = change_range['start']['line']\n start_col = change_range['start']['character']\n end_line = change_range['end']['line']\n end_col = change_range['end']['character']\n\n if start_line == len(self.lines):\n self._source = self._source + text\n return\n\n new = io.StringIO()\n\n for i, line in enumerate(self.lines):\n if i < start_line:\n new.write(line)\n continue\n if i > end_line:\n new.write(line)\n continue\n\n if i == start_line:\n new.write(line[:start_col])\n new.write(text)\n\n if i == end_line:\n new.write(line[end_col:])\n\n self._source = new.getvalue()\n\nclass WorkSpace(object):\n\n def __init__(self, rootUri, endpoint):\n self.rootUri = rootUri\n self.root_path = uris.to_fs_path(self.rootUri)\n self._endpoint = endpoint\n self._docs = {}\n\n def publish_diagnostics(self, doc_uri, diagnostics):\n self._endpoint.notify(lsp.Capability.M_PUBLISH_DIAGNOSTICS, params={'uri': doc_uri, 'diagnostics': diagnostics})\n\n def show_message(self, message, msg_type=lsp.MessageType.Info):\n self._endpoint.notify(lsp.Capability.M_SHOW_MESSAGE, params={'type': msg_type, 'message': message})\n\n def put_document(self, doc_uri, source, version=None):\n self._docs[doc_uri] = self._create_document(doc_uri, source=source, version=version)\n\n def update_document(self, doc_uri, change, version=None):\n self._docs[doc_uri].apply_change(change)\n self._docs[doc_uri].version = version\n \n def _create_document(self, doc_uri, source=None, version=None):\n return Document(doc_uri, source=source, version=version)","repo_name":"excursus/mypyls","sub_path":"mypyls/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"7671157465","text":"'''\n 有道翻译\n'''\nimport requests\nimport time,random\nfrom hashlib import md5\n\nclass YdSpider:\n def __init__(self):\n self.url='http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'\n self.headers = {\n \"Accept\": \"application/json, text/javascript, */*; q=0.01\",\n \"Accept-Encoding\": \"gzip, deflate\",\n \"Accept-Language\": \"zh-CN,zh;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Content-Length\": \"251\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Cookie\": \"OUTFOX_SEARCH_USER_ID=-369496913@10.108.160.19; JSESSIONID=aaaRTXUlLGvgLh9cCe8dx; OUTFOX_SEARCH_USER_ID_NCOO=1151966975.930748; ___rl__test__cookies=1584783177268\",\n \"Host\": \"fanyi.youdao.com\",\n \"Origin\": \"http://fanyi.youdao.com\",\n \"Referer\":\"http://fanyi.youdao.com/\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\",\n \"X-Requested-With\": \"XMLHttpRequest\"\n}\n\n\n def get_ts_salt_sign(self,word):\n ts = str(int(time.time() * 1000))\n salt = ts + str(random.randint(0,9))\n string = \"fanyideskweb\" + word + salt + \"Nw(nmmbP%A-r6U3EUn]Aj\"\n s = md5()\n s.update(string.encode())\n\n sign = s.hexdigest()\n\n return ts,salt,sign\n\n def attack_yd(self,word):\n ts,salt,sign = self.get_ts_salt_sign(word)\n data = {\n \"i\": word,\n \"from\": \"AUTO\",\n \"to\": \"AUTO\",\n \"smartresult\": \"dict\",\n \"client\": \"fanyideskweb\",\n \"salt\": salt,\n \"sign\": sign,\n \"ts\": ts,\n \"bv\": \"94ef9c063d6b2a801fab916722d70203\",\n \"doctype\": \"json\",\n \"version\": \"2.1\",\n \"keyfrom\": \"fanyi.web\",\n \"action\": \"FY_BY_REALTlME\"\n}\n html = requests.post(url=self.url,data=data,headers=self.headers).text\n print(html)\n\n def run(self):\n word = input('请输入要翻译的单词:')\n self.attack_yd(word)\n\n\nif __name__ == '__main__':\n spider = YdSpider()\n spider.run()\n\n\n\n\n","repo_name":"Xback11qm/YouDao","sub_path":"YouDao.py","file_name":"YouDao.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"18440607585","text":"import logging\nimport os\nimport json\nimport boto3\nfrom botocore.exceptions import ClientError\n\ndef lambda_handler(event, context):\n \"\"\"\n Main Function\n\n General description of each step this main function is performing\n \"\"\"\n setup_logging()\n log.info('Lambda received event:')\n log.info(json.dumps(event))\n\n client = boto3.client('s3')\n bucket_name = event['detail']['requestParameters']['bucketName']\n if \"CreateBucket\" in event[\"detail\"][\"eventName\"]:\n\n client.put_bucket_encryption(\n Bucket = bucket_name,\n ServerSideEncryptionConfiguration={\n 'Rules': [\n {\n 'ApplyServerSideEncryptionByDefault': {\n 'SSEAlgorithm': 'AES256'\n }\n }\n ]\n }\n )\n return True\ndef setup_logging():\n \"\"\"\n Logging Function.\n\n Creates a global log object and sets its level.\n \"\"\"\n global log\n log = logging.getLogger()\n log_levels = {'INFO': 20, 'WARNING': 30, 'ERROR': 40}\n\n if 'logging_level' in os.environ:\n log_level = os.environ['logging_level'].upper()\n if log_level in log_levels:\n log.setLevel(log_levels[log_level])\n else:\n log.setLevel(log_levels['ERROR'])\n log.error(\"The logging_level environment variable is not set to INFO, WARNING, or \\\n ERROR. The log level is set to ERROR\")\n else:\n log.setLevel(log_levels['ERROR'])\n log.info('Logging setup complete - set to log level ' + str(log.getEffectiveLevel()))\n","repo_name":"awslabs/aws-lambda-security-controls","sub_path":"amazon-s3/s3-enable-aes-256-encryption/lambda/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"46"} +{"seq_id":"14287801646","text":"import os, sys, time\nfrom platform import system\n\n\nif system() == 'Linux':\n current_path = str(os.path.abspath(os.getcwd())) + '/scripts'\n pico_dir = \"/media/\" + os.popen('whoami').read().replace('\\n', '') + \"/RPI-RP2\"\n if os.path.exists(pico_dir):\n os.system(\"cp \" + current_path + \"/../.pio/build/pico/firmware.uf2 \" + pico_dir)\n else:\n sys.exit()\n\nelif system() == 'Windows':\n # sleep for 1 second to get the 2040 to boot into uf2\n time.sleep(1)\n current_path = str(os.path.abspath(os.getcwd()))\n\n device_ids = os.popen('wmic logicaldisk get deviceid').read().replace(' ', '').strip().split('\\n')\n volume_names = os.popen('wmic logicaldisk get volumename').read().replace(' ', '').strip().split('\\n')\n \n for volume_name, device_id in zip(volume_names, device_ids):\n print(volume_name)\n if volume_name == 'RPI-RP2':\n pico_dir = device_id + \"\\\\\"\n #print(pico_dir)\n break\n\n #print(\"copy \" + current_path + \"\\\\.pio\\\\build\\\\pico\\\\firmware.uf2 \" + pico_dir)\n os.system('copy \"' + current_path + '\\\\.pio\\\\build\\\\pico\\\\firmware.uf2\" ' + pico_dir)\n \nelse:\n print(\"exit, failed\")\n sys.exit()","repo_name":"im-redactd/saintcon2023_minibadge","sub_path":"scripts/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"3351867659","text":"from numbers import Number\n\nimport numpy as np\nimport torch\n\n\nclass MovAvg:\n \"\"\"Class for moving average.\n\n It will automatically exclude the infinity and NaN. Usage:\n ::\n\n >>> stat = MovAvg(size=66)\n >>> stat.add(torch.tensor(5))\n 5.0\n >>> stat.add(float('inf')) # which will not add to stat\n 5.0\n >>> stat.add([6, 7, 8])\n 6.5\n >>> stat.get()\n 6.5\n >>> print(f'{stat.mean():.2f}±{stat.std():.2f}')\n 6.50±1.12\n \"\"\"\n\n def __init__(self, size: int = 100) -> None:\n super().__init__()\n self.size = size\n self.cache: list[np.number] = []\n self.banned = [np.inf, np.nan, -np.inf]\n\n def add(self, data_array: Number | np.number | list | np.ndarray | torch.Tensor) -> float:\n \"\"\"Add a scalar into :class:`MovAvg`.\n\n You can add ``torch.Tensor`` with only one element, a python scalar, or\n a list of python scalar.\n \"\"\"\n if isinstance(data_array, torch.Tensor):\n data_array = data_array.flatten().cpu().numpy()\n if np.isscalar(data_array):\n data_array = [data_array]\n for number in data_array: # type: ignore\n if number not in self.banned:\n self.cache.append(number)\n if self.size > 0 and len(self.cache) > self.size:\n self.cache = self.cache[-self.size :]\n return self.get()\n\n def get(self) -> float:\n \"\"\"Get the average.\"\"\"\n if len(self.cache) == 0:\n return 0.0\n return float(np.mean(self.cache)) # type: ignore\n\n def mean(self) -> float:\n \"\"\"Get the average. Same as :meth:`get`.\"\"\"\n return self.get()\n\n def std(self) -> float:\n \"\"\"Get the standard deviation.\"\"\"\n if len(self.cache) == 0:\n return 0.0\n return float(np.std(self.cache)) # type: ignore\n\n\nclass RunningMeanStd:\n \"\"\"Calculates the running mean and std of a data stream.\n\n https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm\n\n :param mean: the initial mean estimation for data array. Default to 0.\n :param std: the initial standard error estimation for data array. Default to 1.\n :param clip_max: the maximum absolute value for data array. Default to\n 10.0.\n :param epsilon: To avoid division by zero.\n \"\"\"\n\n def __init__(\n self,\n mean: float | np.ndarray = 0.0,\n std: float | np.ndarray = 1.0,\n clip_max: float | None = 10.0,\n epsilon: float = np.finfo(np.float32).eps.item(),\n ) -> None:\n self.mean, self.var = mean, std\n self.clip_max = clip_max\n self.count = 0\n self.eps = epsilon\n\n def norm(self, data_array: float | np.ndarray) -> float | np.ndarray:\n data_array = (data_array - self.mean) / np.sqrt(self.var + self.eps)\n if self.clip_max:\n data_array = np.clip(data_array, -self.clip_max, self.clip_max)\n return data_array\n\n def update(self, data_array: np.ndarray) -> None:\n \"\"\"Add a batch of item into RMS with the same shape, modify mean/var/count.\"\"\"\n batch_mean, batch_var = np.mean(data_array, axis=0), np.var(data_array, axis=0)\n batch_count = len(data_array)\n\n delta = batch_mean - self.mean\n total_count = self.count + batch_count\n\n new_mean = self.mean + delta * batch_count / total_count\n m_a = self.var * self.count\n m_b = batch_var * batch_count\n m_2 = m_a + m_b + delta**2 * self.count * batch_count / total_count\n new_var = m_2 / total_count\n\n self.mean, self.var = new_mean, new_var\n self.count = total_count\n","repo_name":"thu-ml/tianshou","sub_path":"tianshou/utils/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","stars":6905,"dataset":"github-code","pt":"46"} +{"seq_id":"18261900125","text":"from rest_framework import serializers\n\nfrom ..models import WeChatAccount\n\n\nclass WeChatAccountSerializer(serializers.ModelSerializer):\n class Meta:\n model = WeChatAccount\n fields = '__all__'\n extra_kwargs = {\n 'openId': {'write_only': True},\n 'session_key': {'write_only': True},\n 'unionId': {'write_only': True}\n }\n","repo_name":"AngelLiang/django-demo","sub_path":"101-miniprogram/miniprogram/serializers/wechataccount.py","file_name":"wechataccount.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"10796695516","text":"from pygtlink import *\n\n__all__ = ['PositionMessage']\n\nIGTL_STATUS_HEADER_SIZE = 30\n\n# TODO: add documentation\n\n\nclass PositionMessage(MessageBase):\n \"\"\"\n The class implements the openIgtLink position message\n\n :ivar float _x: The x component of the position\n :ivar float _y: The y component of the position\n :ivar float _z: The z component of the position\n :ivar float _ox: The first component of the orientation quaternion\n :ivar float _oy: The second component of the orientation quaternion\n :ivar float _oz: The third component of the orientation quaternion\n :ivar float _w: The fourth component of the orientation quaternion\n \"\"\"\n\n def __init__(self):\n MessageBase.__init__(self)\n\n # Setting std header\n self._messageType = \"POSITION\"\n self._headerVersion = IGTL_HEADER_VERSION_1\n\n # setting command header parameters\n self._x = 0 # float32\n self._y = 0 # float32\n self._z = 0 # float32\n self._ox = 0 # float32\n self._oy = 0 # float32\n self._oz = 0 # float32\n self._w = 0 # float32\n\n def setPosition(self, pos):\n \"\"\"\n Sets the position\n\n :param pos: The position to be set. It can be a 3-element list or nd.array\n \"\"\"\n if len(pos) != 3:\n return\n self._x = float(pos[0])\n self._y = float(pos[1])\n self._z = float(pos[2])\n\n def setQuaternion(self, quat):\n \"\"\"\n Sets the quaternion\n\n :param quat: The quaternion to be set. It can be a 4-element list or nd.array\n \"\"\"\n if len(quat) != 4:\n return\n self._ox = float(quat[0])\n self._oy = float(quat[1])\n self._oz = float(quat[2])\n self._w = float(quat[3])\n\n def getPosition(self):\n \"\"\"\n Gets the position\n\n :returns: The position as a list [x, y, z]\n \"\"\"\n return [self._x, self._y, self._z]\n\n def getQuaternion(self):\n \"\"\"\n Sets the quaternion\n\n :returns: The quaternion as a list [ox, oy, oz, w]\n \"\"\"\n return [self._ox, self._oy, self._oz, self._w]\n\n def _packContent(self, endian=\">\"):\n\n # set the command header\n\n self.body = struct.pack(endian + '7f',\n self._x,\n self._y,\n self._z,\n self._ox,\n self._oy,\n self._oz,\n self._w)\n\n self._bodySize = len(self.body)\n\n def _unpackContent(self, endian=\">\"):\n\n img_binary_header = self.body[0:IGTL_STATUS_HEADER_SIZE]\n unpacked_header = struct.unpack(endian + '7f', img_binary_header)\n\n self._x = unpacked_header[0]\n self._y = unpacked_header[1]\n self._z = unpacked_header[2]\n self._ox = unpacked_header[3]\n self._oy = unpacked_header[4]\n self._oz = unpacked_header[5]\n self._w = unpacked_header[6]\n","repo_name":"mariatirindelli/PyOpenIgtlink","sub_path":"pygtlink/position_message.py","file_name":"position_message.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"46"} +{"seq_id":"27771103775","text":"from time import time\nfrom datetime import datetime, timedelta\nfrom bellum.orders.models import GenericOrderTable, MotherRelocationOrder, LandarmyProduceOrder\nfrom bellum.common.fixtures.relocation import getRelocationTime \n\ndef orderRelocate(mother, race, target_planet):\n now = time()\n relTime = getRelocationTime(mother, race, mother.orbiting, target_planet)\n completion = now + relTime\n\n \n got = GenericOrderTable(None,\n datetime.fromtimestamp(completion),\n datetime.fromtimestamp(now),\n 0)\n got.save()\n\n \n \n mro = MotherRelocationOrder(None,\n got.id,\n mother.orbiting.id,\n target_planet.id,\n mother.id)\n mro.save()\n \ndef doRelocationOrder(entry):\n mro, = MotherRelocationOrder.objects.filter(got=entry)\n mum = mro.mother\n mum.orbiting = mro.loc_to\n mum.save()\n mro.delete()\n \n","repo_name":"piotrmaslanka/bellum","sub_path":"orders/mother/relocate.py","file_name":"relocate.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"46"} +{"seq_id":"15256559494","text":"class Solution(object):\n def findOrder(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: List[int]\n \"\"\"\n graph = {i: [] for i in range(numCourses)}\n indegree = [0] *numCourses\n for a, b in prerequisites:\n graph[b].append(a)\n indegree[a] += 1\n # pick a zero indegree elment \n \n zero = []\n for i in range(numCourses):\n if indegree[i] == 0:\n zero.append(i)\n \n res = [] \n while zero:\n node = zero.pop(0)\n res.append(node)\n \n for n in graph[node]:\n indegree[n] -= 1\n if indegree[n] == 0:\n zero.append(n)\n \n return res if sum(indegree) == 0 else []\n \n","repo_name":"yilinanyu/Leetcode-with-Python","sub_path":"corseschedule2.py","file_name":"corseschedule2.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"46"} +{"seq_id":"14198251475","text":"import json\nimport random, pickle\nimport os,re\nimport pandas as pd\nimport requests\nfrom collections import defaultdict\n\nAPI_ERROR = 'data not found in API!!'\nCALL_API = '需要调用外部api来回答这个问题,'\n\n# 干掉了一些奇怪的设施\ndevice_config = {\n '羊城通充值点':['地铁卡充值的地方','地铁卡充值点'],\n '楼梯升降机':['升降机','电梯'],\n '专用电梯':[],\n '卫生间':['洗手间','厕所','公厕','男厕所','女厕所'],\n '自动柜员机':['贩���机'],\n '自动照相机':['自动照相机','照相机','照相点'],\n '自动售卖机':['自动售卖机'],\n '优惠券打印机':[],\n '手机充电机':['手机充电的地方'],\n '便利店':[],\n '面包西饼':['面包西饼店','面包店','西饼店'],\n '糖果小吃':['糖果店','糖果小吃店','小吃店'],\n '书报文具':['报刊亭'],\n '餐饮':['吃饭的地方','饭店','餐厅'],\n '盲道':[],\n '自助售卡充值机':['售卡机'],\n '母婴室':[],\n '轮椅坡道':['无障碍通道'],\n '出站扶梯':[],\n '进站扶梯':[],\n '无障碍卫生间':[],\n '第三卫生间':[]\n}\n\nstation_alias = {\n '机场南(1号航站楼)':['机场南','机场','白云机场','白云机场1号航站楼','机场1号航站楼'],\n '机场北(2号航站楼)':['机场北','白云机场2号航站楼', '机场2号航站楼']\n}\n\nclass MetraData:\n\n def __init__(self, reload=True) -> None:\n\n self.url_base = 'https://gzmtrapi-t.jiaxincloud.com/mtrassit'\n # name to id mapping\n self.station_dict = {}\n self.station_id_dict = {}\n\n # name to id mapping\n self.line_dict = {}\n\n # device name to id\n self.device_dict = {}\n\n # line name to station name list\n self.line_station_names = {}\n \n # station name to direction list\n self.station_directions = defaultdict(dict)\n\n if reload:\n self._init_lines()\n self._init_stations()\n self._init_device()\n with open('config-sample/metra_obj.pickle', 'wb') as fout:\n pickle.dump([self.station_dict, self.line_dict, self.line_station_names, self.station_directions, self.device_dict], fout)\n else:\n self.station_dict, self.line_dict, self.line_station_names, self.station_directions, self.device_dict = pickle.load(open('config-sample/metra_obj.pickle', 'rb'))\n \n # remap device alias, remove unusual devices\n device_dict = {}\n for k, v in device_config.items():\n device_dict[k] = self.device_dict[k]\n for _k in v:\n device_dict[_k] = self.device_dict[k]\n self.device_dict = device_dict\n\n # map station alias\n for k, v in station_alias.items():\n _id = self.station_dict[k]\n for alias in v:\n self.station_dict[alias] = _id\n\n to_add = []\n for k, _id in self.station_dict.items():\n if k.endswith('站'):\n to_add.append((k[:-1], _id))\n else:\n to_add.append((k+'站', _id))\n\n for k, v in to_add:\n self.station_dict[k] = v\n\n self.station_id_dict = {v:k for k, v in self.station_dict.items()}\n\n def _init_lines(self):\n url = f'{self.url_base}/rest/mtr/lines'\n res = requests.get(url).json()\n\n for rec in res['lines']:\n self.line_dict[rec['nameCn']] = rec['lineId']\n\n return self.line_dict\n\n def _init_stations(self):\n for line_name, line_id in self.line_dict.items():\n url = f'{self.url_base}/rest/mtr/lines/{line_id}/stations'\n station_info = requests.get(url).json()['stations']\n dir1 = station_info[0]['nameCn']\n dir2 = station_info[-1]['nameCn']\n self.line_station_names[line_name] = [s['nameCn'] for s in station_info]\n\n for station in station_info:\n self.station_dict[station['nameCn']] = station['stationId']\n self.station_directions[station['nameCn']][line_name] = {\n 'dir1':dir1,\n 'dir2':dir2\n }\n\n def _init_device(self):\n url = f'{self.url_base}/rest/mtr/categories'\n device_info = requests.get(url).json()['categories']\n for d in device_info:\n self.device_dict[d['nameCn']] = d['categoryId']\n\n def _check_station(self, station_name):\n if not station_name in self.station_dict:\n return f'抱歉广州地铁没有{station_name}站' \n \n def _check_device(self, device_name):\n if device_name not in self.device_dict:\n return f\"抱歉广州地铁没有{device_name}\"\n\n def _check_line(self, line_name):\n if not line_name in self.line_station_names:\n return f\"抱歉广州地铁没有{line_name}\"\n\n def _query_time(self, type, from_station, to_station):\n from_id = self.station_dict[from_station]\n to_id = self.station_dict[to_station]\n _url = f'{self.url_base}/rest/mtr/serviceTimes?stationId={from_id}&toStationId={to_id}'\n\n service_time = requests.get(_url).json()['serviceTimes']\n service_time = [s for s in service_time if s['stationId'] == from_id]\n try:\n return service_time[0][type]\n \n \n except (KeyError,IndexError):\n return API_ERROR\n\n def list_line_stations(self, line_name):\n if self._check_line(line_name) is not None:\n return self._check_line(line_name)\n \n return ','.join(self.line_station_names[line_name])\n\n def query_station_time(self, type, station_name):\n if self._check_station(station_name) is not None:\n return self._check_station(station_name)\n\n directions = self.station_directions[station_name]\n txt_list = []\n for line_name, dirs in directions.items():\n dir1 = dirs['dir1']\n dir2 = dirs['dir2']\n\n dir1_time = self._query_time(type, from_station=station_name, to_station=dir1)\n dir2_time = self._query_time(type, from_station=station_name, to_station=dir2)\n\n _facelet = '首班车' if type == 'startTime' else '末班车'\n\n txt = f'{line_name}{station_name}前往{dir1}的{_facelet}时间是{dir1_time},往{dir2}方向的{_facelet}时间是{dir2_time}'\n txt_list.append(txt)\n\n return '。'.join(txt_list)+'。'\n\n def query_route_time(self, type, from_station, to_station):\n if self._check_station(from_station):\n return self._check_station(from_station)\n \n if self._check_station(to_station):\n return self._check_station(to_station)\n\n\n _time = self._query_time(type, from_station, to_station)\n _facelet = '首班车' if type == 'startTime' else '末班车'\n txt = f\"{from_station}前往{to_station}的{_facelet}时间是{_time}\"\n \n\n return txt\n\n def query_device(self, station_name, device_name):\n if self._check_station(station_name):\n return self._check_station(station_name)\n \n if self._check_device(device_name):\n return self._check_device(device_name)\n\n station_id = self.station_dict[station_name]\n device_id = self.device_dict[device_name]\n\n _url = f'{self.url_base}/rest/mtr/devices?stationId={station_id}&categoryId={device_id}'\n data = requests.get(_url).json()\n if len(data.get('stations',[]))>0:\n devices = data['stations']\n txt = f'{device_name}位于'\n elif len(data.get('recommendStations',[]))>0:\n txt = f'最近的{device_name}位于'\n devices = data['recommendStations']\n else:\n devices = []\n\n if len(devices)>0:\n for d in devices:\n if 'stationId' in d:\n _name = self.station_id_dict[d['stationId']]\n txt += f\"{_name}的{d['locationCn']}\"\n else:\n txt += f\"{d['locationCn']}\"\n else:\n txt = f'{station_name}附近没有{device_name}'\n \n return txt\n\n def query_route(self, from_station, to_station):\n if self._check_station(from_station):\n return self._check_station(from_station)\n \n if self._check_station(to_station):\n return self._check_station(to_station)\n\n from_id = self.station_dict[from_station]\n to_id = self.station_dict[to_station]\n _url = f'{self.url_base}/rest/mtr/transfer?stationId={from_id}&toStationId={to_id}'\n try:\n route = requests.get(_url).json()['transfer']['routeCn']\n route_desc = json.loads(route)['desc']\n except KeyError:\n route_desc = API_ERROR\n return route_desc\n\n def query_ticket(self, from_station, to_station):\n if self._check_station(from_station):\n return self._check_station(from_station)\n \n if self._check_station(to_station):\n return self._check_station(to_station)\n\n from_id = self.station_dict[from_station]\n to_id = self.station_dict[to_station]\n _url = f'{self.url_base}/rest/mtr/ticketPrice?stationId={from_id}&toStationId={to_id}'\n try:\n price = requests.get(_url).json()['ticketPrice']\n return f'从{from_station}到{to_station}的地铁票价是{price}元'\n except KeyError:\n return API_ERROR\n \n\n def query_station_nearby(self, location):\n _url = f'{self.url_base}/rest/mtr/near?location={location}'\n desc = requests.get(_url).json()\n return desc\n \n \n def proceed_api_call(self, api_str):\n # find func call pattern\n p = f'({CALL_API}[\\w|_]*\\([^()]*\\))'\n matched = re.findall(p, api_str)\n\n ans = api_str\n for func_str in matched:\n api_result = self._proceed_api_call(func_str.replace(CALL_API,''))\n ans = ans.replace(func_str, api_result)\n\n '''\n 因为答案的format没考虑周全,训练数据中混入了格式混乱的数据。需要在这里硬处理一下。治本的方法把API返回的文本和template文案约定好标点符号的使用\n '''\n ans = ans.replace('。,','。')\n\n return ans\n\n # if ',' in api_str:\n # api_strs = api_str.split(',')\n # results = [self._proceed_api_call(s) for s in api_strs]\n # text = results[0]\n # for r in results[1:]:\n # if r[-1] in [',','。']:\n # text += r\n # else:\n # text += ','+r\n # return text\n # else:\n # return self._proceed_api_call(api_str)\n\n def _proceed_api_call(self, api_str):\n try:\n return eval(f'self.{api_str}')\n except Exception as e:\n print('error processing '+api_str)\n\nif __name__ == '__main__':\n data = MetraData(reload=False)\n \n \n result = data.line_dict.keys()\n print(','.join(result))\n \n ","repo_name":"kaihe/xunhong","sub_path":"metra_api.py","file_name":"metra_api.py","file_ext":"py","file_size_in_byte":11245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"37765841814","text":"import os.path as path\nimport math\n\n# Input data\n# ==========\n\nhfac = 4.0\ncs = 50.0\ncourant = 0.1\nrefd = 1.0\nalpha = 0.0\nRe = 2000\nU = 1.0\nL = H = 2.0 * math.pi\nperiods_to_run = 30.0\np0 = 3.0 * refd * U**2\n# Number of fluid particles in y direction\nnx = ny = 400\n\n# Dimensions and number of particles readjustment\n# ===============================================\ndr = L / nx\nn = nx * ny\n\nvisc_dyn = refd * U * L / Re\nvisc_dyn = max(alpha / 8.0 * refd * hfac * dr * cs, visc_dyn)\n\nT = L / U\nend_time = periods_to_run * T\n\n# Particles generation\n# ====================\nprint(\"Opening output file...\")\noutput = open(\"Fluid.dat\", \"w\")\nstring = \"\"\"#############################################################\n# #\n# # ## # # # # #\n# # # # # # # # # # #\n# ##### # # # # ##### ## ### # # ## ### ### #\n# # # # # # # # # # # # # # # # # # # # #\n# # # # # # # # # # # # # # # # # # # # #\n# # # ## # ## # # ### ### ### ## ### # # #\n# # # # #\n# ## # # #\n# #\n#############################################################\n\"\"\"\noutput.write(string)\nprint(string)\n\nstring = \"\"\"\n Writing fluid particles...\n\"\"\"\nprint(string)\n\nPercentage = -1\ni = 0\nimove = 1\nEkin = 0.0\nx = -0.5 * L + 0.5 * dr\nwhile x < 0.5 * L:\n y = -0.5 * H + 0.5 * dr\n while y < 0.5 * H:\n if Percentage != (i * 100) / n:\n Percentage = (i * 100) / n\n if not Percentage % 10:\n string = ' {}%'.format(Percentage)\n print(string)\n \n \n i += 1\n u = U * math.sin(x) * math.cos(y) \n v = -U * math.cos(x) * math.sin(y)\n press = (math.cos(2.0 * x) + math.cos(2.0 * y)) / 4.0 \n dens = refd + press / cs**2\n mass = refd * dr**2.0\n Ekin += 0.5 * mass * (u*u + v*v)\n string = (\"{} {}, \" * 4 + \"{}, {}, {}, {}\\n\").format(\n x, y,\n 0.0, 0.0,\n u, v,\n 0.0, 0.0,\n dens,\n 0.0,\n mass,\n imove)\n output.write(string)\n y += dr\n x += dr\nprint(' 100%')\n\n# XML definition generation\n# =========================\n\ntemplates_path = path.join('@EXAMPLE_DEST_DIR@', 'templates')\nXML = ('BCs.xml', 'Fluids.xml', 'Main.xml', 'plot_e.py', 'Rescale.cl',\n 'Rescale.xml', 'Settings.xml', 'SPH.xml', 'BCs.xml', 'Time.xml')\n\ndomain_min = (-L, -H)\ndomain_min = str(domain_min).replace('(', '').replace(')', '')\ndomain_max = (L, H)\ndomain_max = str(domain_max).replace('(', '').replace(')', '')\n\ndata = {'DR':str(dr), 'HFAC':str(hfac), 'CS':str(cs), 'COURANT':str(courant),\n 'DOMAIN_MIN':domain_min, 'DOMAIN_MAX':domain_max, 'REFD':str(refd),\n 'VISC_DYN':str(visc_dyn), 'P0':str(p0), 'RE':str(Re), 'L':str(L),\n 'U':str(U), 'N':str(n), 'END_TIME':str(end_time), 'E_KIN':str(Ekin)}\nfor fname in XML:\n # Read the template\n f = open(path.join(templates_path, fname), 'r')\n txt = f.read()\n f.close()\n # Replace the data\n for k in data.keys():\n txt = txt.replace('{{' + k + '}}', data[k])\n # Write the file\n f = open(fname, 'w')\n f.write(txt)\n f.close()\n","repo_name":"sanguinariojoe/aquagpusph","sub_path":"examples/2D/taylor_green/cMake/Create.py","file_name":"Create.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"46"} +{"seq_id":"19030473393","text":"import pathlib\n\nimport pytorch_lightning as pl\nimport torchvision.io as io\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import DataLoader, Dataset\n\n\nclass ColorMapDataset(Dataset):\n\n def __init__(self, dataset_paths):\n self.dataset_paths = dataset_paths\n\n def __len__(self):\n return len(self.dataset_paths)\n\n def __getitem__(self, idx):\n image_path, cmap_path = self.dataset_paths[idx]\n image = io.read_image(str(image_path), mode=io.ImageReadMode.RGB)\n cmap = io.read_image(str(cmap_path), mode=io.ImageReadMode.RGB)\n\n image = (image - 127.5) / 128.0 # normalize to [-1, 1]\n cmap = (cmap - 127.5) / 128.0\n return image, cmap\n\n\nclass ColorMapDatamodule(pl.LightningDataModule):\n\n def __init__(\n self, seed=420, resolution=256,\n batch_size=16, num_workers=4, val_samples=12, subsample=-1\n ):\n super().__init__()\n\n self.seed = seed\n self.batch_size = batch_size\n self.num_workers = num_workers\n\n data_dir = pathlib.Path(__file__).parents[2] / \"data\" / str(resolution)\n raw_dir = data_dir / \"raw\"\n image_paths = list(sorted(raw_dir.glob(\"*.png\")))\n image_paths = image_paths[:subsample] if (subsample > 0) else image_paths\n\n def cmap_path(_image_path):\n return data_dir / \"cmaps\" / f\"cmap_{_image_path.stem}.png\"\n\n dataset_paths = [(p, cmap_path(p)) for p in image_paths]\n\n # (X, 10) train-val split\n pl.seed_everything(seed=seed)\n train_size = len(dataset_paths) - val_samples\n train_paths, val_paths = train_test_split(dataset_paths, train_size=train_size, random_state=seed)\n\n self.train = ColorMapDataset(train_paths)\n self.val = ColorMapDataset(val_paths)\n\n def train_dataloader(self):\n return DataLoader(self.train, self.batch_size, shuffle=True, num_workers=self.num_workers)\n\n def val_dataloader(self):\n return DataLoader(self.val, 1, num_workers=self.num_workers)\n","repo_name":"alstonlo/photobashing-gan","sub_path":"src/experimental/datamodule.py","file_name":"datamodule.py","file_ext":"py","file_size_in_byte":2037,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"570751979","text":"# services/db-api/project/manage.py\n\n\nfrom flask.cli import FlaskGroup, with_appcontext\nfrom project import app, db, mongo\nfrom project.api_models.station import Station\nimport os\n\ncli = FlaskGroup(app)\n\n@cli.command()\ndef recreate_db():\n print('Running cli_recreate_db')\n db.drop_all()\n db.create_all()\n db.session.commit()\n\n@cli.command()\ndef init_tables():\n print('Running through cli_init_tables')\n \"\"\" Load station master data from csv\"\"\"\n with open(os.environ.get('MASTER_STATION'), 'r') as f:\n conn = db.engine.connect().connection\n cursor = conn.cursor()\n cmd = 'COPY station(bundesland,rb,bm,bfnr,station,bfdsabk,katvst,strasse,plz,ort,aufgabenvergeber) FROM STDIN WITH (FORMAT CSV, HEADER TRUE, DELIMITER \";\", ENCODING \"UTF-8\")'\n cursor.copy_expert(cmd, f)\n conn.commit()\n\n with open(os.environ.get('MASTER_ELEVATOR'), 'r') as f:\n conn = db.engine.connect().connection\n cursor = conn.cursor()\n cmd = 'COPY elevator(standort_equipment,technplatzbezeichng,equipment,equipmentname,ort,wirtschaftseinheit,hersteller,baujahr,antriebsart,anzahl_haltestellen,anzahl_tueren_kabine,anzahl_tueren_schacht,foerdergeschwindigkeit,foerderhoehe,lage,tragkraft,erweiterte_ortsangabe,min_tuerbreite,kabinentiefe,kabinenbreite,kabinenhoehe,tuerhohe,fabriknummer,tuerart,geokoordinaterechtswert,geokoordinatehochwert,ausftextlichebeschreibung) FROM STDIN WITH (FORMAT CSV, HEADER TRUE, DELIMITER \";\", ENCODING \"UTF-8\")'\n cursor.copy_expert(cmd, f)\n conn.commit()\n\n#mongo cli commands\n@cli.command()\ndef mongo_init():\n print('run trough docker with: docker-compose exec mongo-db mongorestore -u bart -p \"downy37)tory\" -h mongo-db --port 27017 -d eva_dev ./data/db/dump/eva')\n #mongo.cx.admin.command('ismaster')\n\n\nif __name__ == '__main__':\n print('Running through main')\n cli()\n","repo_name":"JoshPrim/EVA-Projekt","sub_path":"services/db-api/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"29518476814","text":"import numpy as np\n\nimport qubit\nimport qugate\n\n\nclass QuReg:\n\n def __init__(self, size):\n self.size = size\n self.score = {}\n self.next_time = 1\n\n def __call__(self, arg):\n if isinstance(arg, np.matrix):\n return self.get_op * arg\n\n def add_gate(self, gate, bit=1, time=None):\n\n if not time:\n time = self.next_time\n\n num_qubits = int(np.log(gate.op.shape[0]) / np.log(2) + 1 / 2)\n time_ops = self.score[time] if time in self.score else {}\n\n for i in range(num_qubits):\n time_ops[bit + i] = (gate, i)\n\n self.score[time] = time_ops\n self.next_time = max(self.next_time, time + 1)\n\n print(num_qubits, \",\", time_ops.keys(), \",\", self.score.keys())\n\n return self\n\n def get_op(self):\n ops = [step[1] for step in sorted([[time, ops] for time, ops in self.score.items()])[::-1]]\n return np.prod([np.sum([qugate.I if bit not in op else op[bit][0] for bit in range(1, self.size + 1) if (bit in op and not op[bit][1]) or bit not in op]) for op in ops])\n","repo_name":"eddddddy/QuSim","sub_path":"qureg.py","file_name":"qureg.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"4236807720","text":"import pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\n\n\ndef read_exsx_file():\n excel = pd.read_excel(\"./1112 10片2448網片偏移量與焊接測試結果/1112 10片2448網片偏移量與焊接測試結果_AOI_sorted.xlsx\")\n return excel\n\n\ndef read_aoi_labels_and_d_values():\n excel = read_exsx_file()\n e1 = excel.iloc[:20, 9: 15]\n e2 = excel.iloc[:20, 24: 30]\n e1.columns = [\"品質(上)\", \"品質(下)\", \"品質(上)-對角\", \"品質(下)-對角\", \"d值\", \"d值-對角\"]\n e2.columns = e1.columns\n df = pd.concat([e1, e2], ignore_index=True)\n return df\n\n\n# 分短邊與長邊\n# df = read_aoi_labels_and_d_values()\n# df[\"品質組合\"] = df[\"品質(上)\"] + df[\"品質(下)\"]\n# df[\"品質組合-對角\"] = df[\"品質(上)-對角\"] + df[\"品質(下)-對角\"]\n# df = df.replace(\"OKOK\", \"OK\").replace(\"NGNG\", \"NG\")\n# df = df[[\"品質組合\", \"d值\", \"品質組合-對角\", \"d值-對角\"]]\n#\n# df_long = pd.DataFrame()\n# df_short = pd.DataFrame()\n# i = 0\n#\n# while i < len(df):\n#\n# df_long = pd.concat([df_long, df.loc[df.index == i, [\"品質組合\", \"d值\"]]], ignore_index=True)\n# df_ = df.loc[df.index == i + 1, [\"品質組合-對角\", \"d值-對角\"]]\n# df_.columns = df_long.columns\n# df_long = pd.concat([df_long, df_], ignore_index=True)\n#\n# df_short = pd.concat([df_short, df.loc[df.index == i + 1, [\"品質組合\", \"d值\"]]], ignore_index=True)\n# df_ = df.loc[df.index == i, [\"品質組合-對角\", \"d值-對角\"]]\n# df_.columns = df_long.columns\n# df_short = pd.concat([df_short, df_], ignore_index=True)\n#\n# i = i + 2\n#\n# fig = go.Figure()\n# fig.add_trace(go.Box(x=df_long[\"品質組合\"], y=df_long[\"d值\"], name=\"長邊\"))\n# fig.add_trace(go.Box(x=df_short[\"品質組合\"], y=df_short[\"d值\"], name=\"短邊\"))\n# fig.write_html(\"./1219 d值量測結果/長邊-短邊.html\")\n# # fig.show()\n# exit(0)\n\n# 分OK與NG\ndf = read_aoi_labels_and_d_values()\ndf[\"品質組合\"] = df[\"品質(上)\"] + df[\"品質(下)\"]\ndf[\"品質組合-對角\"] = df[\"品質(上)-對角\"] + df[\"品質(下)-對角\"]\ndf = df.replace(\"OKOK\", \"OK\").replace(\"NGNG\", \"NG\")\ndf1 = df[[\"品質組合\", \"d值\"]]\ndf2 = df[[\"品質組合-對角\", \"d值-對角\"]]\ndf2.columns = df1.columns\ndf = pd.concat([df1, df2], ignore_index=True)\n\ndf_OK = df[df[\"品質組合\"] == \"OK\"]\ndf_NG = df[df[\"品質組合\"] == \"NG\"]\ndf_OKNG = df[df[\"品質組合\"] == \"OKNG\"]\ndf_NGOK = df[df[\"品質組合\"] == \"NGOK\"]\n\nprint(\"OK占比:{}/{}\".format(len(df_OK), len(df)))\nprint(\"OKNG占比:{}/{}\".format(len(df_OKNG), len(df)))\nprint(\"NGOK占比:{}/{}\".format(len(df_NGOK), len(df)))\nprint(\"NG占比:{}/{}\".format(len(df_NG), len(df)))\n\nfig = px.box(df, x=\"品質組合\", y=\"d值\", points=\"all\")\nfig.write_html(\"./1219 d值量測結果/OK-NG.html\")\n# fig.show()\n\n","repo_name":"ShaoHsienLo/III-I-JANG-code-backup","sub_path":"d_value_and_aoi_result.py","file_name":"d_value_and_aoi_result.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"74503563018","text":"\"\"\"\nhttps://leetcode.com/problems/min-stack/description/\n\nDesign a stack that supports push, pop, top, and retrieving the minimum element\nin constant time.\n\npush(x) -- Push element x onto stack.\npop() -- Removes the element on top of the stack.\ntop() -- Get the top element.\ngetMin() -- Retrieve the minimum element in the stack.\n\nExample:\n MinStack minStack = new MinStack();\n\n minStack.push(-2);\n minStack.push(0);\n minStack.push(-3);\n minStack.getMin(); --> Returns -3.\n minStack.pop();\n minStack.top(); --> Returns 0.\n minStack.getMin(); --> Returns -2.\n\n---\n\n-2\n-2 0\n-2 0 -3\n-2 0 <- 0 is top\n\n\"\"\"\nimport sys\n\n\nclass MinStack:\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.stack = []\n self.min_stack = []\n\n def push(self, x):\n \"\"\"\n :type x: int\n :rtype: void\n \"\"\"\n self.stack.append(x)\n\n n = len(self.min_stack)\n if n == 0:\n self.min_stack.append(x)\n elif x <= self.min_stack[n - 1]:\n self.min_stack.append(x)\n\n def pop(self):\n \"\"\"\n :rtype: void\n \"\"\"\n size = len(self.stack)\n pop = self.stack[size - 1]\n self.stack = self.stack[0:size - 1]\n\n n = len(self.min_stack)\n if pop == self.min_stack[n - 1]:\n self.min_stack = self.min_stack[0:n - 1]\n\n def top(self):\n \"\"\"\n :rtype: int\n \"\"\"\n n = len(self.stack)\n return self.stack[n - 1]\n\n def getMin(self):\n \"\"\"\n :rtype: int\n \"\"\"\n n = len(self.min_stack)\n return self.min_stack[n - 1]\n","repo_name":"dreamflyings/codingchallenge","sub_path":"leetcode/python/min_stack.py","file_name":"min_stack.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"22042643872","text":"import torch\nimport numpy as np\nfrom flickr.data.build import make_dataloader\nfrom flickr.data.transforms.build import build_transforms\nfrom flickr.modules import *\nfrom flickr.data.build import build_dataset\nfrom flickr.data import samplers\n\nfrom common.utils.load import smart_resume, smart_partial_load_model_state_dict\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport torch.distributed as distributed\nimport random\nfrom tqdm import tqdm\nfrom flickr.data.collate_batch import BatchCollator\nimport pickle\nimport os, sys\ntry:\n from apex import amp\n from apex.parallel import DistributedDataParallel as Apex_DDP\nexcept ImportError:\n pass\n\nIMG_SIZE = 1000\nTXT_SIZE = 1000 * 5\n\n\ndef to_cuda(batch):\n batch = list(batch)\n\n for i in range(len(batch)):\n if isinstance(batch[i], torch.Tensor):\n batch[i] = batch[i].cuda(non_blocking=True)\n elif isinstance(batch[i], list):\n for j, o in enumerate(batch[i]):\n if isinstance(batch[i], torch.Tensor):\n batch[i][j] = o.cuda(non_blocking=True)\n\n return batch\n\n\ndef reconstruct_txt_batch(batch, new_batch):\n for b, new_b in zip(batch, new_batch):\n b[3] = new_b[0]\n b[5] = new_b[1]\n return batch\n\n\ndef reconstruct_img_batch(batch, new_batch):\n for b, new_b in zip(batch, new_batch):\n b[0] = new_b[0]\n b[1] = new_b[1]\n b[2] = new_b[2]\n b[-1] = new_b[-1]\n return batch\n\n\ndef generated_model_loader(args, config):\n # manually set random seed\n if config.RNG_SEED > -1:\n random.seed(config.RNG_SEED)\n np.random.seed(config.RNG_SEED)\n torch.random.manual_seed(config.RNG_SEED)\n torch.cuda.manual_seed_all(config.RNG_SEED)\n\n # cudnn\n torch.backends.cudnn.benchmark = False\n if args.cudnn_off:\n torch.backends.cudnn.enabled = False\n\n model = eval(config.MODULE)(config)\n\n if args.dist:\n local_rank = int(os.environ.get('LOCAL_RANK') or 0)\n config.GPUS = str(local_rank)\n torch.cuda.set_device(local_rank)\n master_address = os.environ['MASTER_ADDR']\n master_port = int(os.environ['MASTER_PORT'] or 23457)\n world_size = int(os.environ['WORLD_SIZE'] or 1)\n rank = int(os.environ['RANK'] or 0)\n if args.slurm:\n distributed.init_process_group(backend='nccl')\n else:\n distributed.init_process_group(\n backend='nccl',\n init_method='tcp://{}:{}'.format(master_address, master_port),\n world_size=world_size,\n rank=rank,\n group_name='mtorch')\n\n print(f'native distributed, size: {world_size}, local rank: {local_rank}')\n torch.cuda.set_device(local_rank)\n config.GPUS = str(local_rank)\n\n model = model.cuda()\n if not config.TRAIN.FP16:\n model = DDP(model, device_ids=[local_rank], output_device=local_rank)\n\n test_dataloader = make_dataloader(config,\n mode='test',\n distributed=True,\n num_replicas=world_size,\n rank=rank)\n\n else:\n model = model.cuda()\n test_dataloader = make_dataloader(config, mode='test', distributed=False)\n\n if config.TRAIN.FP16:\n [model] = amp.initialize([model],\n opt_level='O2',\n keep_batchnorm_fp32=False)\n if args.dist:\n model = Apex_DDP(model, delay_allreduce=False)\n\n # partial load pretrain state dict\n if config.NETWORK.PARTIAL_PRETRAIN != \"\":\n pretrain_state_dict = \\\n torch.load(config.NETWORK.PARTIAL_PRETRAIN, map_location=lambda storage, loc: storage)[\n 'state_dict']\n prefix_change = [prefix_change.split('->') for prefix_change in\n config.NETWORK.PARTIAL_PRETRAIN_PREFIX_CHANGES]\n if len(prefix_change) > 0:\n pretrain_state_dict_parsed = {}\n for k, v in pretrain_state_dict.items():\n no_match = True\n for pretrain_prefix, new_prefix in prefix_change:\n if k.startswith(pretrain_prefix):\n k = new_prefix + k[len(pretrain_prefix):]\n pretrain_state_dict_parsed[k] = v\n no_match = False\n break\n if no_match:\n pretrain_state_dict_parsed[k] = v\n pretrain_state_dict = pretrain_state_dict_parsed\n smart_partial_load_model_state_dict(model, pretrain_state_dict)\n\n if args.dist:\n distributed.barrier()\n for v in model.state_dict().values():\n distributed.broadcast(v, src=0)\n\n return test_dataloader, model\n\n\ndef generate_ITR_scores(test_dataloader, model):\n txt2img_scores = torch.ones([TXT_SIZE, IMG_SIZE]).cuda()*(-100)\n model.eval()\n\n for nbatch, batch in tqdm(enumerate(test_dataloader), 'ITR: '):\n img_index = batch[-2]\n txt_index = batch[-1]\n batch = to_cuda(batch[:-2])\n outputs, loss = model.forward(*batch)\n txt2img_scores[txt_index, img_index] = outputs['rank_scores'].view(-1).detach()\n\n return txt2img_scores\n\n\ndef test_net(args, config):\n if os.path.exists(os.path.join(args.model_dir, 'flickr_txt2img.pkt')):\n data = torch.load(os.path.join(args.model_dir, 'flickr_txt2img.pkt'))\n score_matrix = data['score_matrix']\n else:\n test_dataloader, model = generated_model_loader(args, config)\n score_matrix = generate_ITR_scores(test_dataloader, model)\n if args.dist:\n distributed.all_reduce(score_matrix)\n if not os.path.exists(args.model_dir):\n os.makedirs(args.model_dir)\n torch.save({'score_matrix': score_matrix},\n os.path.join(args.model_dir, 'flickr_txt2img.pkt'))\n\n img2j = {i: j for j, i in enumerate(range(IMG_SIZE))}\n txt2i = {t: i for i, t in enumerate(range(TXT_SIZE))}\n txt2img = torch.tensor([[i]*5 for i in range(IMG_SIZE)]).view(-1).tolist()\n img2txts = torch.tensor([list(range(5*i, 5*i+5)) for i in range(IMG_SIZE)]).tolist()\n txt_ids = range(TXT_SIZE)\n img_ids = range(IMG_SIZE)\n # image retrieval\n _, rank_txt = score_matrix.topk(10, dim=1)\n gt_img_j = torch.LongTensor([img2j[txt2img[txt_id]]\n for txt_id in txt_ids],\n ).to(rank_txt.device\n ).unsqueeze(1).expand_as(rank_txt)\n rank = (rank_txt == gt_img_j).nonzero()\n if rank.numel():\n ir_r1 = (rank < 1).sum().item() / len(txt_ids)\n ir_r5 = (rank < 5).sum().item() / len(txt_ids)\n ir_r10 = (rank < 10).sum().item() / len(txt_ids)\n else:\n ir_r1, ir_r5, ir_r10 = 0, 0, 0\n\n # text retrieval\n _, rank_img = score_matrix.topk(10, dim=0)\n tr_r1, tr_r5, tr_r10 = 0, 0, 0\n for j, img_id in enumerate(img_ids):\n gt_is = [txt2i[t] for t in img2txts[img_id]]\n ranks = [(rank_img[:, j] == i).nonzero() for i in gt_is]\n rank = min([10] + [r.item() for r in ranks if r.numel()])\n if rank < 1:\n tr_r1 += 1\n if rank < 5:\n tr_r5 += 1\n if rank < 10:\n tr_r10 += 1\n tr_r1 /= len(img_ids)\n tr_r5 /= len(img_ids)\n tr_r10 /= len(img_ids)\n\n tr_mean = (tr_r1 + tr_r5 + tr_r10) / 3\n ir_mean = (ir_r1 + ir_r5 + ir_r10) / 3\n r_mean = (tr_mean + ir_mean) / 2\n\n eval_log = {'txt_r1': tr_r1,\n 'txt_r5': tr_r5,\n 'txt_r10': tr_r10,\n 'txt_r_mean': tr_mean,\n 'img_r1': ir_r1,\n 'img_r5': ir_r5,\n 'img_r10': ir_r10,\n 'img_r_mean': ir_mean,\n 'r_mean': r_mean}\n print(eval_log)\n return eval_log","repo_name":"supfisher/DCE-VL-Boosting-Generic-Visual-Linguistic-Representation-with-Dynamic-Contexts","sub_path":"VL-BERT/flickr/function/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7939,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"24170936898","text":"# 对于china_trial每行数据,根据icd9匹配atc-4\n# 查询不到对应的atc-4时,写入的值为{'ATC': {}, 'Prob': {}}\n\nimport os\nimport pandas as pd\n\nfrom dotenv import load_dotenv\n\nload_dotenv() # load .env file\n\n\ncolumn_name_of_icd9 = os.environ.get(\"column_name_of_icd9\")\ncolumn_name_of_atc = os.environ.get(\"column_name_of_atc\")\noutput_save_path = os.environ.get(\"output_save_path\")\ninput_data_path = os.environ.get(\"input_data_path\")\nICD2ATC_path = os.environ.get(\"ICD2ATC_path\")\n\ndef icd9_to_atc4(icd9:int, ICD2ATC_df:pd.DataFrame)->dict:\n '''\n input icd9 value, return atc-4 accordingly\n icd9 must be integer or else the boolean indexing will always be False\n\n >>> df = read_ICD2ATC()\n >>> icd = 7\n >>> print(icd9_to_atc4(icd, df))\n {'ATC': {3: 'A07A', 4: 'P01A'}, 'Prob': {3: 0.4666500746640119, 4: 0.533349925335988}}\n '''\n # 获取对应分布\n atc4_distr = ICD2ATC_df[ICD2ATC_df[\"ICD\"] == icd9]\n\n # 使用.to_dict()转换为字典格式,读取为DataFrame时可以用pd.DataFrame.from_dict()\n atc4_distr = atc4_distr[['ATC', 'Prob']].to_dict()\n # print(atc4_distr)\n\n # 返回字典格式\n return atc4_distr\n\n\ndef read_ICD2ATC(path:str=ICD2ATC_path)->pd.DataFrame:\n '''read ICD2ATC excel file'''\n\n dtypes = {\n \"ATC\": \"object\", \n \"ICD\": \"object\",\n \"Prob\": \"float\"\n }\n\n df = pd.read_excel(path, dtype=dtypes, usecols=list(dtypes))\n return df\n\n\n\ndef iterate_over(icd9_df:pd.DataFrame, ICD2ATC_df:pd.DataFrame)->pd.DataFrame:\n '''\n 遍历dataframe每一行, 返回写入atc-4后的dataframe\n 设置缺失值处理逻辑\n '''\n \n for i in icd9_df.index:\n icd9 = icd9_df.at[i, column_name_of_icd9]\n\n # icd9非缺失值且为纯数字\n if not pd.isna(icd9) and icd9.isdigit():\n\n # 将Excel中文本格式储存的数字转换为int类型\n \n icd9 = int(icd9)\n\n # 调用helper function,将atc-4写入该列\n icd9_df.at[i, column_name_of_atc] = str(icd9_to_atc4(icd9, ICD2ATC_df))\n else:\n # 跳过缺失值的处理\n continue\n\n return icd9_df\n\n\n\ndef test_icd9_to_atc4():\n icd9 = 3 # icd9 must be integer\n ICD2ATC_df = read_ICD2ATC()\n print(ICD2ATC_df.dtypes)\n print(ICD2ATC_df)\n icd9_to_atc4(icd9, ICD2ATC_df)\n\n# test icd9_to_atc4 function\n# test_icd9_to_atc4()\n\n\n# def main():\n# # 用pandas读取indication > icd9操作后的结果,成为dataframe对象\n# icd9_df = pd.read_excel(input_data_path)\n \n# print(icd9_df)\n\n# # 插入新的一列用于存储atc-4 value\n# # icd9_df['atc-4'] = None # 通过事先手动插入来注释掉这一行\n \n# # 读取包含ICD到ATC转换关系的excel\n# ICD2ATC_df = read_ICD2ATC()\n\n# # 遍历每一行, 处理得到写入atc-4的dataframe对象\n# atc4_df = iterate_over(icd9_df, ICD2ATC_df)\n# print(atc4_df[\"ATC-4\"])\n\n# # 用pandas将dataframe对象保存为新的excel文件\n# atc4_df.to_excel(output_save_path)\n\n\n# if __name__ == \"__main__\":\n# main()\n\n\n# run doctest\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()","repo_name":"arocen/drug_data_process","sub_path":"icd9_to_atc4.py","file_name":"icd9_to_atc4.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"43062519133","text":"from bs4 import BeautifulSoup\r\nimport time\r\nimport requests\r\nimport json\r\nimport re\r\nimport codecs\r\nfrom six import u\r\n\r\ndef ptt_crawler():\r\n resp = requests.get(\r\n url = PTT_URL + '/bbs/Gossiping/index.html',\r\n cookies = {'over18': '1'},\r\n verify = True,\r\n timeout = 3\r\n )\r\n if resp.status_code != 200:\r\n print('Invalid url:', resp.url)\r\n\r\n soup = BeautifulSoup(resp.text,\"html.parser\")\r\n next_url = soup.select(\"div.btn-group.btn-group-paging a\")\r\n page = next_url[1][\"href\"][20:25]\r\n \r\n resp = requests.get(\r\n url = PTT_URL + '/bbs/Gossiping/index' + str(page) + '.html',\r\n cookies = {'over18': '1'}\r\n )\r\n if resp.status_code != 200:\r\n print('Invalid url:', resp.url)\r\n \r\n soup = BeautifulSoup(resp.text, 'html.parser')\r\n divs = soup.find_all(\"div\", \"r-ent\") \r\n for div in divs:\r\n try:\r\n href = div.find('a')['href']\r\n link = PTT_URL + href\r\n article_id = re.sub('\\.html', '', href.split('/')[-1])\r\n #print(link, article_id + '\\n')\r\n parse_article(link, article_id)\r\n except:\r\n pass\r\n time.sleep(0.5)\r\n\r\ndef parse_article(link, article_id):\r\n resp = requests.get(\r\n url = link,\r\n cookies = {'over18': '1'},\r\n verify = True,\r\n timeout = 3\r\n )\r\n if resp.status_code != 200:\r\n print('Invalid url:', resp.url)\r\n return json.dumps({\"error\": \"invalid url\"}, sort_keys=True, ensure_ascii=False)\r\n\r\n soup = BeautifulSoup(resp.text, 'html.parser')\r\n main_content = soup.find(id=\"main-content\")\r\n metas = main_content.select('div.article-metaline')\r\n author = ''\r\n title = ''\r\n date = ''\r\n if metas:\r\n author = metas[0].select('span.article-meta-value')[0].string if metas[0].select('span.article-meta-value')[0] else author\r\n title = metas[1].select('span.article-meta-value')[0].string if metas[1].select('span.article-meta-value')[0] else title\r\n date = metas[2].select('span.article-meta-value')[0].string if metas[2].select('span.article-meta-value')[0] else date\r\n \r\n # remove and keep push nodes\r\n pushes = main_content.find_all('div', class_='push')\r\n for push in pushes:\r\n push.extract()\r\n \r\n # 移除 '※ 發信站:' (starts with u'\\u203b'), '◆ From:' (starts with u'\\u25c6'), 空行及多餘空白\r\n # 保留英數字, 中文及中文標點, 網址, 部分特殊符號\r\n filtered = [ v for v in main_content.stripped_strings if v[0] not in [u'※', u'◆'] and v[:2] not in [u'--'] ]\r\n expr = re.compile(u(r'[^\\u4e00-\\u9fa5\\u3002\\uff1b\\uff0c\\uff1a\\u201c\\u201d\\uff08\\uff09\\u3001\\uff1f\\u300a\\u300b\\s\\w:/-_.?~%()]'))\r\n for i in range(len(filtered)):\r\n filtered[i] = re.sub(expr, '', filtered[i])\r\n\r\n filtered = [_f for _f in filtered if _f] # remove empty strings\r\n filtered = [x for x in filtered if article_id not in x] # remove last line containing the url of the article\r\n content = ' '.join(filtered)\r\n content = re.sub(r'(\\s)+', ' ', content)\r\n\r\n data = {\r\n 'url': link,\r\n 'article_id': article_id,\r\n 'article_title': title,\r\n 'author': author,\r\n 'date': date,\r\n 'content': content,\r\n }\r\n print(data, '\\n')\r\n\r\nif __name__ == '__main__':\r\n PTT_URL = 'https://www.ptt.cc'\r\n filename = 'PTT_Gossiping.json'\r\n ptt_crawler()","repo_name":"Staler2019/NCU-Projects","sub_path":"WIMU/WebCrawler_DataStore/sample code/crawler_ptt.py","file_name":"crawler_ptt.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"70762240139","text":"\"\"\"\n@FileName:check_download.py\\n\n@Description:检查下载文件是否完整\\n\n@Author:Wang.Lei\\n\n@Time:2023/3/14 10:44\\n\n@Department:Postgrate\\n\n\"\"\"\nfrom pathlib import Path\nimport arcpy\n\ndef find_files(path, endwith = 'tif'):\n # 获取路径下所有文件中的 .tif文件,并且依据文件名数字进行排序\n # 注意需要 i 需为 Path 类型,才可以使用 .stem 方法访问文件名 str\n find_function = sorted(Path(path).rglob('*' + endwith),\n key= lambda i: int(i.stem[0:]))\n imgsdir_list = find_function\n\n return imgsdir_list\n\n\narcpy.env.workspace = r\"H:\\2020-10-01_2020-12-31S2_sorted\"\nimg_path = r\"H:\\2020-10-01_2020-12-31S2_sorted\"\n# arcpy.env.workspace = 'H:\\Mosaic'\n# img_path = r\"H:\\Mosaic\"\n# 计算总共渔网个数\nshp_path = r\"F:\\Data\\yuwang_data\\Southest.shp\"\ncount = int(arcpy.management.GetCount(shp_path).getOutput(0))\n\n# 查找路径下的文件\nimgsdir_list = find_files(img_path)\ncount_list = list(range(count))\n# 创建已有文件文件名列表(数字)\nimgs_list_num = []\nfor img_dir in imgsdir_list:\n img_name_num = int(img_dir.stem[0:])\n imgs_list_num.append(img_name_num)\n\ndiffer_list = list(set(count_list).difference(imgs_list_num))\ndiffer_list.sort(reverse=False)\nif __name__=='__main__':\n need_list_ans=[]\n differ_begin = differ_list[0]\n for i in range(len(differ_list)):\n if i+1 < len(differ_list) and differ_list[i+1]-differ_list[i]!=1:\n need_list_ans.append([differ_begin,differ_list[i]])\n print(differ_begin,differ_list[i])\n differ_begin = differ_list[i+1]","repo_name":"LeiWangqq/Study","sub_path":"glacier/check_download.py","file_name":"check_download.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"73307408139","text":"import re\nimport pandas as pd\nfrom hazm import Normalizer\nfrom string import punctuation\nfrom datetime import datetime\nfrom jdatetime import datetime as jd\nfrom tqdm import tqdm\nimport numpy as np\n\ntqdm.pandas()\n\nclass Clean:\n\n def __init__(self, data, field_name) -> None:\n self.normalizer = Normalizer()\n self.data = data\n self.field_name = field_name\n \n @staticmethod\n def remove_punctuation(text):\n punctuation_ = punctuation+'،'\n\n return text.translate(str.maketrans(punctuation_, ' '*len(punctuation_))) \n \n @staticmethod\n def replace_with_space(text):\n return text.replace('\\u200c', ' ')\n \n def normalize(self, row):\n row[self.field_name] = self.normalizer.normalize(row[self.field_name])\n row[self.field_name] = self.remove_punctuation(row[self.field_name])\n row[self.field_name] = self.replace_with_space(row[self.field_name])\n return row\n \n def normalize_data(self):\n self.data = self.data.progress_apply(self.normalize, axis=1)\n return self.data\n","repo_name":"ali-ardakani/CarModelPredictor","sub_path":"data_processing/clean.py","file_name":"clean.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"22905343006","text":"# -*- coding: utf-8 -*-\n# pylint: disable=no-self-use,invalid-name,protected-access\n\nimport sqlite3\n\nfrom unittest import mock, TestCase\n\nfrom src import lsankidb\n\nclass LsankidbTests(TestCase):\n @mock.patch('src.lsankidb.print')\n @mock.patch('src.lsankidb.Db')\n @mock.patch('src.lsankidb._find_db_path')\n @mock.patch('src.lsankidb._parse_args')\n def test_main_finds_db_and_prints_it(self, mock_parse_args, mock_find_db_path, mock_db,\n mock_print):\n mock_parse_args.return_value.PATH = None\n mock_find_db_path.return_value = '/path/to/db.anki2'\n mock_db.side_effect = ['hello']\n\n lsankidb.main()\n\n mock_db.assert_called_once_with(mock_find_db_path.return_value)\n mock_print.assert_has_calls([mock.call('hello')])\n\n @mock.patch('src.lsankidb.print')\n @mock.patch('src.lsankidb.Db')\n @mock.patch('src.lsankidb._parse_args')\n def test_main_prints_passed_db(self, mock_parse_args, mock_db, mock_print):\n mock_parse_args.return_value.PATH = '/path/to/db.anki2'\n mock_db.side_effect = ['hello']\n\n lsankidb.main()\n\n mock_db.assert_called_once_with(mock_parse_args.return_value.PATH)\n mock_print.assert_has_calls([mock.call('hello')])\n\n @mock.patch('src.lsankidb._find_db_path')\n @mock.patch('src.lsankidb._parse_args')\n def test_main_fails_if_no_db_found(self, mock_parse_args, mock_find_db_path):\n mock_parse_args.return_value.PATH = None\n mock_find_db_path.return_value = None\n\n with self.assertRaises(SystemExit):\n lsankidb.main()\n\n @mock.patch('src.lsankidb.Db')\n @mock.patch('src.lsankidb._parse_args')\n def test_main_fails_with_corrupted_db(self, mock_parse_args, mock_db):\n mock_parse_args.return_value.PATH = '/path/to/db.anki2'\n mock_db.side_effect = sqlite3.OperationalError('error')\n\n with self.assertRaises(sqlite3.OperationalError):\n lsankidb.main()\n\n @mock.patch('src.lsankidb.os.walk')\n def test_find_db_path_happy_case(self, mock_walk):\n mock_walk.return_value = [('/root', [], ['unsupported.ext', 'db.anki2'])]\n\n self.assertEqual('/root/db.anki2', lsankidb._find_db_path('/search/here'))\n\n @mock.patch('src.lsankidb.os.walk')\n def test_find_db_path_sad_case(self, mock_walk):\n mock_walk.return_value = [('/root', [], ['unsupported.ext', 'unsupported2.ext'])]\n\n self.assertIsNone(lsankidb._find_db_path('/search/here'))\n\nclass DbTests(TestCase):\n @mock.patch('AnkiTools.tools.read.readAnki2')\n def test_init_reads_decks_and_cards(self, mock_read):\n mock_read.return_value.__enter__.return_value.decks = {\n '1': {\n 'did': '1',\n 'name': 'german',\n },\n '2': {\n 'did': '2',\n 'name': 'french',\n },\n }\n mock_read.return_value.__enter__.return_value.cards = {\n '10': {\n 'did': '1',\n 'note': {\n 'content': 'a',\n },\n },\n '11': {\n 'did': '1',\n 'note': {\n 'content': 'b',\n },\n },\n '20': {\n 'did': '2',\n 'note': {\n 'content': 'c',\n },\n },\n }\n\n self.assertEqual(\"\"\"\\\nfrench\n c\ngerman\n a\n b\"\"\", str(lsankidb.Db('/path/to/db.anki2')))\n\n def test_init_fails_if_unsupported_extension(self):\n with self.assertRaises(KeyError):\n lsankidb.Db('/path/to/unsupported.ext')\n\n @mock.patch('AnkiTools.tools.read.readApkg')\n def test_init_supports_apkg_extension(self, mock_read):\n db_path = '/path/to/db.apkg'\n\n lsankidb.Db(db_path)\n\n mock_read.assert_called_once_with(db_path)\n\n @mock.patch('AnkiTools.tools.read.readAnki2')\n def test_init_removes_duplicate_cards(self, mock_read):\n mock_read.return_value.__enter__.return_value.decks = {\n '1': {\n 'did': '1',\n 'name': 'german',\n },\n }\n mock_read.return_value.__enter__.return_value.cards = {\n '10': {\n 'did': '1',\n 'note': {\n 'content': 'a',\n },\n },\n '11': {\n 'did': '1',\n 'note': {\n 'content': 'a',\n },\n },\n }\n\n self.assertEqual(\"\"\"\\\ngerman\n a\"\"\", str(lsankidb.Db('/path/to/db.anki2')))\n","repo_name":"AurelienLourot/lsankidb","sub_path":"test/test_lsankidb.py","file_name":"test_lsankidb.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"46"} +{"seq_id":"1810290444","text":"import os\nimport argparse\nimport tensorflow as tf\n\nparser = argparse.ArgumentParser()\nparser.add_argument('path')\nparser.add_argument('--version', default=0)\nargs = parser.parse_args()\n\ninputs = tf.placeholder(tf.int32, [None, 1])\noutputs = tf.identity(inputs)\n\ninputs_info = tf.saved_model.utils.build_tensor_info(inputs)\noutputs_info = tf.saved_model.utils.build_tensor_info(outputs)\n\nsignature = (\n tf.saved_model.signature_def_utils.build_signature_def(\n inputs={tf.saved_model.signature_constants.PREDICT_INPUTS: inputs_info},\n outputs={tf.saved_model.signature_constants.PREDICT_OUTPUTS: outputs_info},\n method_name=tf.saved_model.signature_constants.PREDICT_METHOD_NAME\n )\n)\n\nwith tf.Session() as sess:\n builder = tf.saved_model.builder.SavedModelBuilder(os.path.join(args.path, str(args.version)))\n builder.add_meta_graph_and_variables(\n sess,\n [tf.saved_model.tag_constants.SERVING],\n signature_def_map={tf.saved_model.signature_constants.PREDICT_METHOD_NAME: signature}\n )\n builder.save()\n","repo_name":"dwyatte/tensorflow-serving-benchmark","sub_path":"server/create_model.py","file_name":"create_model.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","stars":33,"dataset":"github-code","pt":"46"} +{"seq_id":"43573780619","text":"\"\"\"\n\n \"\"\"\n\nimport json\n\nimport pandas as pd\nfrom githubdata import GithubData\n\n\nclass Params :\n min_dur_sec = 3600\n\np = Params()\n\nclass GDUrl :\n with open('gdu.json' , 'r') as fi :\n gj = json.load(fi)\n\n selff = gj['selff']\n src = gj['src']\n src0 = gj['src0']\n src1 = gj['src1']\n\ngu = GDUrl()\n\nclass ColName :\n tn = 'TracingNo'\n ctic = 'CodalTicker'\n cname = 'CompanyName'\n lc = 'LetterCode'\n titl = 'Title'\n pjdt = 'PublishDateTime'\n isest = 'IsEstimate'\n ftic = 'FirmTicker'\n dur = 'Duration'\n\nc = ColName()\n\ndef main() :\n pass\n\n ##\n\n gd_src = GithubData(gu.src)\n ##\n ds = gd_src.read_data()\n ##\n c2k = {\n c.tn : None ,\n c.ctic : None ,\n c.pjdt : None ,\n }\n ds = ds[c2k.keys()]\n\n ##\n msk = ds[c.tn].isna()\n df1 = ds[msk]\n\n ##\n ds = ds.dropna(subset = [c.ctic])\n\n ##\n\n gd0 = GithubData(gu.src0)\n ds0 = gd0.read_data()\n ##\n ds0 = ds0.set_index(c.ctic)\n ##\n\n ds[c.ftic] = ds[c.ctic].map(ds0[c.ftic])\n ##\n ds = ds.dropna(subset = [c.ftic])\n ds = ds.drop(columns = [c.ctic])\n ds = ds[[c.tn , c.ftic , c.pjdt]]\n\n ##\n\n gd1 = GithubData(gu.src1)\n do = gd1.read_data()\n ##\n dov = do.head()\n ##\n\n msk = do[c.dur].ge(p.min_dur_sec)\n\n df1 = do[~msk]\n df2 = do[msk]\n\n ##\n\n\n ##\n\n##\nif __name__ == '__main__' :\n main()\n print('Done!')\n","repo_name":"imahdimir/assign-news-to-day","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"44028880053","text":"# pylint: disable=missing-docstring\n\nimport unittest\n\nfrom pyfakefs import fake_filesystem_unittest\n\nfrom soften import app\n\n\ndef make_config():\n return app.Config(author='Mock Author',\n email='author@mock.com',\n name='mypkg',\n url='mypkg.mock.com',\n version='1.2.3')\n\n\nclass TestSoften(unittest.TestCase):\n \"\"\"Uncategorized tests.\"\"\"\n\n def test_has_main(self):\n config = make_config()\n config.repo_path = '/myRepo'\n with fake_filesystem_unittest.Patcher() as patcher:\n self.assertFalse(app.has_main(config))\n patcher.fs.CreateFile('/myRepo/mypkg/__main__.py')\n self.assertTrue(app.has_main(config))\n","repo_name":"nicholasbishop/soften","sub_path":"tests/test_soften.py","file_name":"test_soften.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"8552065366","text":"#!/usr/bin/env python \n\nfrom matplotlib import pyplot as plt \n\n\ndef get_data(inf):\n\n data = {}\n with open(inf, 'r') as f:\n\n while True:\n line = f.readline()\n if not line:\n break\n else:\n line = f.readline()\n nk = (line.split()[-1]).strip(':')\n line = f.readline()\n if nk not in data:\n data[nk] = {}\n data[nk]['x'] = []\n data[nk]['y'] = []\n energy = float(line.split()[2]) \n ampmx = float(line.split()[5])\n data[nk]['x'].append(energy)\n data[nk]['y'].append(ampmx)\n \n return data \n \nfig=plt.figure(figsize=(6,4))\nax1=plt.subplot(121)\nax2=plt.subplot(122)\ndata1 = get_data('AgIn.matrix')\ndata2 = get_data('ZnSn.matrix')\n\nfor k in data1:\n ax1.bar(data1[k]['x'], data1[k]['y'], color='k', width=0.01)\nfor k in data2:\n ax2.bar(data2[k]['x'], data2[k]['y'], color='k', width=0.01)\n\nax1.arrow(1.03,0.08, 0.0, -0.06, fc='r', ec='r',\n\thead_width=0.05, head_length=0.02)\nax1.text(1.03-0.3, 0.085, \"$\\mathregular{E_{g}=\"+str(1.03)+\"}$\")\nax2.arrow(0.81,0.08, 0.0, -0.06, fc='r', ec='r',\n\thead_width=0.05, head_length=0.02)\nax2.text(0.81-0.3, 0.085, \"$\\mathregular{E_{g}=\"+str(0.81)+\"}$\")\nax1.set_title('$\\mathregular{Cs_{4}[AgIn]_{2}Cl_{12}}$')\nax2.set_title('$\\mathregular{Cs_{4}[Ag_{2}ZnSn]Cl_{12}}$')\nax1.set_xlim(0.5,3.0)\nax1.set_ylim(0.,0.6)\nax2.set_ylim(0.,0.6)\nax2.set_xlim(0.5,3.0)\nplt.xlabel(\"Energy (eV)\")\nax1.set_ylabel(\"Ampitude\")\nplt.savefig('matrix.png', dpi=300)\n#plt.show()\n\n\n\n","repo_name":"CaptainDasheng/MMP2_learn","sub_path":"jump4by/jump2/visualizer/post_data/matrix/plot_matrix.py","file_name":"plot_matrix.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"30526707496","text":"from django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom personas.models import persona\nfrom .forms import PersonaForm\n\ndef paginainicio(request):\n return render(request,'PaginaInicio.html')\n\ndef Registro(request):\n if request.method == 'POST':\n form = PersonaForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('gestionusuarios')\n else:\n form = PersonaForm()\n return render(request,'Registro.html',{'form':form})\n\ndef gestionusuarios(request):\n no_personas_var = persona.objects.count()\n Personas = persona.objects.all()\n DicMensajes = {'msg1': 'Valor mensaje 1'}\n return render(request,'Gestionusuarios.html', {'no personas':no_personas_var, 'personas':Personas})\n\ndef EditarPersona(request, id):\n Persona = persona.objects.get(id = id)\n if request.method == 'GET':\n form = PersonaForm(instance=Persona)\n contexto = {\n 'form':form\n }\n else:\n form = PersonaForm(request.POST, instance=Persona)\n contexto = {\n 'form':form\n }\n if form.is_valid():\n form.save()\n return redirect('gestionusuarios')\n return render(request,'Registro.html', contexto)\n\ndef eliminarPersona(request, id):\n Persona = persona.objects.get(id = id)\n Persona.delete()\n return redirect('gestionusuarios')\n\n\n\n","repo_name":"carlos14ms/FINAL_TENDECIAS","sub_path":"sap/SITIOWEB/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"39004500804","text":"from tkinter import *\n\n\n# Action perform on button\ndef calculate():\n result = float(entry.get())\n km = round(result * 1.609)\n label3.config(text=km)\n\n\nwindow = Tk()\nwindow.title(\"Mile to Km converter\")\nwindow.config(padx=20, pady=20)\n\n# Entry\nentry = Entry(width=10)\nentry.grid(column=1, row=0)\n\n# Label1\nlabel = Label(text=\"Miles\")\nlabel.grid(column=2, row=0)\n\n# Label2\nlabel2 = Label(text=\"is equal to\")\nlabel2.grid(column=0, row=1)\n\n# Label3\nlabel3 = Label(text=\"0\")\nlabel3.grid(column=1, row=1)\n\n# Label4\nlabel4 = Label(text=\"Km\")\nlabel4.grid(column=2, row=1)\n\n\n\n\n# Button\nbutton = Button(text=\"Calculate\", command=calculate)\nbutton.grid(column=1, row=2)\n\nwindow.mainloop()\n","repo_name":"NosheenRashid/OOP_Projects","sub_path":"mile_to_km/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"41138273444","text":"import Dynamics\nimport numpy as np\n\n\nclass InverseController(object):\n def __init__(self, Kp, Kv):\n \"\"\"\n\n :param Kp: numpy matrix\n :param Kv: numpy matrix\n \"\"\"\n self._Kv = Kv\n self._Kp = Kp\n\n def get_torque(self, robot, q,qd,qdd):\n \"\"\"\n\n :param robot: the robot\n :param trajectory: tuple of joint trajectories\n :return: the torqu input\n \"\"\"\n\n q_measured = np.asarray(robot.q).reshap(3, 1)\n qd_measured = np.asarray(robot.qd).reshap(3, 1)\n\n q_desired = np.asarray(q).reshap(3, 1)\n qd_desired = np.asarray(qd).reshap(3, 1)\n qdd_desired = np.asarray(qdd).reshap(3, 1)\n\n aq = qdd_desired - self._Kv*(qd_measured - qd_desired ) - self._Kp*(q_measured - q_desired )\n\n M = Dynamics.make_mass_matrix(robot)\n C = Dynamics.make_coriolis_matrix(robot)\n G = Dynamics.make_gravity_matrix(robot)\n load = np.asarray(robot.tau).reshap(3, 1)\n\n u = M*aq + C*qd_measured + G - load\n\n\n\n","repo_name":"StrokeRehabilitationRobot/Dynamics","sub_path":"InverseController.py","file_name":"InverseController.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"14092986396","text":"#!/usr/bin/python3\n\n\"\"\" Load cultural features questionnaires and parse them into a working format \"\"\"\n\nimport pandas\nfrom xlrd.biffh import XLRDError\nfrom clldutils.misc import slug\n\nclass UnexpectedCultureFormatError (ValueError):\n \"\"\"Exception to be thrown when a questionnaire is misformatted\"\"\"\n pass\n\ndef parse_culture_questionnaire(filename):\n questionnaire = pandas.ExcelFile(filename)\n\n metadata_sheet_name = 'Metadata'\n if metadata_sheet_name in questionnaire.sheet_names:\n metadata_sheet = questionnaire.parse(metadata_sheet_name, header=None)\n try:\n metadata_blob = \"; \".join(map(str, metadata_sheet.values))\n except KeyError:\n metadata_blob = \"\"\n else:\n metadata_blob = \"\"\n metadata = metadata_blob\n\n weird_rows = set()\n answers = pandas.DataFrame(columns = [\"Answer\", \"Original Answer\", \"Notes\"])\n features = pandas.DataFrame(columns = [\"Domain\", \"Question_text_English\", \"Question_text_Indonesian\", \"Question_notes\"])\n try:\n data_sheet = questionnaire.parse(\n 0,\n skiprows=[0, 1, 2, 3, 4]).dropna('columns', 'all')\n except XLRDError:\n raise UnexpectedCultureFormatError(\n \"Culture sheet did not have a 'Questionnaire' sheet\")\n if \"answer\" in data_sheet.columns[5].lower():\n cols = list(data_sheet.columns)\n cols[5]=\"Original Answer\"\n data_sheet.columns = cols\n else:\n raise UnexpectedCultureFormatError(\n \"Expected Excel column F to have 'answer' in its header.\")\n \n for i, row in data_sheet.iterrows():\n if pandas.isnull(row[\"Q_ID\"]):\n # print(row)\n continue\n id = str(row[\"Q_ID\"]).lower()\n if pandas.isnull(row[5]):\n # print(row)\n continue\n else:\n question = row[features.columns]\n question.name = id\n features = features.append(question)\n\n answer = row[answers.columns]\n if pandas.isnull(answer['Original Answer']):\n answer['Answer'] = None\n elif type(answer['Original Answer']) == int:\n answer['Answer'] = answer['Original Answer']\n elif slug(answer['Original Answer']) == 'yes':\n answer['Answer'] = True\n elif slug(answer['Original Answer']) == 'no':\n answer['Answer'] = False\n elif slug(answer['Original Answer']) == 'na':\n answer['Answer'] = None\n else:\n answer['Answer'] = answer['Original Answer']\n\n answer.name = id\n answers = answers.append(answer)\n\n assert(len(features) == len(answers))\n return metadata, features, answers\n\nif __name__=='__main__':\n import sys\n metadata, features, answers = parse_questionnaire(sys.argv[1])\n print(metadata)\n print(features)\n print(answers.to_string())\n","repo_name":"Anaphory/plld_app","sub_path":"plld_app/scripts/parse_cultural_questionnaire.py","file_name":"parse_cultural_questionnaire.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"30837679638","text":"import torch\nimport torch.nn as nn\nimport torch.autograd as autograd\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nimport model as model\nimport util_openimages as util\nfrom config import opt\nimport numpy as np\nimport random\nimport time\nimport os\nimport socket\nfrom torch.utils.data import DataLoader\nimport h5py\nimport pickle\nimport logging\nimport csv\nimport pandas as pd\n\nif not os.path.exists(\"logs\"):\n os.system(\"mkdir -p \" + \"logs\") #os.mkdir(\"logs\")\nlog_filename = os.path.join(\"logs\",opt.SESSION + '.log')\nlogging.basicConfig(level=logging.INFO, filename=log_filename)\n\nprint(opt)\nlogging.info(opt)\n\n#############################################\n#setting up seeds\nif opt.manualSeed is None:\n opt.manualSeed = random.randint(1, 10000)\nprint(\"Random Seed: \", opt.manualSeed)\nnp.random.seed(opt.manualSeed)\nrandom.seed(opt.manualSeed)\ntorch.manual_seed(opt.manualSeed)\nif opt.cuda:\n torch.cuda.manual_seed(opt.manualSeed)\n torch.cuda.manual_seed_all(opt.manualSeed)\ntorch.set_default_tensor_type('torch.FloatTensor')\ncudnn.benchmark = True # For speed i.e, cudnn autotuner\n########################################################\n\nif torch.cuda.is_available() and not opt.cuda:\n print(\"WARNING: You have a CUDA device, so you should probably run with --cuda\")\n\n\ndata = util.DATA_LOADER(opt) ### INTIAL DATALOADER ###\nprint('===> Loading datasets')\nprint(opt.src)\nprint('===> Result path ')\nprint(opt.save_path)\nprint('===> total samples')\nprint(data.ntrain)\n\nlogging.info('===> Loading datasets')\nlogging.info(opt.src)\nlogging.info('===> total samples')\nlogging.info(data.ntrain)\n\nmodel_vgg = None\nmodel_vgg = model.vgg_net()\nmodel_test = model.BiAM(opt, dim_feature=[196,512])\n\nprint(model_test)\nlogging.info(model_test)\nname='NUS_WIDE_{}'.format(opt.SESSION)\nopt.save_path += '/'+name\n\nif opt.cuda:\n model_test = model_test.cuda()\n data.vecs_400 = data.vecs_400.cuda()\n data.vecs_7186 = data.vecs_7186.cuda()\n if model_vgg is not None:\n model_vgg.cuda()\n if not opt.vgg_base_trainmode:\n model_vgg.eval()\ngzsl_vecs = torch.cat([data.vecs_7186,data.vecs_400],0)\n\n\nprint(\"=======================EVALUATION MODE=======================\")\nlogging.info(\"=======================EVALUATION MODE=======================\")\ntest_start_time = time.time()\n\ngzsl_model_path=\"pretrained_weights/model_best_gzsl.pth\"\nzsl_model_path=\"pretrained_weights/model_best_zsl.pth\"\n\npaths = [gzsl_model_path, zsl_model_path]\nfor model_path in paths:\n print(model_path)\n logging.info(model_path)\n model_test.load_state_dict(torch.load(model_path))\n logging.info(\"model loading finished\")\n model_test.eval()\n\n src = opt.src\n test_loc = os.path.join(src, 'OpenImages', 'test_features_lesa', 'OPENIMAGES_TEST_CONV5_4_LESA_VGG_NO_CENTERCROP.h5')\n test_features = h5py.File(test_loc, 'r')\n test_feature_keys = list(test_features.keys())\n image_names = np.unique(np.array([m.split('-')[0] for m in test_feature_keys]))\n ntest = len(image_names)\n test_batch_size = opt.test_batch_size\n\n path_top_unseen = os.path.join(src, 'OpenImages','2018_04', 'top_400_unseen.csv')\n df_top_unseen = pd.read_csv(path_top_unseen, header=None)\n idx_top_unseen = df_top_unseen.values[:, 0]\n assert len(idx_top_unseen) == 400\n\n print('===> total TEST samples')\n print(ntest)\n logging.info('===> total TEST samples')\n logging.info(ntest)\n\n prediction_400 = torch.empty(ntest,400)\n prediction_7586 = torch.empty(ntest,7586)\n prediction_7186 = torch.empty(ntest,7186)\n lab_400 = torch.empty(ntest,400)\n lab_7586 = torch.empty(ntest,7586)\n lab_7186 = torch.empty(ntest,7186)\n\n if model_vgg is not None:\n model_vgg.eval()\n\n for m in range(0, ntest, test_batch_size):\n strt = m\n endt = min(m+test_batch_size, ntest)\n bs = endt-strt\n c=m\n c+=bs\n features, labels_7186, labels_2594 = np.empty((bs,512,196)), np.empty((bs,7186)), np.empty((bs,2594))\n for i, key in enumerate(image_names[strt:endt]):\n features[i,:,:] = np.float32(test_features.get(key+'-features'))\n labels_7186[i,:] = np.int32(test_features.get(key+'-seenlabels'))\n labels_2594[i,:] = np.int32(test_features.get(key+'-unseenlabels'))\n\n features = torch.from_numpy(features).float()\n labels_7186 = torch.from_numpy(labels_7186).long()\n labels_400 = torch.from_numpy(labels_2594).long()[:,idx_top_unseen]\n labels_7586 = torch.cat((labels_7186,labels_400),1)\n\n with torch.no_grad():\n vgg_4096 = model_vgg(features.cuda()) if model_vgg is not None else None\n logits_400 = model_test(features.cuda(), data.vecs_400, vgg_4096)\n logits_7586 = model_test(features.cuda(), gzsl_vecs, vgg_4096) ##seen-unseen\n logits_7186 = model_test(features.cuda(), data.vecs_7186, vgg_4096) ##seen-unseen\n \n prediction_400[strt:endt,:] = logits_400\n prediction_7586[strt:endt,:] = logits_7586\n prediction_7186[strt:endt,:] = logits_7186\n\n lab_400[strt:endt,:] = labels_400\n lab_7586[strt:endt,:] = labels_7586\n lab_7186[strt:endt,:] = labels_7186\n\n print((\"completed calculating predictions over all {} images\".format(c)))\n logging.info((\"completed calculating predictions over all {} images\".format(c)))\n\n ############################# SEEN ##############################################\n lab_7186 = lab_7186.cuda()\n prediction_7186 = prediction_7186.cuda()\n temp_7186 = torch.clamp(lab_7186,0,1).sum(1).nonzero().flatten() ## take only the images with positive annotations\n lab_7186 = lab_7186[temp_7186]\n prediction_7186 = prediction_7186[temp_7186]\n\n ## AP ##\n temp_lab_7186=(lab_7186!=0)\n temp_lab_7186 = torch.clamp(temp_lab_7186,0,1)\n mask = temp_lab_7186.sum(0).nonzero().flatten()\n\n map_lab_7186 = lab_7186[:,mask]\n imgs_per_label = torch.clamp(map_lab_7186,0,1).sum(0)\n\n map_prediction_7186 = prediction_7186[:,mask]\n\n ap_7186 = util.compute_AP(map_prediction_7186, map_lab_7186)\n print('SEEN AP on 4728 classes',torch.mean(ap_7186).item())\n logging.info('SEEN AP on 4728 classes:%.4f',torch.mean(ap_7186).item())\n\n weighted_map_7186 = (imgs_per_label.float() * ap_7186).sum()/imgs_per_label.sum().float()\n print('WEIGHTED SEEN AP on 4728 classes',weighted_map_7186.item())\n logging.info('WEIGHTED SEEN AP on 4728 classes:%.4f',weighted_map_7186.item())\n\n del weighted_map_7186, ap_7186, imgs_per_label, temp_lab_7186, lab_7186, prediction_7186, mask\n torch.cuda.empty_cache()\n\n logits_7186_20 = map_prediction_7186.clone()\n\n F1_20_7186,P_20_7186,R_20_7186 = util.compute_F1(map_prediction_7186, map_lab_7186, 'overall', k_val=20)\n print('g_k=20',torch.mean(F1_20_7186).item(), torch.mean(P_20_7186).item(), torch.mean(R_20_7186).item())\n logging.info('g_k=20:%.4f,%.4f,%.4f',torch.mean(F1_20_7186).item(), torch.mean(P_20_7186).item(), torch.mean(R_20_7186).item())\n\n del map_prediction_7186\n torch.cuda.empty_cache()\n\n logits_7186_5 = logits_7186_20.clone()\n\n F1_10_7186,P_10_7186,R_10_7186 = util.compute_F1(logits_7186_20, map_lab_7186, 'overall', k_val=10)\n print('g_k=10',torch.mean(F1_10_7186).item(), torch.mean(P_10_7186).item(), torch.mean(R_10_7186).item())\n logging.info('g_k=10:%.4f,%.4f,%.4f',torch.mean(F1_10_7186).item(), torch.mean(P_10_7186).item(), torch.mean(R_10_7186).item())\n\n del logits_7186_20\n torch.cuda.empty_cache()\n\n logits_7186_1 = logits_7186_5.clone()\n\n F1_5_7186,P_5_7186,R_5_7186 = util.compute_F1(logits_7186_5, map_lab_7186, 'overall', k_val=5)\n print('g_k=5',torch.mean(F1_5_7186).item(), torch.mean(P_5_7186).item(), torch.mean(R_5_7186).item())\n logging.info('g_k=5:%.4f,%.4f,%.4f',torch.mean(F1_5_7186).item(), torch.mean(P_5_7186).item(), torch.mean(R_5_7186).item())\n\n\n del logits_7186_5\n torch.cuda.empty_cache()\n\n F1_1_7186,P_1_7186,R_1_7186 = util.compute_F1(logits_7186_1, map_lab_7186, 'overall', k_val=1)\n print('g_k=1',torch.mean(F1_1_7186).item(), torch.mean(P_1_7186).item(), torch.mean(R_1_7186).item())\n logging.info('g_k=1:%.4f,%.4f,%.4f',torch.mean(F1_1_7186).item(), torch.mean(P_1_7186).item(), torch.mean(R_1_7186).item())\n\n del logits_7186_1\n torch.cuda.empty_cache()\n\n del map_lab_7186, F1_20_7186, P_20_7186, R_20_7186, F1_10_7186, P_10_7186, R_10_7186, F1_5_7186, P_5_7186, R_5_7186, F1_1_7186, P_1_7186, R_1_7186\n torch.cuda.empty_cache()\n \n ################################################################################################################################\n ############################# ZSL ##############ß################################\n prediction_400 = prediction_400.cuda()\n lab_400 = lab_400.cuda()\n\n temp_400 = torch.clamp(lab_400,0,1).sum(1).nonzero().flatten() ## take only the images with positive annotations\n lab_400 = lab_400[temp_400]\n prediction_400 = prediction_400[temp_400]\n\n logits_400_20 = prediction_400.clone()\n logits_400_3 = prediction_400.clone()\n logits_400_1 = prediction_400.clone()\n\n\n ap_400 = util.compute_AP(prediction_400, lab_400)\n print('ZSL AP',torch.mean(ap_400).item())\n logging.info('ZSL AP: %.4f',torch.mean(ap_400).item())\n\n imgs_per_label = torch.clamp(lab_400,0,1).sum(0)\n weighted_map_400 = (imgs_per_label.float() * ap_400).sum()/imgs_per_label.sum().float()\n\n print('WEIGHTED ZSL AP',torch.mean(weighted_map_400).item())\n logging.info('WEIGHTED ZSL AP: %.4f',torch.mean(weighted_map_400).item())\n\n F1_20_400,P_20_400,R_20_400 = util.compute_F1(logits_400_20, lab_400, 'overall', k_val=20)\n print('k=20',torch.mean(F1_20_400).item(),torch.mean(P_20_400).item(),torch.mean(R_20_400).item())\n logging.info('k=20: %.4f,%.4f,%.4f',torch.mean(F1_20_400).item(),torch.mean(P_20_400).item(),torch.mean(R_20_400).item())\n\n del logits_400_20, temp_400\n torch.cuda.empty_cache()\n\n F1_10_400,P_10_400,R_10_400 = util.compute_F1(prediction_400, lab_400, 'overall', k_val=10)\n print('k=10',torch.mean(F1_10_400).item(),torch.mean(P_10_400).item(),torch.mean(R_10_400).item())\n logging.info('k=10: %.4f,%.4f,%.4f',torch.mean(F1_10_400).item(),torch.mean(P_10_400).item(),torch.mean(R_10_400).item())\n\n del prediction_400\n torch.cuda.empty_cache()\n\n F1_3_400,P_3_400,R_3_400 = util.compute_F1(logits_400_3, lab_400, 'overall', k_val=3)\n print('k=3',torch.mean(F1_3_400).item(),torch.mean(P_3_400).item(),torch.mean(R_3_400).item())\n logging.info('k=3: %.4f,%.4f,%.4f',torch.mean(F1_3_400).item(),torch.mean(P_3_400).item(),torch.mean(R_3_400).item())\n\n del logits_400_3\n torch.cuda.empty_cache()\n\n F1_1_400,P_1_400,R_1_400 = util.compute_F1(logits_400_1, lab_400, 'overall', k_val=1)\n print('k=1',torch.mean(F1_1_400).item(),torch.mean(P_1_400).item(),torch.mean(R_1_400).item())\n logging.info('k=1: %.4f,%.4f,%.4f',torch.mean(F1_1_400).item(),torch.mean(P_1_400).item(),torch.mean(R_1_400).item())\n\n del logits_400_1\n torch.cuda.empty_cache()\n\n del features, lab_400\n torch.cuda.empty_cache()\n\n ############################# GZSL ##############################################\n lab_7586 = lab_7586.cuda()\n prediction_7586 = prediction_7586.cuda()\n\n temp_7586 = torch.clamp(lab_7586,0,1).sum(1).nonzero().flatten() ## take only the images with positive annotations\n lab_7586 = lab_7586[temp_7586]\n prediction_7586 = prediction_7586[temp_7586]\n\n ## AP ##\n temp_lab_7586=(lab_7586!=0)\n temp_lab_7586 = torch.clamp(temp_lab_7586,0,1)\n mask = temp_lab_7586.sum(0).nonzero().flatten()\n # imgs_per_label = temp_lab_7586.sum(0)\n\n map_lab_7586 = lab_7586[:,mask]\n imgs_per_label = torch.clamp(map_lab_7586,0,1).sum(0)\n\n map_prediction_7586 = prediction_7586[:,mask]\n\n ap_7586 = util.compute_AP(map_prediction_7586, map_lab_7586)\n print('GZSL AP on 4728+400 classes',torch.mean(ap_7586).item())\n logging.info('GZSL AP on 4728+400 classes:%.4f',torch.mean(ap_7586).item())\n\n weighted_map_7586 = (imgs_per_label.float() * ap_7586).sum()/imgs_per_label.sum().float()\n print('WEIGHTED GZSL AP on 4728+400 classes',weighted_map_7586.item())\n logging.info('WEIGHTED GZSL AP on 4728+400 classes:%.4f',weighted_map_7586.item())\n\n del weighted_map_7586, ap_7586, imgs_per_label, map_lab_7586, map_prediction_7586, temp_lab_7586, mask\n torch.cuda.empty_cache()\n\n logits_7586_20 = prediction_7586.clone()\n\n F1_20_7586,P_20_7586,R_20_7586 = util.compute_F1(prediction_7586, lab_7586, 'overall', k_val=20)\n print('g_k=20',torch.mean(F1_20_7586).item(), torch.mean(P_20_7586).item(), torch.mean(R_20_7586).item())\n logging.info('g_k=20:%.4f,%.4f,%.4f',torch.mean(F1_20_7586).item(), torch.mean(P_20_7586).item(), torch.mean(R_20_7586).item())\n\n del prediction_7586\n torch.cuda.empty_cache()\n\n logits_7586_5 = logits_7586_20.clone()\n\n F1_10_7586,P_10_7586,R_10_7586 = util.compute_F1(logits_7586_20, lab_7586, 'overall', k_val=10)\n print('g_k=10',torch.mean(F1_10_7586).item(), torch.mean(P_10_7586).item(), torch.mean(R_10_7586).item())\n logging.info('g_k=10:%.4f,%.4f,%.4f',torch.mean(F1_10_7586).item(), torch.mean(P_10_7586).item(), torch.mean(R_10_7586).item())\n\n del logits_7586_20\n torch.cuda.empty_cache()\n\n logits_7586_1 = logits_7586_5.clone()\n\n F1_5_7586,P_5_7586,R_5_7586 = util.compute_F1(logits_7586_5, lab_7586, 'overall', k_val=5)\n print('g_k=5',torch.mean(F1_5_7586).item(), torch.mean(P_5_7586).item(), torch.mean(R_5_7586).item())\n logging.info('g_k=5:%.4f,%.4f,%.4f',torch.mean(F1_5_7586).item(), torch.mean(P_5_7586).item(), torch.mean(R_5_7586).item())\n\n del logits_7586_5\n torch.cuda.empty_cache()\n\n F1_1_7586,P_1_7586,R_1_7586 = util.compute_F1(logits_7586_1, lab_7586, 'overall', k_val=1)\n print('g_k=1',torch.mean(F1_1_7586).item(), torch.mean(P_1_7586).item(), torch.mean(R_1_7586).item())\n logging.info('g_k=1:%.4f,%.4f,%.4f',torch.mean(F1_1_7586).item(), torch.mean(P_1_7586).item(), torch.mean(R_1_7586).item())\n\n del logits_7586_1\n torch.cuda.empty_cache()\n\n del lab_7586, F1_20_7586, P_20_7586, R_20_7586, F1_10_7586, P_10_7586, R_10_7586, F1_5_7586, P_5_7586, R_5_7586, F1_1_7586, P_1_7586, R_1_7586\n torch.cuda.empty_cache()\n\n print(\"------------------------------------------------------------------\")\n print(\"TEST Time: {:.4f}\".format(time.time()-test_start_time))\n print(\"------------------------------------------------------------------\")\n\n logging.info(\"------------------------------------------------------------------\")\n logging.info(\"TEST Time: {:.4f}\".format(time.time()-test_start_time))\n logging.info(\"------------------------------------------------------------------\")\n","repo_name":"akshitac8/BiAM","sub_path":"evaluate_openimages.py","file_name":"evaluate_openimages.py","file_ext":"py","file_size_in_byte":14831,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"46"} +{"seq_id":"34593769675","text":"from django import forms\nfrom django.forms import ModelForm, SplitDateTimeField, widgets\nfrom django.utils.safestring import mark_safe\nfrom django.utils.encoding import smart_unicode\nfrom django.conf import settings\n\nfrom lg.models import LivingGroup\nfrom recaptcha.client import captcha\n\nclass ReCaptcha(widgets.Widget):\n recaptcha_challenge_name = 'recaptcha_challenge_field'\n recaptcha_response_name = 'recaptcha_response_field'\n\n def render(self, name, value, attrs=None):\n return mark_safe(u'%s' % captcha.displayhtml(settings.RECAPTCHA_PUBLIC_KEY))\n\n def value_from_datadict(self, data, files, name):\n return [data.get(self.recaptcha_challenge_name, None), \n data.get(self.recaptcha_response_name, None)]\n\nclass ReCaptchaField(forms.CharField):\n default_error_messages = {\n 'captcha_invalid': (u'Invalid captcha')\n }\n\n def __init__(self, *args, **kwargs):\n self.widget = ReCaptcha\n self.required = True\n super(ReCaptchaField, self).__init__(*args, **kwargs)\n\n def clean(self, values):\n super(ReCaptchaField, self).clean(values[1])\n recaptcha_challenge_value = smart_unicode(values[0])\n recaptcha_response_value = smart_unicode(values[1])\n check_captcha = captcha.submit(recaptcha_challenge_value, recaptcha_response_value, settings.RECAPTCHA_PRIVATE_KEY, {})\n if not check_captcha.is_valid:\n raise forms.util.ValidationError(self.error_messages['captcha_invalid'])\n return values[0]\n \n \nclass LivingGroupForm(ModelForm):\n error_css_class = 'error'\n required_css_class = 'required'\n class Meta:\n model = LivingGroup\n widgets = {\n 'lg_name' : forms.TextInput( attrs = {'placeholder' : 'Example: Tau Nu Phi', 'size' : '30'}),\n 'rep_name' : forms.TextInput( attrs = {'size' : '30'}),\n 'rep_email' : forms.TextInput( attrs = {'size' : '30'}),\n 'rep_phone' : forms.TextInput( attrs = {'size' : '30'}),\n 'first_choice' : forms.SplitDateTimeWidget (attrs = {'size' : '15'}, date_format = '%m/%d/%Y', time_format = '%I:%M%p'),\n 'second_choice' : forms.SplitDateTimeWidget (attrs = {'size' : '15'}, date_format = '%m/%d/%Y', time_format = '%I:%M%p'),\n 'third_choice' : forms.SplitDateTimeWidget (attrs = {'size' : '15'}, date_format = '%m/%d/%Y', time_format = '%I:%M%p'),\n 'alternative_choice': forms.Textarea( attrs = {'placeholder' : 'Example: We have study breaks on Thursday nights at 9pm.', 'cols': '60', 'rows':'4'}),\n 'location' : forms.Textarea( attrs = {'placeholder' : 'Example: Outside our house on 84 Massachusetts Ave.', 'cols': '60', 'rows':'4'}),\n 'comments' : forms.Textarea( attrs = {'placeholder' : 'Example: The outlet might far away, so bring a long extension cable.', 'cols': '60', 'rows':'4'}),\n 'captcha' : ReCaptcha()\n }\n exclude = ('year',)\n \n first_choice = SplitDateTimeField(input_date_formats = ['%m/%d/%Y'], input_time_formats = ['%I:%M%p'])\n second_choice = SplitDateTimeField(input_date_formats = ['%m/%d/%Y'], input_time_formats = ['%I:%M%p'])\n third_choice = SplitDateTimeField(input_date_formats = ['%m/%d/%Y'], input_time_formats = ['%I:%M%p'])\n captcha = ReCaptchaField();\n","repo_name":"tnq/grogosite","sub_path":"lg/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3475,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"46"} +{"seq_id":"23449815217","text":"import wrapt\n\nfrom aws_xray_sdk.core import xray_recorder\nfrom aws_xray_sdk.core.models import http\nfrom aws_xray_sdk.ext.util import inject_trace_header, strip_url, get_hostname\n\n\ndef patch():\n\n wrapt.wrap_function_wrapper(\n 'requests',\n 'Session.request',\n _xray_traced_requests\n )\n\n wrapt.wrap_function_wrapper(\n 'requests',\n 'Session.prepare_request',\n _inject_header\n )\n\n\ndef _xray_traced_requests(wrapped, instance, args, kwargs):\n\n url = kwargs.get('url') or args[1]\n\n return xray_recorder.record_subsegment(\n wrapped, instance, args, kwargs,\n name=get_hostname(url),\n namespace='remote',\n meta_processor=requests_processor,\n )\n\n\ndef _inject_header(wrapped, instance, args, kwargs):\n request = args[0]\n headers = getattr(request, 'headers', {})\n inject_trace_header(headers, xray_recorder.current_subsegment())\n setattr(request, 'headers', headers)\n\n return wrapped(*args, **kwargs)\n\n\ndef requests_processor(wrapped, instance, args, kwargs,\n return_value, exception, subsegment, stack):\n\n method = kwargs.get('method') or args[0]\n url = kwargs.get('url') or args[1]\n\n subsegment.put_http_meta(http.METHOD, method)\n subsegment.put_http_meta(http.URL, strip_url(url))\n\n if return_value is not None:\n subsegment.put_http_meta(http.STATUS, return_value.status_code)\n elif exception:\n subsegment.add_exception(exception, stack)\n","repo_name":"aws/aws-xray-sdk-python","sub_path":"aws_xray_sdk/ext/requests/patch.py","file_name":"patch.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":305,"dataset":"github-code","pt":"46"} +{"seq_id":"44030900390","text":"#!/usr/bin/python\n\ndef Fibo(n):\n if n == 0:\n return 0\n if n == 1:\n return 1\n return Fibo(n-1)+Fibo(n-2)\n\nprint(Fibo(7))\n'''\nl1 = []\nfor i in range(11):\n x = Fibo(i)\n l1.append(x)\nprint l1\n'''\nprint( [Fibo(x) for x in range(11)])\n","repo_name":"jeetendrabhattad/Python","sub_path":"basics/list_comprehensions_fibo.py","file_name":"list_comprehensions_fibo.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"46"} +{"seq_id":"23976592620","text":"#%%\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nfrom net import Net\n#%%\n# Hyper Parameters\nBATCH_SIZE = 32\nLR = 0.01\nEPSILON = 0.9 # greedy policy\nGAMMA = 0.9 # alpha\nTARGET_REPLACE_ITER = 100 # target update frequency\nMEMORY_CAPACITY = 2000\n\n# using GPU\nprint(\"GPU is ->\",torch.cuda.is_available())\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(torch.cuda.get_device_name(0))\n\nclass DDQN:\n def __init__(self,N_STATES,N_ACTIONS,ENV_A_SHAPE):\n self.eval_net, self.target_net = Net(N_STATES,N_ACTIONS).to(device), Net(N_STATES,N_ACTIONS).to(device)\n #self.eval_net.cuda()\n #self.target_net.cuda()\n \n self.learn_step_counter = 0 # for target update\n self.memory_counter = 0 # for storing memory\n self.memory = np.zeros((MEMORY_CAPACITY, N_STATES*2+2))\n self.optimizer = torch.optim.Adam(self.eval_net.parameters(), lr=LR)\n self.loss_func = nn.MSELoss()\n self.N_STATES = N_STATES\n self.N_ACTIONS = N_ACTIONS\n self.ENV_A_SHAPE = ENV_A_SHAPE\n def choose_action(self,x):\n x = torch.unsqueeze(torch.FloatTensor(x),0).to(device) # input data to tensor\n if np.random.uniform() < EPSILON:\n action_value = self.eval_net.forward(x)\n action = torch.max(action_value, 1)[1].data.cpu().numpy()\n action = action[0] if self.ENV_A_SHAPE == 0 else action.reshape(self.ENV_A_SHAPE) \n else:\n action = np.random.randint(0, self.N_ACTIONS)\n action = action if self.ENV_A_SHAPE == 0 else action.reshape(self.ENV_A_SHAPE)\n return action\n def store_transition(self,s,a,r,s_):\n transition = np.hstack((s, [a,r],s_))\n index = self.memory_counter % MEMORY_CAPACITY\n self.memory[index,:] = transition\n self.memory_counter += 1\n def learn(self):\n # target parameter update\n if self.learn_step_counter % TARGET_REPLACE_ITER == 0:\n self.target_net.load_state_dict(self.eval_net.state_dict())\n self.learn_step_counter +=1\n \n # sample batch transitions\n sample_index = np.random.choice(MEMORY_CAPACITY, BATCH_SIZE)\n b_memory = self.memory[sample_index, :]\n # need using cuda\n b_s = torch.FloatTensor(b_memory[:, :self.N_STATES]).cuda() # 0..3\n b_a = torch.LongTensor(b_memory[:, self.N_STATES:self.N_STATES+1].astype(int)).cuda() #4\n b_r = torch.FloatTensor(b_memory[:, self.N_STATES+1:self.N_STATES+2]).cuda() #5\n b_s_ = torch.FloatTensor(b_memory[:, -self.N_STATES:]).cuda() #6..9\n '''\n print('b_s:',b_s)\n print('b_a:',b_a)\n print('b_r:',b_r)\n print('b_s_:',b_s_)\n '''\n # q_eval w.r.t the action in experience\n q_eval = self.eval_net(b_s).gather(1, b_a) # shape (batch, 1)\n q_next = self.target_net(b_s_).detach() # detach from graph, don't backpropagate\n q_target = b_r + GAMMA * q_next.max(1)[0].view(BATCH_SIZE, 1) # shape (batch, 1)\n loss = self.loss_func(q_eval, q_target)\n '''\n print('q_eval:',q_eval)\n print('q_next:',q_next)\n print(q_next.max(1)[0].view(BATCH_SIZE, 1))\n print('q_target:',q_target)\n print('loss:',loss)\n '''\n '''\n print('bs:',b_s)\n print('eval_net(b_s):',self.eval_net(b_s))\n print('eval_net(b_s).gather(1, b_a):',self.eval_net(b_s).gather(1, b_a))\n '''\n \n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n#%%\n","repo_name":"RozenAstrayChen/Reinforcement-practice","sub_path":"CartPole/Torch_DQN/double_dqn.py","file_name":"double_dqn.py","file_ext":"py","file_size_in_byte":3592,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"46"} +{"seq_id":"13560148577","text":"# -*- coding: utf-8 -*-\n# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: light\n# format_version: '1.5'\n# jupytext_version: 1.3.4\n# kernelspec:\n# display_name: Python [conda env:root] *\n# language: python\n# name: conda-root-py\n# ---\n\nimport pandas as pd\nimport plotly.express as px\nfrom sklearn.preprocessing import KBinsDiscretizer\n\n# Load data\npremium = pd.read_json('./data/BASE A/premium_students.json')\npremium.head()\n\n# Check nulls\npremium.isnull().mean()\n\n# +\n# Data prep\npremium.loc[:, 'RegisteredDate'] = pd.to_datetime(premium['RegisteredDate'], infer_datetime_format=True)\npremium.loc[:, 'SubscriptionDate'] = pd.to_datetime(premium['SubscriptionDate'], infer_datetime_format=True)\n\npremium.loc[:, 'days_until_subscription'] = (premium['SubscriptionDate'] - premium['RegisteredDate']).dt.days\n\npremium.loc[:, 'subscription_date'] = (premium['SubscriptionDate']).dt.date\npremium.loc[:, 'registration_date'] = (premium['RegisteredDate']).dt.date\n\npremium.head()\n# -\n\nfig = px.histogram(premium, x=['registration_date', 'subscription_date'], facet_col='variable')\n# fig.for_each_annotation(lambda a: a.update(text=a.text.split('=')[1]))\nfig.update_layout(showlegend=False,\n yaxis_title='Quantidade de usuários',\n title='Cadastro e conversão, no período'\n )\nfig.update_xaxes(title='Período')\nplot(fig)\n\n\ndef plot(fig):\n fig.update_layout(\n font=dict(family=\"Roboto\", size=16),\n template='plotly_white'\n )\n colors = ['#250541', '#F93D55']\n fig.show()\n\n\n# +\ndf = premium\\\n .groupby(['days_until_subscription'], as_index=False)\\\n .agg({'StudentId':'nunique'})\n\nfig = px.bar(df, x='days_until_subscription', y='StudentId')\nfig.update_layout(\n xaxis_title='Dias entre cadastro e primeira compra',\n yaxis_title='Quantidade de usuários',\n title='Distribuição do tempo até conversão'\n)\nfig.update_xaxes(tickmode = 'linear',\n dtick = 30\n )\nplot(fig)\n\n# +\npremium.loc[premium['days_until_subscription'] == 0, 'class'] = '0 dias'\npremium.loc[premium['days_until_subscription'].between(1, 30), 'class'] = '1 a 30 dias'\npremium.loc[premium['days_until_subscription'] > 30, 'class'] = '+30 dias'\n\npremium['class'].value_counts()\n\n# +\ndf = premium\\\n .groupby(['class'], as_index=False)\\\n .agg({'StudentId':'count', 'days_until_subscription':'mean'})\\\n .sort_values(by='days_until_subscription')\n\ndf.loc[:,'total'] = df['StudentId'].sum()\ndf.loc[:,'percentage'] = 100*df['StudentId']/df['total']\n\nfig = px.bar(df, x='class', y='percentage')\nfig.update_xaxes(type='category', title='Categoria')\nfig.update_yaxes(tickvals=[], title='Percentual (%)')\nfig.update_traces(texttemplate='%{y:.1f}%', textposition='outside', )\nfig.update_layout(\n title='Distribuição dos usuários, por categoria'\n)\nplot(fig)\n# -\n\n\n","repo_name":"adautobraz/case_passei_direto","sub_path":"scripts/Case_Parte_1.py","file_name":"Case_Parte_1.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"16221449050","text":"import sys\n\nfrom Login.loginUI import Ui_Form\nfrom MainGUI.medicWorldGUI import Ui_MainGUI\nfrom PatientForm.newPatientGUI import Ui_NewPatient\nimport PyQt5.QtWidgets as qtw\nimport PyQt5.QtGui as qtg\nimport PyQt5.QtCore as qtc\n\n\n\n# Main class of the GUI that inherits the QWidget object and all its properties\n\nclass MainPage(qtw.QWidget):\n\n # Constructor method of the class\n def __init__(self):\n # call the constructor of the superclass QWidget\n super().__init__()\n\n # Create the instances of the UIs\n self.mainUI = Ui_MainGUI()\n self.loginUI = Ui_Form()\n\n self.initMainPage()\n\n # Initialize the login UIloginUI\n # self.loginUI.setupUi(self)\n # self.loginPage()\n\n self.show()\n\n # Method to connect all the signals of the Login Screen\n def loginPage(self):\n self.loginUI.loginbutton.clicked.connect(self.authenticate)\n\n # Method to make the authentication of the user for the login\n # will implement database authentication\n def authenticate(self):\n username = self.loginUI.username.text()\n password = self.loginUI.password.text()\n if username == \"admin\" and password == \"admin\":\n # for the purpose of this version after the credentials' username:admin password: admin\n # the app initializes the main GUI\n self.initMainPage()\n\n # Method to create the main GUI of the application\n def initMainPage(self):\n # Initialize the UI\n self.mainUI.setupUi(self)\n # Connect the stackedWidget in this case the left dashboard with the respective screens\n self.mainUI.listWidget.currentRowChanged.connect(self.display)\n self.mainUI.exitButton_2.clicked.connect(self.quitApp)\n # Init timers and datetimes\n self.startTimers()\n self.connectButtons()\n\n def connectButtons(self):\n self.loadSuppliesButtons()\n self.mainUI.newPatientButton.clicked.connect(self.openNewPatient)\n\n def openNewPatient(self):\n self.patientWindow = qtw.QMainWindow()\n self.patientFormGUI = Ui_NewPatient()\n self.patientFormGUI.setupUi(self.patientWindow)\n self.patientFormGUI.cancelPatientButon.clicked.connect(self.patientWindow.close)\n self.patientWindow.show()\n\n def startTimers(self):\n # Create a Qtimer object that updates every 1 sec and connect it with the method showTime()\n self.timer = qtc.QTimer()\n self.timer.timeout.connect(self.showTime)\n self.timer.start(1000)\n\n # method that gets the current datetime for the top bar and the Dashboard screen\n def showTime(self):\n current_datetime = qtc.QDateTime.currentDateTime()\n topBarDateTime = current_datetime.toString(\"hh:mm:ss dddd MMMM yy \")\n mainPageDate = current_datetime.toString(\"dddd dd, MMMM\")\n self.mainUI.topDateTime_2.setText(topBarDateTime)\n self.mainUI.dateLabel.setText(mainPageDate)\n\n def loadSuppliesButtons(self):\n drugCategories = [\"Analgesics\", \"Anticonvulsants\", \"Corticosteroids\", \"Antacids\", \"Antiemetics\", \"Laxatives\", \"Antiarrhythimcs\", \"Anti-Inflammatories\",\n \"Sedatives\", \"Antibacterials\", \"Barbiturates\", \"Sleeping-Drugs\", \"Antibiotics\", \"Bronchodilators\", \"Tranquilizers\" ]\n drugCol = [2,4,6]\n spacerCol = [1,3,5]\n self.SuppliesButtons = []\n drug =0\n for j in range(5):\n for i in range(3):\n hspacer = qtw.QSpacerItem(20, 10, qtw.QSizePolicy.Fixed)\n button = qtw.QPushButton(drugCategories[drug])\n button.setStyleSheet(\"\\n\"\n \"font-family: 'Roboto';\\n\"\n \"font-style: normal;\\n\"\n \"font-weight: 600;\\n\"\n \"font-size: 32px;\\n\"\n \"line-height: 38px;\\n\"\n \"text-align: center;\\n\"\n \"border: 0px;\\n\"\n \"border-radius:10px;\\n\"\n \"background: #FFFFFF;\\n\"\n \"color: #1E2F97;\\n\"\n \"\\n\")\n drug += 1\n button.setSizePolicy(qtw.QSizePolicy.Fixed,qtw.QSizePolicy.Fixed)\n button.setMinimumSize(330,108)\n self.mainUI.suppliesLayout.addItem(hspacer,j,spacerCol[i])\n self.mainUI.suppliesLayout.addWidget(button, j, drugCol[i] )\n\n\n # method responsible to display the correct screen when the user interacts with the left dashboard\n def display(self, i):\n self.mainUI.stackedWidget.setCurrentIndex(i)\n\n def quitApp(self):\n sys.exit()\n\n\nif __name__ == '__main__':\n app = qtw.QApplication(sys.argv)\n mw = MainPage()\n app.exec_()\n","repo_name":"mstephanidhs/Software-Engineering","sub_path":"3rd Assignment/Project-Code-v0.2/MainApp/mainApp.py","file_name":"mainApp.py","file_ext":"py","file_size_in_byte":4913,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"46"} +{"seq_id":"25348688902","text":"import numpy as np\nimport scipy.optimize as op\nimport csv\nfrom f1score_calc import f1score_calc\nfrom predict import predict\n\nNUM_OF_FEATURES = 3\n\ndef write_labels():\n path = '../data/'\n myfile = open( path +\"ISIC2018_Task3_Training_GroundTruth.csv\", \"r\")\n reader = csv.reader(myfile)\n \n t = []\n y = []\n data = []\n c = 0\n for line in reader:\n c+= 1\n if c == 1:\n continue\n y = 0\n if float(line[1]) == 1 or float(line[3]) == 1 or float(line[4]) == 1:\n y = 1\n \n line.append(y)\n data.append(line)\n\n print(data)\n myfile2 = open('test_data.csv', 'w')\n with myfile:\n writer = csv.writer(myfile2)\n writer.writerows(data) \n \n print(\"Writing complete\") \n\ndef write_columns():\n path = '../data/TRAINING_DATA/train_data.csv'\n myfile = open( path, \"r\")\n reader = csv.reader(myfile)\n \n t = []\n y = []\n data = []\n c = 0\n for line in reader:\n data = np.append(data, line)\n \n print(data.shape)\n\n path = '../data/TRAINING_DATA/histo_features.csv'\n myfile = open( path, \"r\")\n reader = csv.reader(myfile)\n \n \n X = []\n c = 0\n for line in reader:\n data = np.append(data, line)\n\n data = np.concatenate( ( data, X), axis = 1 )\n print(data.shape)\n myfile2 = open('train_data.csv', 'w')\n with myfile:\n writer = csv.writer(myfile2)\n writer.writerows(data) \n \n print(\"Writing complete\")\n\nwrite_columns()\n","repo_name":"SharathRC/ism-skin-lesions-project","sub_path":"write_columns.py","file_name":"write_columns.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"38591238731","text":"# -*- coding: utf-8 -*-\n# @Author : uhauha2929\n# @Email : ck143302@gmail.com\n\n\ndef add_strings(num1: str, num2: str) -> str:\n \"\"\"给定两个字符串形式的非负整数,返回它们的和\"\"\"\n chars = []\n carry, i, j = 0, len(num1) - 1, len(num2) - 1\n while i >= 0 or j >= 0 or carry:\n if i >= 0:\n carry += ord(num1[i]) - ord('0')\n i -= 1\n if j >= 0:\n carry += ord(num2[j]) - ord('0')\n j -= 1\n chars.insert(0, str(int(carry % 10)))\n carry //= 10\n return ''.join(chars)\n\n\ndef multiply_strings(num1: str, num2: str) -> str:\n \"\"\"给定两个字符串形式的非负整数,返回它们的积\"\"\"\n m, n = len(num1), len(num2)\n if m == 0 or n == 0:\n return '0'\n if num1 == '0' or num2 == '0':\n return '0'\n # 乘积的长度最多为m+n\n ans = [0] * (m + n)\n # 从后往前依次和每一位数相乘\n for i in range(m - 1, -1, -1):\n for j in range(n - 1, -1, -1):\n # 两数第i位和第j位的乘积暂时放到数组的i+j+1位\n ans[i + j + 1] += int(num1[i]) * int(num2[j])\n # 统一处理进位\n for i in range(m + n - 1, 0, -1):\n ans[i - 1] += ans[i] // 10\n ans[i] %= 10\n # ans数组��一位可能位0\n return ''.join(map(str, ans)).lstrip('0')\n\n\ndef check_expr(expr: str):\n \"\"\"检查表达式的合法性,只包含空格数字和英文小括号\n\n 返回值1:括号不匹配 2:异常字符 0:正常\n \"\"\"\n stack = list()\n for char in expr:\n if char.isdigit() or char.isspace() or char in '+-*/':\n continue\n if char == ')':\n if not stack or stack[-1] != '(':\n return 1\n stack.pop()\n elif char == '(':\n stack.append(char)\n else:\n return 2\n return 0 if not stack else 1\n\n\ndef infix2suffix(expr: str) -> str:\n \"\"\"中缀表达式转成后缀表达式(逆波兰表达式 Reverse Polish Notation)\"\"\"\n code = check_expr(expr)\n if code == 1:\n raise ValueError('Invalid bracket.')\n elif code == 2:\n raise ValueError('Invalid character.')\n s1, s2 = [], [] # 两个栈\n p = {'+': 1, '-': 1, '*': 2, '/': 2} # 运算符优先级\n for c in expr:\n if c.isspace():\n continue\n # 遇到操作数时,将其压入S2\n if c.isdigit():\n s2.append(c)\n # 遇到运算符时,比较其与S1栈顶运算符的优先级\n elif c in p:\n while True:\n # 如果S1为空,或栈顶运算符为左括号(,则直接将此运算符入栈\n if not s1 or s1[-1] == '(':\n s1.append(c)\n break\n else:\n # 否则,若优先级比栈顶运算符的高,也将运算符压入S1\n if p[c] > p[s1[-1]]:\n s1.append(c)\n break\n # 否则,将S1栈顶的运算符弹出并压入到S2中\n # 再次循环与S1中新的栈顶运算符相比较\n else:\n s2.append(s1.pop())\n # 遇到括号时\n elif c in '()':\n # 如果是左括号(,则直接压入S1\n if c == '(':\n s1.append(c)\n # 如果是右括号),则依次弹出S1栈顶的运算符,并压入S2\n # 直到遇到左括号为止,此时将这一对括号丢弃\n elif c == ')':\n while True:\n t = s1.pop()\n if t == '(':\n break\n s2.append(t)\n # 将s1剩余的运算符一次加入s2\n while s1:\n s2.append(s1.pop())\n return ''.join(s2)\n\n\ndef calculate(expr: str) -> float:\n \"\"\"字符串表达式计算,支持+-*/()符号\"\"\"\n s = []\n suffix = infix2suffix(expr)\n if not suffix:\n raise ValueError('Empty Reverse Polish Notation.')\n for c in suffix:\n if c.isdigit():\n s.append(c)\n else:\n a = float(s.pop())\n b = float(s.pop())\n if c == '+':\n s.append(a + b)\n elif c == '-':\n s.append(b - a)\n elif c == '*':\n s.append(a * b)\n elif c == '/':\n s.append(b / a)\n return s.pop()\n","repo_name":"uhauha2929/stutils","sub_path":"stutils/string/arithmetic.py","file_name":"arithmetic.py","file_ext":"py","file_size_in_byte":4413,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"31331122474","text":"#!/usr/bin/env python\n\"\"\"\nTests sqs connection methods\n\nUpdate the SQS_CONN_PARAMS to test\n\"\"\"\nimport sys\nimport unittest\nimport logging\nimport warnings\n\nsys.path.insert(0, '..')\nfrom service_clients.aws.sqs_client import SQSClient\n\n\n# Update bucket_name and credentials\nSQS_CONN_PARAMS = {\n 'access_key_id': '',\n 'secret_access_key': '',\n 'aws_region': 'ca-central-1',\n 'queue_url': ''\n}\n\nS3_EVENT_MESSAGE = \\\n '{\"Records\":[{\"eventVersion\":\"2.0\",\"eventSource\":\"aws:s3\",\"awsRegion\":\"ca-central-1\",\"eventTime\":' \\\n '\"2017-11-02T20:46:02.498Z\",\"eventName\":\"ObjectCreated:Put\",\"userIdentity\":{\"principalId\":' \\\n '\"AWS:AIDAJHTJFFPZ6JYIXFBGK\"},\"requestParameters\":{\"sourceIPAddress\":\"54.200.43.31\"},' \\\n '\"responseElements\":{\"x-amz-request-id\":\"9FEAE30337E9E20B\",\"x-amz-id-2\":' \\\n '\"ePCkzMSQgwXGuBUClOGnXto0xgh729x61BY99rS++jkmyjFUVKErNAQzLgBQd6i/VragX4HqoOw=\"},\"s3\":' \\\n '{\"s3SchemaVersion\":\"1.0\",\"configurationId\":\"DeliverToTestProcessor\",\"bucket\":' \\\n '{\"name\":\"ca-central-1-test-bucket\",\"ownerIdentity\":{\"principalId\":\"A1YTN9GI8TG7SZ\"},' \\\n '\"arn\":\"arn:aws:s3:::ca-central-1-test-bucket\"},\"object\":{\"key\":' \\\n '\"home/ftp/1/file.txt-1509655557\",\"size\":674911,' \\\n '\"eTag\":\"939cfcaf3d04deb439927640aa2e0f99\",\"sequencer\":\"0059FB840A5CF6BEB4\"}}}]}'\n\n\nclass TestSQSClient(unittest.TestCase):\n\n def setUp(self):\n \"\"\"Sets up before each test\"\"\"\n logging.debug('setting up')\n self.sqs_client = SQSClient(SQS_CONN_PARAMS, conn_retries=1, msg_wait_seconds=10)\n\n # Silence some of the errors associated with long lived connections\n warnings.filterwarnings(\"ignore\", category=ResourceWarning, message=\"unclosed.*\")\n\n def tearDown(self):\n \"\"\"Tears down after each test\"\"\"\n logging.debug('tearing down')\n\n def shortDescription(self):\n return None\n\n # Test start below\n\n def test_connection1(self):\n conn = self.sqs_client.client\n assert conn\n\n def test_message1(self):\n \"\"\"\n Test sending a message\n \"\"\"\n response = self.sqs_client.send_message('{\"test\":\"this is a test message\"}')\n assert response['ResponseMetadata']['HTTPStatusCode'] == 200\n assert 'MessageId' in response\n\n def test_message2(self):\n \"\"\"\n Test sending a message\n that resembles a s3 event triggered msg to queue\n \"\"\"\n response = self.sqs_message = self.sqs_client.send_message(S3_EVENT_MESSAGE)\n assert response['ResponseMetadata']['HTTPStatusCode'] == 200\n assert 'MessageId' in response\n\n def test_message3(self):\n \"\"\"\n Test receiving a message\n \"\"\"\n messages = self.sqs_client.get_messages(msg_wait_seconds=1)\n assert isinstance(messages, list)\n\n def test_message4(self):\n \"\"\"\n Test deleting a message\n \"\"\"\n self.sqs_message = self.sqs_client.send_message(S3_EVENT_MESSAGE)\n\n msgs = self.sqs_client.get_messages(num_messages=2)\n for msg in msgs:\n assert self.sqs_client.delete_message(msg)\n\n def test_message5(self):\n \"\"\"\n Test deleting a message by handle\n \"\"\"\n self.sqs_message = self.sqs_client.send_message(S3_EVENT_MESSAGE)\n\n msgs = self.sqs_client.get_messages(num_messages=1)\n receipt_handle = msgs[0]['ReceiptHandle']\n assert self.sqs_client.delete_message(receipt_handle=receipt_handle)\n\n # Clean up all messages\n msgs = self.sqs_client.get_messages(msg_wait_seconds=1)\n while msgs:\n msgs = self.sqs_client.get_messages(msg_wait_seconds=1)\n [self.sqs_client.delete_message(msg) for msg in msgs]\n\n def test_message6(self):\n \"\"\"\n Test deleting a invalid msg\n \"\"\"\n with self.assertRaises(KeyError):\n self.sqs_client.delete_message(sqs_message={})\n\n def test_message7(self):\n \"\"\"\n Test deleting a invalid msg\n \"\"\"\n success = self.sqs_client.delete_message(receipt_handle='123abc') # Fails silent if can't find id\n assert success is True\n\n def test_message8(self):\n msgs = self.sqs_client.get_messages(num_messages=2)\n assert isinstance(msgs, list)\n\n\nif __name__ == '__main__':\n unittest.main() # pragma: no cover\n","repo_name":"radzhome/python-service-clients","sub_path":"tests/test_sqs_client.py","file_name":"test_sqs_client.py","file_ext":"py","file_size_in_byte":4371,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"33533514180","text":"import re\n\nfrom linebot import WebhookHandler\nfrom linebot.models import MessageEvent, TextMessage\n\nfrom app.config import LINEBOT_SECRET, CELEBRATING_TARGET\nfrom app.message import send_help_message, send_error_message\nfrom app.message import leaderboard, vote, duckduckgo, etc\n\nhandler = WebhookHandler(LINEBOT_SECRET)\n\n\n@handler.add(MessageEvent, message=TextMessage)\ndef message(line_event):\n if line_event.source.type != \"group\":\n return\n p1 = re.compile(CELEBRATING_TARGET)\n p2 = re.compile(\"생일\")\n text = line_event.message.text\n p3 = re.compile(r\"^!(\\S+)(| .+)$\")\n if p1.search(text) and p2.search(text):\n leaderboard.celebrating_birthday(line_event)\n elif p3.match(text):\n command = p3.match(text)[1]\n args = p3.match(text)[2].lstrip()\n if command in [\"명령어\"]:\n send_help_message(line_event, args)\n elif command in [\"순위\"]:\n leaderboard.send_leaderboard(line_event)\n elif command in [\"투표시작\"]:\n vote.create_vote(line_event, args)\n elif command in [\"투표\"]:\n vote.answer_vote(line_event, args)\n elif command in [\"투표항목\"]:\n vote.add_item(line_event, args)\n elif command in [\"투표종료\"]:\n vote.close_vote(line_event)\n elif command in [\"선택장애\"]:\n etc.select_random_item(line_event, args)\n elif command in [\"이미지\"]:\n duckduckgo.send_image_search_message(line_event, args)\n else:\n send_error_message(line_event, command)\n else:\n pass\n","repo_name":"FelisCatusKR/LineBot-FunFeatures","sub_path":"src/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"21792527738","text":"from numpy import *\nfrom math import *\n\ndef loadDataSet(fileName):\n dataSet = []\n fr = open(fileName)\n for line in fr.readlines():\n curLine = line.strip().split('\\t')\n fltLine = list(map(float, curLine))\n dataSet.append(fltLine)\n return dataSet\n\n# 计算两个向量的欧式距离\ndef distEclud(vecA, vecB):\n return sqrt(sum(power((vecA - vecB), 2)))\n\n'''\n 随机构建初始质心\n 位给定数据集构建一个包含k个随机质心的集合\n'''\ndef randCent(dataSet, k):\n dataMat = mat(dataSet)\n n = shape(dataMat)[1] #dataSet的列数\n centroids = mat(zeros((k, n))) # 创建k行n列的矩阵,centroids存放簇中心\n for j in range(n):\n minJ = min(dataMat[:, j]) # 第j列的最小值\n rangeJ = float(max(dataMat[:, j]) - minJ)\n centroids[:, j] = minJ + rangeJ * random.rand(k, 1)\n return centroids\n\ndef kMeans(dataSet, k, distMeans = distEclud, createCent = randCent):\n dataMat = mat(dataSet)\n m = shape(dataMat)[0]\n clusterAssment = mat(zeros((m, 2))) # 创建一个m行2列的矩阵,第一列存放索引值,第二列存放误差(距离),误差用来评价聚类效果\n centroids = createCent(dataMat, k) # 随机创建k个质点\n clusterChanged = True # 标志变量,若为true则继续迭代\n while clusterChanged:\n clusterChanged = False\n for i in range(m): #遍历每个数据\n # 设置两个变量,分别存放数据点到质心的距离,及数据点属于哪个质心\n minDist = inf\n minIndex = -1\n for j in range(k): #遍历每个质心\n distJI = distMeans(centroids[j, :], dataMat[i, :]) # 计算距离\n if distJI < minDist: # 将数据归为最近的质心\n minDist = distJI\n minIndex = j\n if clusterAssment[i, 0] != minIndex: # 簇分配结果发生改变,更新标志\n clusterChanged = True\n clusterAssment[i, :] = minIndex, minDist ** 2\n # print(centroids)\n for cent in range(k): # 更新质心\n ptsInClust = dataMat[nonzero(clusterAssment[:, 0].A == cent)[0]] # 通过数组过滤来获得给定簇的所有点\n centroids[cent, :] = mean(ptsInClust, axis=0) # 计算所有点的均值,选项axis=0表示沿矩阵的列方向进行均值计算\n return centroids, clusterAssment\n\n# 二分K-均值算法\ndef biKmeans(dataSet, k, distMeans = distEclud):\n dataMat = mat(dataSet)\n m = shape(dataMat)[0]\n clusterAssment = mat(zeros((m, 2)))\n centroid0 = mean(dataMat, axis=0).tolist()[0]\n cenList = [centroid0]\n for j in range(m):\n clusterAssment[j, 1] = distMeans(mat(centroid0), dataMat[j,: ]) ** 2 #计算所有点的误差平方,选项axis=0表示沿矩阵的列方向进行均值计算\n while (len(cenList) < k): # 当簇小于数目k时\n lowestSSE = inf\n for i in range(len(cenList)):\n # 得到dataMat中行号与clusterAssment中所属的中心编号为i的行号对应的子集数据\n ptsInCurrCluster = dataMat[nonzero(clusterAssment[:, 0].A == i)[0], :]\n # 在给定的簇上进行K-均值聚类,k值为2\n centroidMat, splitClusAss = kMeans(ptsInCurrCluster, 2)\n # 划分后的误差平方和\n sseSplit = sum(splitClusAss[:, 1])\n # 剩余的误差平方和\n sseNotSplit = sum(clusterAssment[nonzero(clusterAssment[:, 0].A != i)[0], 1])\n print(\"sseSplit and notSplit: \", sseSplit, sseNotSplit)\n if ((sseSplit + sseNotSplit) < lowestSSE):\n # 选择使得误差最小的那个簇进行划分\n bestCentToSplit = i\n bestNewCents = centroidMat\n bestClustAss = splitClusAss.copy()\n lowestSSE = sseSplit + sseNotSplit\n # 将需要分割的聚类中心下的点进行划分 # 新增的聚类中心编号为len(centList)\n # 将新分出来的两个簇的标号一个沿用它父亲的标号,一个用簇的总数来标号。\n bestClustAss[nonzero(bestClustAss[:, 0].A == 1)[0], 0] = len(cenList)\n bestClustAss[nonzero(bestClustAss[:, 0].A == 0)[0], 0] = bestCentToSplit\n print(\"The bestCentToSplit is: \", bestCentToSplit)\n print(\"The len of bestClustAss is: \", len(bestClustAss))\n print(\"bestNewCents \", bestNewCents)\n\n\n cenList[bestCentToSplit] = bestNewCents[0,:] # 将第一个子簇的质心放在父亲质心的原位置\n cenList.append(bestNewCents[1,:]) # 将第二个子簇的质心添加在末尾\n # print(\"cl: \", cenList)\n\n # 由第i个簇分解为j、k两个簇所得到的数据将分解之前的数据替换掉\n clusterAssment[nonzero(clusterAssment[:,0].A == bestCentToSplit)[0],: ] = bestClustAss\n return cenList, clusterAssment\n\ndm = loadDataSet('testSet2.txt')\nprint(shape(dm))\ncl, ca = biKmeans(dm, 3)\n\n\n\n\n\n","repo_name":"kim1992/Machine-Learning","sub_path":"机器学习实战/kMeans/kMeans.py","file_name":"kMeans.py","file_ext":"py","file_size_in_byte":5013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"29094640270","text":"import numpy as np\nimport astropy.units as u\n\nfrom lsst.faro.utils.filtermatches import filterMatches\n\n__all__ = (\"photRepeat\", \"calcPhotRepeat\")\n\n\ndef photRepeat(matchedCatalog, magName=None, nMinPhotRepeat=50, **filterargs):\n \"\"\"Measure the photometric repeatability of a set of observations.\n\n Parameters\n ----------\n matchedCatalog : `lsst.afw.table.base.Catalog`\n `~lsst.afw.table.base.Catalog` object as created by\n `~lsst.afw.table.multiMatch` matching of sources from multiple visits.\n magName : `str`\n Name of the magnitude field. Default \"slot_PsfFlux_mag\".\n nMinPhotRepeat : `int`\n Minimum number of sources required to return a measurement.\n **filterargs\n Additional arguments to pass to `filterMatches` for catalog filtering.\n\n Returns\n -------\n photo_resid_meas : `dict`\n Photometric repeatability statistics and related quantities as measured\n by `calcPhotRepeat`. Returns NaN values if there are fewer than\n nMinPhotRepeat sources in the matched catalog.\n \"\"\"\n if magName is None:\n magName = \"slot_PsfFlux_mag\"\n filteredCat = filterMatches(matchedCatalog, **filterargs)\n magKey = filteredCat.schema.find(magName).key\n\n # Require at least nMinPhotRepeat objects to calculate the repeatability:\n if filteredCat.count > nMinPhotRepeat:\n phot_resid_meas = calcPhotRepeat(filteredCat, magKey)\n # Check that the number of stars with >2 visits is >nMinPhotRepeat:\n okcount = phot_resid_meas[\"count\"] > 2\n if np.sum(okcount) > nMinPhotRepeat:\n return phot_resid_meas\n else:\n return {\"nomeas\": np.nan * u.mmag}\n else:\n return {\"nomeas\": np.nan * u.mmag}\n\n\ndef calcPhotRepeat(matches, magKey):\n \"\"\"Calculate the photometric repeatability of a set of measurements.\n\n Parameters\n ----------\n matches : `lsst.afw.table.GroupView`\n `~lsst.afw.table.GroupView` of sources matched between visits using\n MultiMatch, as provided by `lsst.faro.utils.matcher.matchCatalogs`.\n magKey : `lsst.afw.table` schema key\n Magnitude column key in the ``GroupView``.\n E.g., ``magKey = allMatches.schema.find(\"slot_ModelFlux_mag\").key``\n where ``allMatches`` is the result of `lsst.afw.table.MultiMatch.finish()`.\n\n Returns\n -------\n statistics : `dict`\n Repeatability statistics and ancillary quantities calculated from the\n input ``GroupView`` matched catalog. Fields are:\n - ``count``: array of number of nonzero magnitude measurements for each\n input source.\n - ``magMean``: `~astropy.unit.Quantity` array of mean magnitudes, in mag,\n for each input source.\n - ``rms``: `~astropy.unit.Quantity` array of RMS photometric repeatability\n about the mean, in mmag, for each input source.\n - ``repeatability``: scalar `~astropy.unit.Quantity` of the median ``rms``.\n This is calculated using all sources with more than 2 magnitude\n measurements, and reported in mmag.\n - ``magResid``: `~astropy.unit.Quantity` array for each input source,\n containing the magnitude residuals, in mmag, with respect to ``magMean``.\n \"\"\"\n matches_rms = (matches.aggregate(np.nanstd, field=magKey) * u.mag).to(u.mmag)\n matches_count = matches.aggregate(np.count_nonzero, field=magKey)\n matches_mean = matches.aggregate(np.mean, field=magKey) * u.mag\n magResid = []\n for gp in matches.groups:\n magResid.append(((gp[magKey] - np.mean(gp[magKey])) * (u.mag)).to(u.mmag))\n magResid = np.array(magResid, dtype=\"object\")\n okrms = matches_count > 2\n if np.sum(okrms) > 0:\n return {\n \"count\": matches_count,\n \"magMean\": matches_mean,\n \"rms\": matches_rms,\n \"repeatability\": np.median(matches_rms[okrms]),\n \"magResid\": magResid,\n }\n else:\n return {\n \"count\": 0,\n \"magMean\": np.nan * u.mag,\n \"rms\": np.nan * u.mmag,\n \"repeatability\": np.nan * u.mmag,\n \"magDiffs\": 0 * u.mmag,\n }\n","repo_name":"lsst/faro","sub_path":"python/lsst/faro/utils/phot_repeat.py","file_name":"phot_repeat.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"26649755823","text":"import matplotlib.pyplot as plt\r\n\r\n# Sample data: contributor names and their response counts\r\ncontributors = ['Contributor A', 'Contributor B', 'Contributor C', 'Contributor D']\r\nresponse_counts = [45, 62, 30, 53]\r\n\r\n# Create a bar chart\r\nplt.bar(contributors, response_counts, color='blue')\r\n\r\n# Add labels and title\r\nplt.xlabel('Contributors')\r\nplt.ylabel('Response Counts')\r\nplt.title('Contributor Responses')\r\n\r\n# Display the chart\r\nplt.show()\r\n","repo_name":"gsnadeerameedin/Crowdsourcing-Platform","sub_path":"contributor_responses_graph.py","file_name":"contributor_responses_graph.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"15315822805","text":"\nstrin=input()\ntemp=strin.split()\nn=int(temp[0])\nk=int(temp[1])\ncoe=[]\nfor i in range(n):\n strin=input()\n coe.append(list(map(int,strin.split())))\nfor i in coe:\n key=round(-(i[1]/(2*i[0])))\n i.append(key)\nresult=[]\nwork=[]\ndis=0\nwhile len(result)**+}\"\"\"\n chunkparser = nltk.RegexpParser(chunk_gram)\n chunked = chunkparser.parse(tagged_data)\n chunked.draw()\n\n except Exception as e:\n print(str(e))\n\n\nprocess_content(custom_tokenize)","repo_name":"Shivam-bot/NLP","sub_path":"tagging.py","file_name":"tagging.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"43103127454","text":"\"\"\"\\\nPEP INFO\n\nPEP 303 -- Extend divmod() for Multiple Divisors\nStatus: Rejected\nCreated: 2002-12-31\n\nMODULE INFO\n\nThis module changes divmod() mostly following the PEP. However, divmod()\ndivides the divisors with the first divisor first. Last divisor first\nlike proposed is the rdivmod() function. The inverse_divmod function\nfrom PEP 303 is also added.\n\nREFERENCES\n\nPEP 303: \n\"\"\"\nPEP = 303\n\ndef divmod(dividend, *divisors) -> tuple:\n # Mostly copied from PEP 303\n modulos = ()\n q = dividend\n while divisors:\n try:\n qd = q.__divmod__\n except AttributeError:\n raise TypeError(f\"unsupported operand type(s) \"\n f\"for divmod(): {type(q).__name__!r} and \"\n f\"{type(divisors[0]).__name__!r}\") from None\n qr = qd(divisors[0])\n if qr is NotImplemented:\n raise TypeError(f\"unsupported operand type(s) \"\n f\"for divmod(): {type(q).__name__!r} and \"\n f\"{type(divisors[0]).__name__!r}\")\n q, r = qr\n modulos = (r,) + modulos\n divisors = divisors[1:]\n return (q,) + modulos[::-1]\ndef rdivmod(dividend, *divisors) -> tuple:\n x = divmod(dividend, *divisors[::-1])\n return (x[0], *x[1:][::-1])\ndef inverse_divmod(seq, *factors):\n # Copied from PEP 303\n product = seq[0]\n for x, y in zip(factors, seq[1:]):\n product = product * x + y\n return product\n","repo_name":"wyz23x2/rejected-peps","sub_path":"rejected_peps/pep303.py","file_name":"pep303.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"31997478396","text":"from Bio import SeqIO\nfrom shlex import quote\nimport argparse\n\ndef calc_n50(fastafile):\n lengths = []\n seqs = SeqIO.parse(fastafile, \"fasta\")\n for seq in seqs:\n lengths.append(len(seq.seq))\n lengths.sort()\n asmlen = sum(lengths)\n cumsum = 0\n for l in lengths:\n cumsum += l\n if cumsum >= asmlen/2:\n return sum(lengths), len(lengths), l\n\ndef n50_main(argv=None):\n \"\"\"Calculate N50 and total length of a set of contigs\"\"\"\n ap = argparse.ArgumentParser()\n ap.add_argument(\"fastas\", help=\"FASTA file of contigs\", nargs=\"+\")\n args = ap.parse_args(argv)\n \n for infile in args.fastas:\n nbases, ncontig, n50 = calc_n50(infile)\n print(quote(infile), \":\", sep=\"\")\n print(\" ncontigs:\", ncontig)\n print(\" n50:\", n50)\n print(\" total_length:\", nbases)\n\n\nif __name__ == \"__main__\":\n n50_main()\n","repo_name":"kdm9/blindschleiche","sub_path":"blsl/n50.py","file_name":"n50.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"16647969785","text":"# Import libraries\nimport pandas as pd\nimport datetime\nfrom os import listdir\nfrom os.path import isfile, join\nfrom airflow.models import Variable\n\n\ndef dim_status(df):\n current_status = df['6'].drop_duplicates().reset_index().drop('index',axis=1)\n current_status['Status_SK'] = range(1, len(current_status.index)+1)\n current_status = current_status[['Status_SK','6']]\n return current_status\n\ndef to_integer(dt_time):\n return 10000*dt_time.year + 100*dt_time.month + dt_time.day\n\ndef create_date_table(df):\n start = df['date'].min()\n end = df['date'].max()\n df = pd.DataFrame({\"Date\": pd.date_range(start, end)})\n df['Date_SK'] = df['Date'].map(lambda x: to_integer(x))\n df[\"Day\"] = df.Date.dt.day_name\n df[\"Week\"] = df.Date.dt.weekofyear\n df[\"Quarter\"] = df.Date.dt.quarter\n df[\"Year\"] = df.Date.dt.year\n df[\"Year_half\"] = (df.Quarter + 1) // 2\n date_table = df\n cols = ['Date_SK','Date','Day','Week','Quarter','Year','Year_half']\n date_table = date_table[cols]\n return date_table\n\n\ndef dim_item(df):\n mask = ['5','1','4','2','3']\n df2 = df[mask].drop_duplicates().sort_values(by='5')\n df2['Item_SK'] = range(1, len(df2.index)+1)\n Item = df2[['Item_SK','5','1','4','2','3']]\n Item = Item.merge(category_df,left_on='1', right_on='1', how='left')\n Item_codes = Item['3']\n\n Item_urls = []\n for code in Item_codes:\n URL = 'https://www.company.com/uk/p/{}'.format(code)\n Item_urls.append(URL)\n\n Image_urls = []\n for code in Item_codes:\n URL = 'https://media2.companyassets.com/i/company/{}/'.format(code)\n Image_urls.append(URL)\n\n Item['ItemURL'] = Item_urls\n Item['ImageURL'] = Image_urls\n\n return Item\n\n\ndef sales(df):\n df = df.merge(Status, left_on='6',right_on='6', how='left').drop('6', axis=1)\n cols_to_use = Item.columns.difference(df.columns)\n Item[cols_to_use]\n columns = ['2','3','5','4','1']\n sales = df.merge(Item, left_on=columns, right_on=columns, how='left').drop(columns,axis=1)\n sales.rename(columns={'date':'Date'}, inplace=True)\n sales['Date']= pd.to_datetime(sales['Date'])\n Date_table = Date[['Date_SK','Date']]\n sales = sales.merge(Date_table,left_on='Date',right_on='Date')\n cols = ['Item_SK','Status_SK','Date_SK','7', '8', '9',\n '10', '11', '9-1', '9-2',\n '9-3', '',\n '16', '17', '18',\n '19' ]\n sales = sales[cols]\n\n return sales\n\n\nSTAGING_DATA_LOCATION = Variable.get('staging_data_location')\nSTAR_SCHEMA_LOCATION = Variable.get('star_schema_location')\n\nstaging_df = pd.read_csv(STAGING_DATA_LOCATION+'sales_stage.csv')\ncategory_df = pd.read_csv(STAGING_DATA_LOCATION+'category_stage.csv')\n\nStatus = dim_status(staging_df)\nItem = dim_item(staging_df)\nDate = create_date_table(staging_df)\nSales = sales(staging_df)\n\ntable_dict = {'Status':Status,'Item':Item,'Date':Date,'Sales':Sales}\n\nfor name,table in table_dict.items():\n table.to_csv(STAR_SCHEMA_LOCATION+name+'.csv')\n","repo_name":"AlexanderA28/sample_report_system","sub_path":"3.TransformData.py","file_name":"3.TransformData.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"25273258409","text":"class Counter:\n def __init__(self, my_id):\n\n self._items = {}\n self._id = my_id\n\n def add(self, item_name, amount, price_of_unit):\n\n if item_name not in self._items:\n\n self._items[item_name] = {\n 'quantity': amount, 'price per unit': price_of_unit}\n else:\n self._items[item_name]['quantity'] += amount\n\n def remove(self, item_name, amount):\n if item_name not in self._items:\n pass\n elif amount >= self._items[item_name]['quantity']:\n del self._items[item_name]\n else:\n self._items[item_name]['quantity'] -= amount\n\n def reset(self):\n\n self._items.clear()\n\n def get_total(self):\n total_price_of_items = 0\n for item in self._items:\n total_price_of_items += (self._items[item]['quantity']\n * self._items[item]['price per unit'])\n return round(total_price_of_items, 2)\n\n def status(self):\n\n total_amount_of_items = 0\n\n for item in self._items:\n total_amount_of_items += self._items[item]['quantity']\n\n return (f'{self._id} {total_amount_of_items} {self.get_total()}')\n\n\ncart1 = Counter('C0001')\n\ncart1.add('potato', 2, 3.65)\ncart1.add('banana', 15, 1.54)\ncart1.remove('banana', 2)\n\n\nprint(cart1.status())\n\n\nclass Sector:\n def __init__(self):\n self.fr = 0\n self.to = 0\n self.rad = 0\n\n def rotate(self, angle):\n if angle + self.to > 359:\n print('This action is not possible')\n else:\n self.fr += angle\n self.to += angle\n\n def intersect(self, other):\n\n if self.fr >= other.fr:\n new_fr = self.fr\n else:\n new_fr = other.fr\n if self.to <= other.to:\n new_to = self.to\n else:\n new_to = other.to\n if self.rad <= other.rad:\n new_rad = self.rad\n else:\n new_rad = other.rad\n new_sector = Sector()\n new_sector.fr = new_fr\n new_sector.to = new_to\n new_sector.rad = new_rad\n return new_sector\n\n def is_empty(self):\n if self.fr == self.to:\n return True\n else:\n return False\n\n def __eq__(self, other):\n if self.rad == other.rad and self.fr == other.fr and self.to == other.to:\n return True\n else:\n return False\n\n def __str__(self):\n\n return (f'{self.fr} {self.to} {self.rad}')\n","repo_name":"idanpap/python-problems-bbk","sub_path":"session8/session8.py","file_name":"session8.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"26574680495","text":"import torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .bmm1 import *\nfrom .bmm2 import *\nfrom model.layers.padding import *\nfrom .softmax import *\n\n\nclass FastUnpadBertSelfAttention(nn.Module):\n\n def __init__(self,\n config,\n enable_stream=True,\n enable_sync=True,\n fuse_mask=True,\n fuse_scale=True,\n fuse_qkv=True,\n fuse_dropout=True,\n apex_softmax=True,\n pad=True):\n super(FastUnpadBertSelfAttention, self).__init__()\n if config.hidden_size % config.num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" %\n (config.hidden_size, config.num_attention_heads))\n self.num_attention_heads = config.num_attention_heads\n self.attention_head_size = int(config.hidden_size /\n config.num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n self.hidden_size = config.hidden_size\n\n self.fuse_qkv = fuse_qkv\n self.fuse_scale = fuse_scale\n self.fuse_mask = fuse_mask\n self.fuse_dropout = fuse_dropout\n self.apex_softmax = apex_softmax\n self.pad = pad\n self.enable_stream = enable_stream\n\n self.query = nn.Linear(config.hidden_size, self.all_head_size)\n self.key = nn.Linear(config.hidden_size, self.all_head_size)\n self.value = nn.Linear(config.hidden_size, self.all_head_size)\n\n if self.fuse_qkv:\n self.bmm1 = Bmm1Strided(None,\n None,\n self.num_attention_heads,\n self.attention_head_size,\n scale=self.fuse_scale,\n stream=enable_stream,\n sync=enable_sync,\n timer=False)\n self.bmm2 = Bmm2Strided(None,\n None,\n self.num_attention_heads,\n self.attention_head_size,\n stream=enable_stream,\n sync=enable_sync,\n timer=False)\n else:\n self.bmm1 = Bmm1(None,\n None,\n self.num_attention_heads,\n self.attention_head_size,\n scale=self.fuse_scale,\n stream=enable_stream,\n sync=enable_sync)\n self.bmm2 = Bmm2(None,\n None,\n self.num_attention_heads,\n self.attention_head_size,\n stream=enable_stream,\n sync=enable_sync)\n\n if self.fuse_dropout == False:\n self.dropout = nn.Dropout(config.attention_probs_dropout_prob)\n\n if self.fuse_mask == True and self.fuse_dropout == True:\n self.softmax = FastMaskSoftmaxDropout(\n dim=-1,\n dropout_prob=config.attention_probs_dropout_prob,\n stream=enable_stream,\n sync=(not self.pad),\n timer=False)\n elif self.fuse_mask == True:\n self.softmax = FastMaskSoftmax(dim=-1,\n stream=enable_stream,\n sync=enable_sync,\n timer=False)\n else:\n self.softmax = FastSoftmax(dim=-1,\n stream=enable_stream,\n sync=enable_sync,\n timer=False)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads,\n self.attention_head_size)\n x = torch.reshape(x, new_x_shape)\n return x.permute(0, 2, 1, 3)\n\n def transpose_key_for_scores(self, x):\n new_x_shape = x.size()[:-1] + (self.num_attention_heads,\n self.attention_head_size)\n x = torch.reshape(x, new_x_shape)\n return x.permute(0, 2, 3, 1)\n\n def pytorch_softmax(self, attention_scores, batch, seqlen, heads):\n ntokens2 = 0\n for i in range(batch):\n ntokens2 += seqlen[i] * seqlen[i] * self.num_attention_heads\n attention_probs = torch.zeros(ntokens2,\n device=\"cuda\",\n dtype=torch.float16)\n ntokens2 = 0\n for i in range(batch):\n tokens2 = seqlen[i] * seqlen[i] * self.num_attention_heads\n attention_probs[ntokens2:ntokens2 + tokens2] = F.softmax(\n attention_scores[ntokens2:ntokens2 + tokens2].view(\n 1, self.num_attention_heads, seqlen[i], seqlen[i]),\n dim=-1).flatten().contiguous()\n ntokens2 += tokens2\n return attention_probs\n\n def forward(self,\n hidden_states,\n attention_mask,\n seqlen,\n batch,\n is_training=True):\n\n self.batch = batch\n\n # QKV\n if self.fuse_qkv:\n weight = torch.cat([\n self.query.weight.view(self.num_attention_heads,\n self.attention_head_size, 1,\n self.hidden_size),\n self.key.weight.view(self.num_attention_heads,\n self.attention_head_size, 1,\n self.hidden_size),\n self.value.weight.view(self.num_attention_heads,\n self.attention_head_size, 1,\n self.hidden_size)\n ],\n dim=1).reshape(self.all_head_size * 3,\n self.hidden_size).contiguous()\n bias = torch.cat([\n self.query.bias.view(self.num_attention_heads, 1,\n self.attention_head_size),\n self.key.bias.view(self.num_attention_heads, 1,\n self.attention_head_size),\n self.value.bias.view(self.num_attention_heads, 1,\n self.attention_head_size)\n ],\n dim=1).reshape(3 * self.hidden_size).contiguous()\n mixed_x_layer = torch.addmm(bias, hidden_states, weight.t())\n else:\n query_layer = self.query(hidden_states)\n key_layer = self.key(hidden_states)\n value_layer = self.value(hidden_states)\n\n # BMM1.\n if self.enable_stream: torch.cuda.synchronize()\n if self.fuse_qkv:\n attention_scores, qkv_layer = self.bmm1(mixed_x_layer, self.batch,\n seqlen)\n else:\n attention_scores = self.bmm1(query_layer, key_layer, self.batch,\n seqlen)\n\n if self.enable_stream: torch.cuda.synchronize()\n if self.fuse_scale == False:\n attention_scores = attention_scores / math.sqrt(\n self.attention_head_size)\n\n # Softmax.\n if self.enable_stream: torch.cuda.synchronize()\n if self.fuse_mask == True and self.fuse_dropout == True:\n attention_probs = self.softmax(attention_scores, attention_mask,\n self.batch, seqlen,\n self.num_attention_heads,\n is_training)\n elif self.fuse_mask == True:\n attention_probs = self.softmax(attention_scores, attention_mask,\n self.batch, seqlen,\n self.num_attention_heads)\n else:\n attention_scores = attention_scores + attention_mask.view(-1)\n if self.apex_softmax == True:\n attention_probs = self.softmax(attention_scores, self.batch,\n seqlen,\n self.num_attention_heads)\n else:\n if self.pad == True:\n attention_probs = F.softmax(attention_scores.view(\n batch, self.num_attention_heads, seqlen[0], seqlen[0]),\n dim=-1).flatten().contiguous()\n else:\n attention_probs = self.pytorch_softmax(\n attention_scores, self.batch, seqlen,\n self.num_attention_heads)\n\n # Dropout.\n if self.enable_stream: torch.cuda.synchronize()\n if self.fuse_dropout == False:\n attention_probs = self.dropout(attention_probs)\n\n # BMM2.\n if self.enable_stream: torch.cuda.synchronize()\n if self.fuse_qkv:\n context_layer = self.bmm2(attention_probs, qkv_layer, self.batch,\n seqlen)\n else:\n context_layer = self.bmm2(attention_probs, value_layer, self.batch,\n seqlen)\n\n if self.enable_stream: torch.cuda.synchronize()\n new_context_layer_shape = context_layer.size()[:-2] + (\n self.all_head_size, )\n context_layer = torch.reshape(context_layer, new_context_layer_shape)\n return context_layer\n","repo_name":"FlagOpen/FlagPerf","sub_path":"training/nvidia/bert-pytorch/config/layers/mha.py","file_name":"mha.py","file_ext":"py","file_size_in_byte":9901,"program_lang":"python","lang":"en","doc_type":"code","stars":205,"dataset":"github-code","pt":"43"} +{"seq_id":"9820018223","text":"# By default, python does not provide abstract classes. Python comes with a module that provides the\r\n# base for defining Abstract Base Class (ABC) and that module name is ABC. ABC works by decorating\r\n# methods of the base class as an abstract and then registering concrete classes as implementations\r\n# of the abstract base. A method becomes abstract when decorated with the kewword @abstractmethod.\r\n\r\nfrom abc import ABC, abstractmethod\r\n\r\n\r\nclass Polygon(ABC):\r\n @abstractmethod\r\n def no_of_sides(self):\r\n pass\r\n\r\n\r\nclass Triangle(Polygon):\r\n\r\n # overriding abstract method\r\n def no_of_sides(self):\r\n print(\"Triangle have 3 sides\")\r\n\r\n\r\nclass Pentagon(Polygon):\r\n\r\n # overriding abstract method\r\n def no_of_sides(self):\r\n print(\"Pentagon have 5 sides\")\r\n\r\n\r\nclass Hexagon(Polygon):\r\n\r\n # overriding abstract method\r\n def no_of_sides(self):\r\n print(\"Hexagon have 6 sides\")\r\n\r\n\r\nclass Quadrilateral(Polygon):\r\n\r\n # overriding abstract method\r\n def no_of_sides(self):\r\n print(\"Quadrilaterals have 4 sides\")\r\n\r\n\r\n# Driver code\r\nR = Triangle()\r\nR.no_of_sides()\r\n\r\nK = Quadrilateral()\r\nK.no_of_sides()\r\n\r\nR = Pentagon()\r\nR.no_of_sides()\r\n\r\nK = Hexagon()\r\nK.no_of_sides()\r\n","repo_name":"Bilalkhan19b/OOP-Python","sub_path":"Abstract_class_example.py","file_name":"Abstract_class_example.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"26693497798","text":"# 2. Write a function that accepts a string and prints the number of uppercase letters and lowercase letters.\n#Sample input: “abcSdefPghijQkl”\n#Expected Output: No. of Uppercase characters : 3 No. of Lower case Characters : 12\n\nu_count = 0\nl_count = 0\ndef strFunc(str):\n global u_count\n global l_count\n for i in range(len(str)):\n if str[i].isupper():\n u_count+=1\n elif str[i].islower():\n l_count+=1\n\nstr1 = input(\"Enter a string : \")\nstrFunc(str1)\nprint(\"UpperCase Characters Count : \",u_count)\nprint(\"LowerCase Characters Count : \",l_count)","repo_name":"Anitha-2023/Python_repo","sub_path":"Task4files/Function2.py","file_name":"Function2.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"70532781890","text":"import json as jsonlib\nimport typing as t\n\n\nclass MockResponse:\n _json: t.Dict[str, t.Any] = None\n _text: str = None\n _bytes: bytes = None\n\n def __init__(\n self,\n status: int = 200,\n url: str = None,\n json: t.Dict[str, t.Any] = None,\n text: str = None,\n bytes: bytes = None,\n callback: t.Callable = None,\n attrs: t.Dict[str, t.Any] = None,\n ):\n self.status = status\n self.url = url\n self._json = json\n self.callback = callback\n self._text = text or jsonlib.dumps(json)\n self._bytes = bytes or self._text.encode(\"utf-8\")\n\n # Set attrs for flexibility\n attrs = attrs or {}\n for field, value in attrs.items():\n if field.startswith(\"_\"):\n raise ValueError(\"Cannot pass underscore attrs to MockedResponse\")\n setattr(self, field, value)\n\n def set_url(self, url: str):\n self.url = url\n\n async def text(self):\n return self._text\n\n async def json(self, *args, **kwargs):\n return self._json\n\n async def read(self):\n return self._bytes\n\n def release(self):\n pass\n\n @property\n def ok(self):\n return self.status < 400\n","repo_name":"IndicoDataSolutions/aiohttp_responses","sub_path":"aiohttp_responses/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"914482584","text":"import warnings\nfrom copy import deepcopy\nfrom itertools import product\n\nimport cv2\nimport torch.nn as nn\nimport torch.optim as optim\nfrom PIL import Image\nfrom numpy import arange\nfrom sklearn.model_selection import StratifiedShuffleSplit, train_test_split, ShuffleSplit\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import Subset\nfrom torchvision.transforms import transforms\n\nfrom michalski_trains.dataset import get_datasets\nfrom models.model import get_model\nfrom models.rcnn import rcnn_parallel\nfrom models.rcnn.rcnn_train import train_rcnn\nfrom models.train_loop import do_train\nfrom util import *\nfrom visualization.vis_model import visualize_statistics, vis_confusion_matrix\nfrom visualization.vis_model_comparison import model_scene_imcount_comparison, csv_to_tex_table\n\n\nclass Trainer:\n def __init__(self, base_scene, raw_trains, train_vis, device, model_name, class_rule, ds_path,\n X_val='image', y_val='direction', max_car=4, min_car=2,\n resume=False, pretrained=True, resize=None, optimizer_='ADAM', loss='CrossEntropyLoss',\n train_size=None, val_size=None, ds_size=10000, image_noise=0, label_noise=0,\n batch_size=50, num_worker=4, lr=None, step_size=5, gamma=.8, momentum=0.9,\n num_epochs=25, setup_model=True, setup_ds=True, save_model=True):\n\n # ds_val setup\n self.settings = f'{train_vis}_{class_rule}_{raw_trains}_{base_scene}_len_{min_car}-{max_car}'\n self.base_scene, self.raw_trains, self.train_vis, self.class_rule = base_scene, raw_trains, train_vis, class_rule\n self.ds_path, self.ds_size = ds_path, ds_size\n self.max_car, self.min_car = max_car, min_car\n self.device = device\n self.X_val, self.y_val = X_val, y_val\n self.pretrained, self.resume, self.save_model = pretrained, resume, save_model\n self.resize, self.image_noise, self.label_noise = resize, image_noise, label_noise\n if self.resize is None:\n self.resize = True if model_name == 'VisionTransformer' else False\n\n # model setup\n self.model_name = model_name\n self.optimizer_name, self.loss_name = optimizer_, loss\n # preprocessing needed for faster rcnn\n self.preprocess = None\n # training hyper parameter\n self.batch_size, self.num_worker, self.step_size, self.gamma, self.momentum, self.num_epochs = \\\n batch_size, num_worker, step_size, gamma, momentum, num_epochs\n self.lr = lr if lr is not None else 0.00001 if model_name == 'VisionTransformer' else 0.001\n self.out_path = self.get_model_path()\n self.ds, self.dl = None, None\n # setup model and dataset\n if setup_model:\n self.setup_model(resume=resume)\n else:\n self.model = None\n if setup_ds:\n self.full_ds = get_datasets(self.base_scene, self.raw_trains, self.train_vis, ds_size=self.ds_size,\n ds_path=self.ds_path,\n y_val=y_val, max_car=self.max_car, min_car=self.min_car,\n class_rule=self.class_rule,\n resize=self.resize, preprocessing=self.preprocess)\n self.setup_ds(train_size=train_size, val_size=val_size)\n else:\n self.full_ds = None\n\n def cross_val_train(self, train_size=None, label_noise=None, rules=None, visualizations=None, scenes=None,\n n_splits=5, model_path=None, save_models=False, replace=False, image_noise=None, ex_name=None,\n start_it=0):\n if train_size is None:\n train_size = [10000]\n if label_noise is None:\n label_noise = [self.label_noise]\n if image_noise is None:\n image_noise = [self.image_noise]\n if rules is None:\n rules = [self.class_rule]\n if visualizations is None:\n visualizations = [self.train_vis]\n if scenes is None:\n scenes = [self.base_scene]\n random_state = 0\n test_size = 2000\n self.save_model = save_models\n tr_it, tr_b = 0, 0\n n_batches = sum(train_size) // self.batch_size\n tr_b_total = n_splits * n_batches * len(label_noise) * len(image_noise) * len(rules) * len(\n visualizations) * len(scenes)\n tr_it_total = n_splits * len(train_size) * len(label_noise) * len(image_noise) * len(rules) * len(\n visualizations) * len(scenes)\n for l_noise, i_noise, rule, visualization, scene in product(label_noise, image_noise, rules, visualizations,\n scenes):\n self.label_noise, self.image_noise, self.class_rule, self.train_vis, self.base_scene = l_noise, i_noise, rule, visualization, scene\n self.full_ds = get_datasets(self.base_scene, self.raw_trains, self.train_vis, class_rule=rule,\n ds_size=self.ds_size, max_car=self.max_car, min_car=self.min_car,\n ds_path=self.ds_path,\n resize=self.resize)\n for t_size in train_size:\n self.full_ds.predictions_im_count = t_size\n cv = StratifiedShuffleSplit(train_size=t_size, test_size=test_size, random_state=random_state,\n n_splits=n_splits)\n y = np.concatenate([self.full_ds.get_direction(item) for item in range(self.full_ds.__len__())])\n\n for fold, (tr_idx, val_idx) in enumerate(cv.split(np.zeros(len(y)), y)):\n self.out_path = self.get_model_path(prefix=True, suffix=f'it_{fold}/', im_count=t_size)\n if tr_it >= start_it and (not (os.path.isfile(self.out_path + 'metrics.json') and os.path.isfile(\n self.out_path + 'model.pth')) or replace):\n print('====' * 10)\n print(\n f'training iteration {tr_it + 1}/{tr_it_total} with {t_size // self.batch_size} '\n f'training batches, already completed: {tr_b}/{tr_b_total} batches. ')\n self.setup_model(resume=self.resume, path=model_path)\n self.setup_ds(tr_idx=tr_idx, val_idx=val_idx, label_noise=self.label_noise,\n image_noise=self.image_noise)\n self.train(rtpt_extra=(tr_b_total - tr_b) * self.num_epochs, set_up=False, ex_name=ex_name)\n del self.model\n tr_b += t_size // self.batch_size\n tr_it += 1\n\n def train(self, rtpt_extra=0, train_size=None, val_size=None, set_up=True, ex_name=None, gpu_count=1):\n if self.full_ds is None:\n self.full_ds = get_datasets(self.base_scene, self.raw_trains, self.train_vis, class_rule=self.class_rule,\n ds_size=self.ds_size, max_car=self.max_car, min_car=self.min_car,\n ds_path=self.ds_path, y_val=self.y_val,\n resize=self.resize)\n if set_up:\n # self.ds_size = ds_size if ds_size is not None else self.ds_size\n self.setup_model(self.resume)\n self.setup_ds(train_size=train_size, val_size=val_size, label_noise=self.label_noise,\n image_noise=self.image_noise)\n if 'rcnn' in self.model_name:\n if gpu_count > 1:\n rcnn_parallel.train_parallel(self.out_path, self.model, self.ds, self.optimizer, self.scheduler,\n self.num_epochs, self.batch_size, self.save_model, world_size=gpu_count,\n ex_name=ex_name)\n else:\n self.model = train_rcnn(self.base_scene, self.raw_trains, self.y_val, self.device, self.out_path,\n self.model_name, self.model, self.full_ds, self.dl, self.checkpoint,\n self.optimizer,\n self.scheduler, self.criteria, num_epochs=self.num_epochs, lr=self.lr,\n step_size=self.step_size, gamma=self.gamma, save_model=self.save_model,\n rtpt_extra=rtpt_extra, ex_name=ex_name\n )\n else:\n self.model = do_train(self.base_scene, self.raw_trains, self.y_val, self.device, self.out_path,\n self.model_name, self.model, self.full_ds, self.dl, self.checkpoint, self.optimizer,\n self.scheduler, self.criteria, num_epochs=self.num_epochs, lr=self.lr,\n step_size=self.step_size, gamma=self.gamma, save_model=self.save_model,\n rtpt_extra=rtpt_extra, ex_name=ex_name\n )\n torch.cuda.empty_cache()\n\n def val(self, val_size=None, set_up=True, model_path=None):\n eps = self.num_epochs\n self.num_epochs = 1\n if set_up:\n val_size = val_size if val_size is not None else self.ds_size\n self.setup_ds(val_size=val_size)\n self.setup_model(self.resume, path=model_path)\n if self.model_name == 'rcnn':\n acc, precision, recall = train_rcnn(self.base_scene, self.raw_trains, self.y_val, self.device,\n self.out_path,\n self.model_name,\n self.model, self.full_ds, self.dl, self.checkpoint, self.optimizer,\n self.scheduler,\n self.criteria, num_epochs=self.num_epochs, lr=self.lr,\n step_size=self.step_size,\n gamma=self.gamma, save_model=False, train='val')\n\n else:\n acc, precision, recall = do_train(self.base_scene, self.raw_trains, self.y_val, self.device, self.out_path,\n self.model_name,\n self.model, self.full_ds, self.dl, self.checkpoint, self.optimizer,\n self.scheduler,\n self.criteria, num_epochs=self.num_epochs, lr=self.lr,\n step_size=self.step_size,\n gamma=self.gamma, save_model=False, train='val')\n torch.cuda.empty_cache()\n self.num_epochs = eps\n return acc, precision, recall\n\n def infer_im(self, im_path):\n im = Image.open(im_path).convert('RGB')\n norm = [transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])]\n if self.resize:\n norm.append(transforms.Resize((224, 224), interpolation=transforms.InterpolationMode.BICUBIC))\n norm = transforms.Compose(norm)\n im = norm(im).unsqueeze(0)\n\n from models.inference import do_infer_im\n label = do_infer_im(im, self.model, self.device)\n return label\n\n def setup_model(self, resume=False, path=None, y_val=None):\n # set path\n path = self.out_path if path is None else path\n set_up_txt = f'set up foundation model: {self.model_name}' if not resume else \\\n f'loading trained model: {self.model_name} from {path} model.pth'\n set_up_txt += f' with lr {self.lr}, loss {self.loss_name},' \\\n f' optimizer {self.optimizer_name}, scheduler: step size {self.step_size}, gamma {self.gamma},' \\\n f' batch size {self.batch_size}, epochs {self.num_epochs}'\n\n if resume and os.path.isfile(path + 'model.pth') and os.path.isfile(path + 'metrics.json'):\n self.checkpoint = torch.load(path + 'model.pth', map_location=self.device)\n set_up_txt += ': loaded from ' + path\n elif resume and os.path.isfile(path + 'model.pth'):\n self.checkpoint = torch.load(path + 'model.pth', map_location=self.device)\n set_up_txt += ': loaded from ' + path\n warnings.warn('no metrics found')\n else: # no checkpoint found\n if resume:\n raise AssertionError(f'no pretrained model or metrics found at {path}\\n please train model first')\n self.checkpoint = None\n\n print(set_up_txt)\n # dim_out = get_output_dim(y_val)\n # class_dim = get_class_dim(y_val)\n dim_out = self.full_ds.get_output_dim() if y_val is None else get_output_dim(y_val)\n class_dim = self.full_ds.get_class_dim() if y_val is None else get_class_dim(y_val)\n if self.loss_name == 'MSELoss':\n loss_fn = nn.MSELoss()\n else:\n loss_fn = nn.CrossEntropyLoss()\n self.criteria = [loss_fn] * dim_out\n rcnn_labels_per_segment = 4 if self.train_vis == 'SimpleObjects' else 3\n self.model, self.preprocess = get_model(self.model_name, self.pretrained and not resume, dim_out, class_dim,\n rcnn_labels_per_segment=rcnn_labels_per_segment)\n\n if self.checkpoint is not None:\n self.model.load_state_dict(self.checkpoint['model_state_dict'])\n\n if self.optimizer_name == 'SGD':\n self.optimizer = optim.SGD(self.model.parameters(), lr=self.lr, momentum=self.momentum)\n elif self.optimizer_name == 'ADAM':\n self.optimizer = optim.Adam(self.model.parameters(), lr=self.lr, weight_decay=1e-5)\n elif self.optimizer_name == 'ADAMW':\n self.optimizer = optim.AdamW(self.model.parameters(), lr=self.lr, weight_decay=1e-5)\n else:\n raise AssertionError('specify valid optimizer')\n if self.checkpoint is not None:\n self.optimizer.load_state_dict(self.checkpoint['optimizer_state_dict'])\n\n # apparently the optimizer is not on gpu -> send it to the gpu\n optimizer_to(self.optimizer, device=self.device)\n\n # self.scheduler = lr_scheduler.ExponentialLR(optimizer, gamma=0.95)\n self.scheduler = lr_scheduler.StepLR(self.optimizer, step_size=self.step_size, gamma=self.gamma)\n\n def setup_ds(self, tr_idx=None, val_idx=None, train_size=None, val_size=None, label_noise=0, image_noise=0):\n if self.full_ds is None:\n self.full_ds = get_datasets(self.base_scene, self.raw_trains, self.train_vis, ds_size=self.ds_size,\n ds_path=self.ds_path, y_val=self.y_val, max_car=self.max_car,\n min_car=self.min_car, class_rule=self.class_rule, resize=self.resize,\n preprocessing=self.preprocess)\n # print(f'set up dataset to directory: {self.ds_path}')\n if tr_idx is None or val_idx is None:\n if train_size is None and val_size is None:\n train_size = int(0.8 * self.ds_size)\n val_size = int(0.2 * self.ds_size)\n elif train_size is None:\n train_size = 0\n elif val_size is None:\n val_size = int(0.2 * self.ds_size)\n # tr_idx = arange(train_size)\n # val_idx = arange(train_size, train_size + val_size)\n tr_idx, val_idx, y_train, y_test = train_test_split(range(self.ds_size), range(self.ds_size), train_size=train_size,\n test_size=val_size, stratify=self.full_ds.y)\n if len(tr_idx) > 0:\n set_up_txt = f'split ds into training ds with {len(tr_idx)} images and validation ds with {len(val_idx)} images'\n print(set_up_txt)\n tr_ds = deepcopy(self.full_ds) if label_noise > 0 or image_noise > 0 else self.full_ds\n if label_noise > 0:\n tr_ds.apply_label_noise(label_noise)\n if image_noise > 0:\n tr_ds.apply_image_noise(image_noise)\n self.ds = {\n 'train': Subset(tr_ds, tr_idx),\n 'val': Subset(self.full_ds, val_idx)\n }\n if 'rcnn' in self.model_name:\n self.dl = {'train': DataLoader(self.ds['train'], batch_size=self.batch_size, num_workers=self.num_worker,\n collate_fn=collate_fn_rcnn),\n 'val': DataLoader(self.ds['val'], batch_size=self.batch_size, num_workers=self.num_worker,\n collate_fn=collate_fn_rcnn)}\n else:\n self.dl = {'train': DataLoader(self.ds['train'], batch_size=self.batch_size, num_workers=self.num_worker),\n 'val': DataLoader(self.ds['val'], batch_size=self.batch_size, num_workers=self.num_worker)}\n\n\n def plt_accuracy(self):\n visualize_statistics(self.raw_trains, self.base_scene, self.y_val, self.ds, self.out_path, self.model_name)\n\n def plt_confusion_matrix(self):\n vis_confusion_matrix(self.raw_trains, self.base_scene, self.out_path, self.model_name, self.model,\n self.dl, self.device)\n\n def plt_cross_val_performance(self, tex_table=False, models=None):\n if models is None:\n models = [self.model_name]\n print('plotting cross validated performance')\n path = self.get_model_path()\n model_scene_imcount_comparison(self.raw_trains, models, self.y_val, path)\n if tex_table:\n csv_to_tex_table(path + 'mean_variance_comparison.csv')\n\n def get_model_path(self, prefix=False, suffix='', im_count=None, model_name=None):\n model_name = self.model_name if model_name is None else model_name\n pre = '_pretrained' if self.pretrained else ''\n im_count = self.ds_size if im_count is None else im_count\n ds_settings = f'{self.train_vis}_{self.class_rule}_{self.raw_trains}_{self.base_scene}'\n train_config = f'imcount_{im_count}_X_val_{self.X_val}{pre}_lr_{self.lr}_step_{self.step_size}_gamma{self.gamma}'\n pref = '' if not prefix else 'cv'\n if self.label_noise > 0:\n pref += f'_{self.label_noise}noise'\n if self.image_noise > 0:\n pref += f'_{self.image_noise}im_noise'\n pref = pref if pref == '' else f'{pref}/'\n\n # if self.label_noise > 0:\n # train_config += f'noise_{self.label_noise}'\n # if self.image_noise > 0:\n # train_config += f'im_noise_{self.image_noise}'\n # if prefix and self.label_noise > 0:\n # pref = f'cv_{self.label_noise}noise/'\n # elif prefix:\n # pref = 'cv/'\n # else:\n # pref = ''\n out_path = f'output/models/{model_name}/{self.y_val}_classification/{ds_settings}/{pref}{train_config}/{suffix}'\n return out_path\n\n\n# copied from https://discuss.pytorch.org/t/moving-optimizer-from-cpu-to-gpu/96068\ndef optimizer_to(optim, device):\n for param in optim.state.values():\n # Not sure there are any global tensors in the state dict\n if isinstance(param, torch.Tensor):\n param.data = param.data.to(device)\n if param._grad is not None:\n param._grad.data = param._grad.data.to(device)\n elif isinstance(param, dict):\n for subparam in param.values():\n if isinstance(subparam, torch.Tensor):\n subparam.data = subparam.data.to(device)\n if subparam._grad is not None:\n subparam._grad.data = subparam._grad.data.to(device)\n\n\ndef get_class_dim(y_val):\n '''\n Get the number of classes for each label\n :param y_val: type of y_val\n :return: number of classes for each label\n '''\n # ds labels\n labels = ['direction']\n label_classes = ['west', 'east']\n attributes = ['color', 'length', 'walls', 'roofs', 'wheel_count', 'load_obj1', 'load_obj2',\n 'load_obj3'] * 4\n color = ['yellow', 'green', 'grey', 'red', 'blue']\n length = ['short', 'long']\n walls = [\"braced_wall\", 'solid_wall']\n roofs = [\"roof_foundation\", 'solid_roof', 'braced_roof', 'peaked_roof']\n wheel_count = ['2_wheels', '3_wheels']\n load_obj = [\"box\", \"golden_vase\", 'barrel', 'diamond', 'metal_pot', 'oval_vase']\n attribute_classes = ['none'] + color + length + walls + roofs + wheel_count + load_obj\n output = {\n 'direction': len(label_classes),\n 'attributes': len(attribute_classes),\n 'mask': len(attribute_classes),\n 'maskv2': len(attribute_classes),\n }\n return output[y_val]\n\n\ndef get_class_names(y_val):\n '''\n Get the class names for each label\n :param y_val: type of y_val\n :return: class names for each label\n '''\n # ds labels\n labels = ['direction']\n label_classes = ['west', 'east']\n attributes = ['color', 'length', 'walls', 'roofs', 'wheel_count', 'load_obj1', 'load_obj2',\n 'load_obj3'] * 4\n color = ['yellow', 'green', 'grey', 'red', 'blue']\n length = ['short', 'long']\n walls = [\"braced_wall\", 'solid_wall']\n roofs = [\"roof_foundation\", 'solid_roof', 'braced_roof', 'peaked_roof']\n wheel_count = ['2_wheels', '3_wheels']\n load_obj = [\"box\", \"golden_vase\", 'barrel', 'diamond', 'metal_pot', 'oval_vase']\n attribute_classes = ['none'] + color + length + walls + roofs + wheel_count + load_obj\n output = {\n 'direction': label_classes,\n 'attributes': attribute_classes,\n 'mask': attribute_classes,\n 'maskv2': attribute_classes,\n }\n return output[y_val]\n\n\ndef get_output_dim(y_val):\n '''\n Get number of labels\n :param y_val: type of y_val\n :return: number of labels\n '''\n # ds labels\n labels = ['direction']\n label_classes = ['west', 'east']\n attributes = ['color', 'length', 'walls', 'roofs', 'wheel_count', 'load_obj1', 'load_obj2',\n 'load_obj3'] * 4\n color = ['yellow', 'green', 'grey', 'red', 'blue']\n length = ['short', 'long']\n walls = [\"braced_wall\", 'solid_wall']\n roofs = [\"roof_foundation\", 'solid_roof', 'braced_roof', 'peaked_roof']\n wheel_count = ['2_wheels', '3_wheels']\n load_obj = [\"box\", \"golden_vase\", 'barrel', 'diamond', 'metal_pot', 'oval_vase']\n attribute_classes = ['none'] + color + length + walls + roofs + wheel_count + load_obj\n output = {\n 'direction': len(labels),\n 'attributes': len(attributes),\n 'mask': len(attributes),\n 'maskv2': len(attributes),\n }\n return output[y_val]\n\n\ndef collate_fn_rcnn(batch):\n \"\"\"\n To handle the data loading as different images may have different number\n of objects and to handle varying size tensors as well.\n \"\"\"\n return tuple(zip(*batch))\n","repo_name":"lukashelff/visual-logical-learning","sub_path":"models/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":23119,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"31770671084","text":"from general_usages import *\nfrom tkinter import *\nfrom math import *\nfrom tkinter import messagebox\n\n\nclass Material:\n def __init__(self, name, material_type, elastic_modulus, ultimate_strength, f_limit, f_limit_cycles,\n f_limit_reversals, stress_intercept, stress_slope,\n fs_coefficient, fs_exponent, fd_coefficient, fd_exponent,\n cs_coefficient, cs_exponent, cg_intercept, cg_exponent, cg_ratio, ts_intensity):\n self.name = name\n material_types = {1: '1. Steel', 2: '2. Aluminum', 3: '3. Nickel', 4: '4. Stainless steel', 5: '5. Other'}\n self.material_elastic = {'1. Steel': 207000, '2. Aluminum': 80000, '3. Nickel': 205000, '4. Stainless': 190000,\n '5. Other': 207000}\n self.material_type = material_types[material_type]\n self.su = ultimate_strength\n self._2nfl = f_limit_reversals\n self.nfl = self.value_or_default(f_limit_cycles, pow(10, 6))\n self.sf = self.value_or_default(stress_intercept, 1.6)\n self.B = self.value_or_default(stress_slope, -0.085)\n self.of = self.value_or_default(fs_coefficient, 1)\n self.b_exponent = self.value_or_default(fs_exponent, 1)\n self.ef = self.value_or_default(fd_coefficient, 1)\n self.c_exponent = self.value_or_default(fd_exponent, 1)\n self.n_exponent = self.value_or_default(cs_exponent, float(self.b_exponent) / float(self.c_exponent))\n self.K = self.value_or_default(cs_coefficient, float(self.of) / pow(float(self.ef), float(self.n_exponent)))\n self.C = cg_intercept\n self.m_exponent = cg_exponent\n self.rmat = cg_ratio\n self.kth = ts_intensity\n self.E = self.value_or_default(elastic_modulus, self.material_elastic[self.material_type])\n self.sfl = f_limit\n # TODO: Set Default for sfl later to avoid conflict with other theories\n\n @staticmethod\n def value_or_default(value, default):\n if value == '':\n return default\n else:\n return value\n\n\nother = Material('Other', 5, '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '')\nalu1100 = Material('Aluminum 1100', 2, 69000, 110, \"\", \"\", \"\", 155, -0.096, 166, -0.096, 1.643, -0.669, 154, 0.144,\n \"\", 2.79, \"\", \"\")\n\n\n# TODO: Store the defaults in a string\n\n\nclass StressLife:\n def __init__(self):\n\n self.window = Toplevel()\n self.window.title(\"Stress Life\")\n\n self.sfcanvas = Canvas(self.window, width=880, height=800)\n self.sfscrollbar = Scrollbar(self.window, command=self.sfcanvas.yview)\n self.sfcanvas.config(yscrollcommand=self.sfscrollbar.set)\n self.sfframe = Frame(self.sfcanvas, height=1650, bg=styles.frame_background)\n self.sfcanvas.create_window((0, 0), window=self.sfframe, anchor=NW)\n self.sfcanvas.config(scrollregion=self.sfcanvas.bbox(\"all\"))\n self.sfcanvas.pack(side=LEFT)\n self.sfscrollbar.pack(side=LEFT, fill=Y, expand=TRUE)\n\n self.givenvar = StringVar(self.sfframe)\n self.givens = ['Smax & Smin',\n 'Sa & Sm']\n self.givenvar.set(self.givens[0])\n self.givenvar.trace('w', lambda *args: self.given_tracer())\n self.givenmenu = OptionMenu(self.sfframe, self.givenvar, *self.givens)\n Label(self.sfframe, bg=styles.frame_background, text='Units are measured in MPA', font=(styles.font, 8)).grid(\n sticky=W)\n Label(self.sfframe, bg=styles.frame_background, text='Loading', font=(styles.font, 30)).grid(sticky=W,\n pady=(15, 0))\n self.givenmenu.grid(sticky=W, padx=5, pady=5)\n self.entrysmax = Entry(self.sfframe)\n self.entrysmin = Entry(self.sfframe)\n self.entrysa = Entry(self.sfframe, state='readonly')\n self.entrysm = Entry(self.sfframe, state='readonly')\n easy_grid(\n [Label(self.sfframe, bg=styles.frame_background, text='Maximum (Smax or e(max))', font=(styles.font, 20)),\n self.entrysmax,\n Label(self.sfframe, bg=styles.frame_background, text='Minimum (Smin or e(min))', font=(styles.font, 20)),\n self.entrysmin,\n Label(self.sfframe, bg=styles.frame_background, text='Alternating (Sa or e(a))', font=(styles.font, 20)),\n self.entrysa,\n Label(self.sfframe, bg=styles.frame_background, text='Mean (Sm or e(m))', font=(styles.font, 20)),\n self.entrysm], 2, 5, 0)\n Label(self.sfframe, bg=styles.frame_background, text='Material', font=(styles.font, 30)).grid(sticky=W,\n pady=(15, 0))\n\n \n self.stress_material_list = [other, alu1100]\n self.stress_display_list = []\n for item in self.stress_material_list:\n self.stress_display_list.append(item.name)\n self.material_var = StringVar(self.sfframe)\n self.material_menu = OptionMenu(self.sfframe, self.material_var, *self.stress_display_list)\n self.material_var.set(self.stress_display_list[0])\n self.material_var.trace('w', lambda *args: self.material_tracer())\n self.entryname = Entry(self.sfframe)\n\n \n\n self.entrytype = Entry(self.sfframe)\n self.entrytype.insert(0, '1. Steel')\n self.entrytype['state'] = 'readonly'\n self.typevar = StringVar(self.sfframe)\n self.types = ['1. Steel', '2. Aluminum', '3. Nickel', '4. Stainless Steel', '5. Other']\n self.typevar.set(self.types[0])\n self.typevar.trace('w', lambda *args: self.type_tracer())\n self.typemenu = OptionMenu(self.sfframe, self.typevar, *self.types)\n\n self.entrysu = Entry(self.sfframe)\n self.entrye_modulus = Entry(self.sfframe)\n self.entryflimit = Entry(self.sfframe)\n self.entryflimitcycles = Entry(self.sfframe)\n self.entryintercept = Entry(self.sfframe)\n self.entryslope = Entry(self.sfframe)\n easy_grid(self.grid_entries(['Material', 'Name', 'Type', 'Ultimate Strength', 'Elastic Modulus',\n 'Fatigue Limit', 'Fatigue Limit Cycles', 'Intercept',\n 'Slope'], [self.material_menu, self.entryname, self.entrytype,\n self.entrysu, self.entrye_modulus, self.entryflimit,\n self.entryflimitcycles, self.entryintercept,\n self.entryslope]), 2, 10, 0)\n self.typemenu.grid(row=12, column=3)\n Label(self.sfframe, bg=styles.frame_background, text='Modifying Factors', font=(styles.font, 30)).grid(sticky=W,\n pady=(\n 15,\n 0))\n \n\n\n\n\n \n self.entryksf = Entry(self.sfframe)\n self.entrykl = Entry(self.sfframe)\n self.size_or_d_var = StringVar(self.sfframe)\n self.size_or_d_lst = ['Ksize',\n 'Diameter']\n self.size_or_d_menu = OptionMenu(self.sfframe, self.size_or_d_var, *self.size_or_d_lst)\n self.size_or_d_var.set(self.size_or_d_lst[0])\n self.size_or_d_var.trace('w', lambda *args: self.size_or_diameter_tracer())\n self.entryksize = Entry(self.sfframe)\n self.entrydiameter = Entry(self.sfframe, state='readonly')\n easy_grid(self.grid_entries(['Surface Factor', 'Loading Factor', 'Use Diameter or size factor?',\n 'Size Factor', 'Diameter (mm)'],\n [self.entryksf, self.entrykl, self.size_or_d_menu,\n self.entryksize, self.entrydiameter]), 2, 20, 0)\n Label(self.sfframe, bg=styles.frame_background, text='Stress Concentration Factor',\n font=(styles.font, 30)).grid(sticky=W, pady=(15, 0))\n self.sc_var = StringVar(self.sfframe)\n self.sc_lst = ['Stress Concentration Factor and radius',\n 'Fatigue Notch Factor',\n 'None']\n self.sc_menu = OptionMenu(self.sfframe, self.sc_var, *self.sc_lst)\n self.sc_var.set(self.sc_lst[0])\n self.sc_var.trace('w', lambda *args: self.sc_factor_tracer())\n self.entrykt = Entry(self.sfframe)\n self.entrykf = Entry(self.sfframe, state='readonly')\n self.entryradius = Entry(self.sfframe)\n # print(self.entrydiameter.grid_info())\n easy_grid(self.grid_entries(['Use:', 'Stress Concentration Factor', 'Fatigue Notch Factor', 'Radius (mm)'],\n [self.sc_menu, self.entrykt, self.entrykf, self.entryradius], ),\n 2, 26, 0)\n self.buttoncalculate = Button(self.sfframe, text=\"Calculate\", font=(styles.font, 24),\n bg=styles.button_background, bd=styles.button_border,\n activebackground=styles.button_active,\n command=lambda: self.get_calculate_data())\n self.buttoncalculate.grid(column=0, row=self.entryradius.grid_info()['row'] + 1, sticky=W, padx=5, pady=(20, 0))\n\n self.surface_var = StringVar(self.sfframe)\n self.surface_lst = ['None', 'Ground', 'Machined', 'Cold Drawn', 'Hot Rolled', 'As Forged']\n self.surface_menu = OptionMenu(self.sfframe, self.surface_var, *self.surface_lst)\n self.surface_var.set(self.surface_lst[0])\n self.surface_var.trace('w', lambda *args: self.surface_tracer())\n\n\n\n\n def grid_entries(self, label_texts, entries):\n grid_list = []\n i = 0\n while i < len(label_texts):\n grid_list.append(\n Label(self.sfframe, bg=styles.frame_background, text=label_texts[i], font=(styles.font, 20)))\n grid_list.append(entries[i])\n i += 1\n return grid_list\n\n def given_tracer(self):\n smax_smin = [self.entrysmax, self.entrysmin]\n sa_sm = [self.entrysa, self.entrysm]\n if self.givens.index(self.givenvar.get()) == 0:\n for item in smax_smin:\n item['state'] = 'normal'\n for item in sa_sm:\n item.delete(0, END)\n item['state'] = 'readonly'\n else:\n for item in smax_smin:\n item.delete(0, END)\n item['state'] = 'readonly'\n for item in sa_sm:\n item['state'] = 'normal'\n\n def material_tracer(self):\n # Sets material to an instance of a class that contains properties (name, material_type, material.su,\n # material.E, material.sfl, material.nfl and material.sf)\n material = self.stress_material_list[self.stress_display_list.index(self.material_var.get())]\n # The keys are entries and the values are properties to assign to the entries\n entry_property = {self.entryname: material.name, self.entrytype: material.material_type,\n self.entrysu: material.su, self.entrye_modulus: material.E, self.entryflimit: material.sfl,\n self.entryflimitcycles: material.nfl, self.entryintercept: material.sf,\n self.entryslope: material.B}\n for item in entry_property.keys():\n item['state'] = 'normal'\n item.delete(0, END)\n item.insert(0, entry_property[item])\n self.entrytype['state'] = 'readonly'\n # TODO: Move last line to calculate function\n\n def size_or_diameter_tracer(self):\n if self.size_or_d_lst.index(self.size_or_d_var.get()) == 0:\n self.entryksize['state'] = 'normal'\n self.entrydiameter.delete(0, END)\n self.entrydiameter['state'] = 'readonly'\n else:\n self.entrydiameter['state'] = 'normal'\n self.entryksize.delete(0, END)\n self.entryksize['state'] = 'readonly'\n\n def sc_factor_tracer(self):\n enable_disable = {0: [self.entrykf],\n 1: [self.entrykt, self.entryradius],\n 2: [self.entrykf, self.entrykt, self.entryradius]}\n index = self.sc_lst.index(self.sc_var.get())\n entries = enable_disable[index]\n for lists in enable_disable.values():\n for entry in lists:\n entry['state'] = 'normal'\n for item in entries:\n item.delete(0, END)\n item['state'] = 'readonly'\n\n def type_tracer(self):\n self.entrytype['state'] = 'normal'\n self.entrytype.delete(0, END)\n self.entrytype.insert(0, self.typevar.get())\n self.entrytype['state'] = 'readonly'\n\n def surface_tracer(self):\n pass\n\n # TODO: Continue\n\n def get_sa_sm(self):\n if self.givens.index(self.givenvar.get()) == 0:\n if float(self.entrysmax.get()) < float(self.entrysmin.get()):\n messagebox.showinfo(\"Edit\", 'The maximum and minimum values were swapped.')\n smax = max([float(self.entrysmax.get()), float(self.entrysmin.get())])\n smin = min([float(self.entrysmax.get()), float(self.entrysmin.get())])\n return (smax - smin) / 2, (smax + smin) / 2\n else:\n return float(self.entrysa.get()), float(self.entrysm.get())\n\n def assign_defaults(self):\n string_material = Material(self.entryname.get(), int(self.entrytype.get()[0]), self.entrye_modulus.get(),\n self.entrysu.get(), self.entryflimit.get(),\n self.entryflimitcycles.get(), '', self.entryintercept.get(),\n self.entryslope.get(), '', '', '', '', '', '', '', '', '', '')\n if self.entryflimit.get() == '':\n self.entryflimit.insert(0, string_material.value_or_default(self.entryflimit.get(),\n float(string_material.sf) *\n pow(float(string_material.nfl),\n float(string_material.B))))\n # Default suspended till get_floats\n return string_material\n\n def get_floats(self, string_material):\n used_material = Material(string_material.name, int(string_material.material_type[0]),\n float(string_material.E),\n float(string_material.su), string_material.sfl,\n float(string_material.nfl), '', float(string_material.sf),\n float(string_material.B), '', '', '', '', '', '', '', '', '', '')\n used_material.sfl = float(self.entryflimit.get())\n return used_material\n\n def get_modifying_factors(self):\n ksf = float(Material.value_or_default(self.entryksf.get(), 1))\n kl = float(Material.value_or_default(self.entrykl.get(), 1))\n if self.entryksize['state'] == 'readonly':\n d = float(Material.value_or_default(self.entrydiameter.get(), 1))\n ksize = pow(d / 7.62, -0.1133)\n else:\n ksize = float(Material.value_or_default(self.entryksize.get(), 1))\n\n return ksf, kl, ksize\n\n def get_notch_factor(self, material):\n if self.entrykf['state'] == 'normal':\n kf = float(Material.value_or_default(self.entrykf.get(), 1))\n else:\n kt = float(Material.value_or_default(self.entrykt.get(), 1))\n r = float(Material.value_or_default(self.entryradius.get(), 1))\n a = 0.025 * pow((2070 / material.su), 1.8)\n kf = 1 + (kt - 1) / (1 + (a / r))\n return kf\n\n def get_calculate_data(self):\n root =Tk()\n\n label_11 = Label(root, bg=\"orange\", text=\"Safety Factor = 1.6\", font=(styles.font, 30))\n label_11.grid(row=0)\n root.mainloop()\n \n \n # If from this class calc using sa, sm else calc using stress factor\n \n\n","repo_name":"naf999/Mechanical-engineering","sub_path":"Dynamic.py","file_name":"Dynamic.py","file_ext":"py","file_size_in_byte":16389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"17348572302","text":"from sqlalchemy.ext.mutable import MutableDict\nfrom sqlalchemy import Column, Integer, String, DateTime, ForeignKey, PickleType, Boolean\nfrom db import Base\n\n\nclass User(Base):\n __tablename__ = \"users\"\n\n user_id = Column(Integer, primary_key=True, unique=True)\n first_name = Column(String)\n last_name = Column(String)\n username = Column(String)\n chat_id = Column(Integer)\n emoji = Column(String)\n subscribed = Column(Boolean)\n\n def __repr__(self) -> str:\n return f\"User id: {self.user_id}, name: {self.first_name}\"\n\n\nclass ImagesRating(Base):\n __tablename__ = \"images_rating\"\n\n id = Column(Integer, primary_key=True)\n image_name = Column(String)\n votes = Column(MutableDict.as_mutable(PickleType))\n\n def __repr__(self) -> str:\n return f\"ImagesRating id: {self.id}, name: {self.image_name}\"\n\n\nclass Anketa(Base):\n __tablename__ = \"anketa\"\n\n id = Column(Integer, primary_key=True)\n created = DateTime()\n rate = Column(Integer)\n name = Column(String)\n comment = Column(String)\n user_id = Column(Integer, ForeignKey(User.user_id), index=True, nullable=False)\n\n def update(self, **kwargs) -> None:\n for key, value in kwargs.items():\n if hasattr(self, key):\n setattr(self, key, value)\n\n def __repr__(self) -> str:\n return f\"Anketa id: {self.id}, name: {self.first_name}\"\n","repo_name":"TheMihMih/tr_bot","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"29012955589","text":"# -*- coding:utf-8 -*-\n\nimport pandas as pd\nfrom constants import *\nimport numpy as np\nimport time\n\n\ndef flowIgnoreType(dataFLow):\n # the number of data a day is 144(block) * 4(type)* 2(in_out) * 81(station)\n # ignore type\n size = len(dataFLow)\n days = int(size/DATA_A_DAY)\n dataFLow = np.reshape(dataFLow, (days, DATA_A_DAY))\n temp_gen = np.zeros((days, NUM_TIME_BLOCK * 2 * NUM_STATIONS))\n\n step = NUM_TIME_BLOCK * NUM_TYPES\n # get the in out flow ignore type\n for i in range(days-1, -1, -1):\n for s in range(0, DATA_A_DAY, step):\n temp = np.reshape(dataFLow[i, s: s+step], (NUM_TYPES, NUM_TIME_BLOCK))\n temp_gen[i, int(s/NUM_TYPES): int((s+step)/NUM_TYPES)] = np.sum(temp, axis=0)\n\n return np.reshape(temp_gen, (days * NUM_TIME_BLOCK * 2 * NUM_STATIONS))\n\n\ndef writeToSubmit(preds):\n preds = flowIgnoreType(preds)\n preds = preds * DECAY\n\n submit = pd.read_csv(DATA_PATH_TEST + SUBMIT_FILE)\n\n in_preds = np.zeros((NUM_TIME_BLOCK * NUM_STATIONS))\n out_preds = np.zeros((NUM_TIME_BLOCK * NUM_STATIONS))\n for i in range(0, len(preds), NUM_TIME_BLOCK * 2):\n # print(int(i/2)+NUM_TIME_BLOCK)\n out_preds[int(i/2): int(i/2)+NUM_TIME_BLOCK] = preds[i: i+NUM_TIME_BLOCK]\n in_preds[int(i/2): int(i/2)+NUM_TIME_BLOCK] = preds[i+NUM_TIME_BLOCK: i+NUM_TIME_BLOCK*2]\n\n # the result less than 1 set to 0\n\n in_preds[in_preds < 1] = 0\n out_preds[out_preds < 1] = 0\n\n submit[HEADER_IN] = in_preds\n submit[HEADER_OUT] = out_preds\n\n now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\n path_save = DATA_PATH_PRED + SUBMIT_FILE[:-4] + '_' +now_time + '.csv'\n submit.to_csv(path_save, index=False)\n\n return path_save\n\n","repo_name":"JanzYe/TianchiMetroFlow","sub_path":"code/predToFile.py","file_name":"predToFile.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"43"} +{"seq_id":"14629883481","text":"import json\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\nfrom matplotlib.patches import Circle\nimport mpl_toolkits.mplot3d.art3d as art3d\n\n# agent_colors = ['red', 'purple', 'green', 'blue', 'orange', 'grey', 'yellow', 'pink']\nagent_colors = ['#332288', '#117733', '#44AA99', '#88CCEE', '#DDCC77', '#CC6677', '#AA4499', '#882255']\n\nt_max = 60\n\ndef plot():\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n plot_constraints(ax)\n for i in range(8):\n plot_solution(ax, i)\n\n ax.set_xlim(0, 50)\n ax.set_ylim(0, 50)\n ax.set_zlim(0, 60)\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('t')\n # draw legend\n ob = Line2D([0], [0], marker='o', color='w', label='Obstacle',\n markerfacecolor='black', markersize=15)\n handles = [ob]\n for i in range(8):\n l = 'Disc ' + str(i + 1)\n handle = Line2D([0], [0], marker='o', color='w', label=l,\n markerfacecolor=agent_colors[i], markersize=15)\n handles.append(handle)\n plt.legend(handles=handles)\n\n plt.show()\n\ndef plot_constraints(ax):\n with open('data/query/constraints.json') as f:\n data = json.load(f)\n for constraint in data:\n x = constraint[0]\n y = constraint[1]\n r = constraint[2]\n # Draw a circle on the x=0 'wall'\n p1 = Circle((x, y), r, color='black', alpha=0.6)\n p2 = Circle((x, y), r, color='black', alpha=0.6)\n ax.add_patch(p1)\n ax.add_patch(p2)\n art3d.pathpatch_2d_to_3d(p1, z=0, zdir=\"z\")\n art3d.pathpatch_2d_to_3d(p2, z=t_max, zdir=\"z\")\n # Draw lines between the circles\n num_lines = 32\n angles = np.linspace(0, 2 * np.pi, num_lines, endpoint=False)\n for angle in angles:\n xx = x + r * np.cos(angle)\n yy = y + r * np.sin(angle)\n\n ax.plot([xx, xx], [yy, yy], [0, t_max], color='black', alpha=0.6, linewidth=2)\n\ndef plot_solution(ax, index):\n with open('data/query/solution' + str(index) + '.json') as f:\n data = json.load(f)\n r = 1 # agent radius\n\n num_lines = 8\n angles = np.linspace(0, 2 * np.pi, num_lines, endpoint=False)\n next_i = 0\n for point in data:\n next_i += 1\n x = point[0]\n y = point[1]\n t = point[2]\n # Draw a circle on the x=0 'wall'\n p = Circle((x, y), r, color=agent_colors[index], alpha=0.6)\n ax.add_patch(p)\n art3d.pathpatch_2d_to_3d(p, z=t, zdir=\"z\")\n # Draw lines between the circles\n if next_i < len(data):\n x_next = data[next_i][0]\n y_next = data[next_i][1]\n t_next = data[next_i][2]\n for angle in angles:\n x1 = x + r * np.cos(angle)\n y1 = y + r * np.sin(angle)\n x2 = x_next + r * np.cos(angle)\n y2 = y_next + r * np.sin(angle)\n ax.plot([x1, x2], [y1, y2], [t, t_next], color=agent_colors[index], alpha=0.6, linewidth=2)\n\n\n\nif __name__ == '__main__':\n plot()","repo_name":"frangrothe/bt-motion-planning","sub_path":"visualization/plotmotionquery.py","file_name":"plotmotionquery.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"8138932312","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import division\n\nimport compas_rhino\nfrom compas_ui.ui import UI\nfrom compas_fofin.objects import CableMeshObject\n\n\n__commandname__ = \"FF_cablemesh_modify_edges\"\n\n\n@UI.error()\ndef RunCommand(is_interactive):\n ui = UI()\n\n cablemesh = ui.scene.active_object\n\n if not isinstance(cablemesh, CableMeshObject):\n raise Exception(\"The active object is not a CableMesh.\")\n\n cablemesh.is_valid = False\n ui.scene.update()\n\n edges = ui.controller.mesh_select_edges(cablemesh)\n\n if edges:\n public = [name for name in cablemesh.mesh.default_edge_attributes.keys() if not name.startswith(\"_\")]\n cablemesh.modify_edges(edges, names=public)\n\n ui.scene.update()\n ui.record()\n\n compas_rhino.rs.UnselectAllObjects()\n\n\nif __name__ == \"__main__\":\n RunCommand(True)\n","repo_name":"BlockResearchGroup/compas-FoFin","sub_path":"src/compas_fofin/rhino/ui/FoFin/dev/FF_cablemesh_modify_edges_cmd.py","file_name":"FF_cablemesh_modify_edges_cmd.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"73885043968","text":"\nfrom colomoto_jupyter import IN_IPYTHON, jupyter_setup\n\nif IN_IPYTHON:\n\n def export_entry(d, f, e=None):\n if e is None:\n e = f\n return {\"name\": \"{} (.{})\".format(d, e),\n \"snippet\": ['biolqm.save(lqm, \"mymodel.{}\", \"{}\")'.format(e, f)]}\n\n menu = [\n {\"name\": \"Upload model\",\n \"snippet\": [\"lqm = biolqm.upload()\"]},\n {\"name\": \"Load model\",\n \"snippet\": [\"lqm = biolqm.load(\\\"model.sbml\\\")\"]},\n \"---\",\n {\"name\":\"Export to file\",\n \"sub-menu\": [\n export_entry(\"SBML-qual v1.0\", \"sbml\"),\n \"Functions formats\",\n export_entry(\"BoolNet\", \"bnet\"),\n export_entry(\"BooleanNet\", \"booleannet\"),\n export_entry(\"BoolSim\", \"boolsim\"),\n export_entry(\"Raw Boolean functions\", \"boolfunctions\"),\n export_entry(\"Truth table\", \"tt\"),\n \"Petri net formats\",\n export_entry(\"APNN\", \"apnn\"),\n export_entry(\"INA\", \"ina\"),\n export_entry(\"PNML\", \"pnml\"),\n \"Dedicated formats\",\n export_entry(\"GINML\", \"ginml\"),\n export_entry(\"GNA non-xml\", \"gna\"),\n export_entry(\"MaBoSS\", \"bnd\"),\n export_entry(\"Pint\", \"an\"),\n ]},\n {\"name\":\"Convert to tool\",\n \"sub-menu\": [\n {\"name\": \"GINsim\", \"snippet\": [\n 'lrg = biolqm.to_ginsim(lqm)']},\n {\"name\": \"MaBoSS\", \"snippet\": [\n 'masim = biolqm.to_maboss(lqm)']},\n {\"name\": \"Pint\", \"snippet\": [\n 'an = biolqm.to_pint(lqm)']},\n ]},\n \"---\",\n {\"name\": \"Compute fixpoints\",\n #{\"name\": \"Compute fixpoints (MDD method)\",\n \"snippet\": [\"fps = biolqm.fixpoints(lqm)\"]},\n #{\"name\": \"Compute fixpoints (ASP method)\",\n # \"snippet\": [\"fps = biolqm.fixpoints(lqm, 'asp')\"]},\n {\"name\": \"Compute trap spaces\",\n \"snippet\": [\"traps = biolqm.trapspace(lqm)\"]},\n \"---\",\n {\"name\":\"Model modifications\",\n \"sub-menu\": [\n {\"name\": \"Perturbation\",\n \"snippet\": [\"lqm_mod = biolqm.perturbation(lqm, \\\"node%0\\\")\"]},\n {\"name\": \"Booleanization\",\n \"snippet\": [\"lqm_bool = biolqm.booleanize(lqm)\"]},\n {\"name\": \"Reduction\",\n \"snippet\": [\"lqm_red = biolqm.reduce(lqm, \\\"fixed,output,duplicate\\\")\"]},\n {\"name\": \"Reversal\",\n \"snippet\": [\"lqm_rev = biolqm.reverse(lqm)\"]},\n {\"name\": \"Sanitize\",\n \"snippet\": [\"lqm_san = biolqm.sanitize(lqm)\"]},\n ]},\n \"---\",\n {\"name\": \"Documentation\",\n \"external-link\": \"http://ginsim.naldi.info/biolqm/site/doc/index.html\"}\n ]\n toolbar = [\n {\"name\": \"upload\", \"setup\": {\n \"icon\": \"fa-upload\",\n \"help\": \"Upload model\",\n \"handler\": \"action_upload_model\"}},\n ]\n js_api = {\n \"action_upload_model\": \"\"\"function() {\n var cell = Jupyter.notebook.get_selected_cell();\n cell.set_text('lqm = '+biolqm_jsapi.module_alias+'.upload()');\n cell.focus_editor();\n }\"\"\",\n }\n jupyter_setup(\"biolqm\",\n label=\"bioLQM\",\n color=\"#00007f\", # for menu and toolbar\n menu=menu,\n toolbar=toolbar,\n js_api=js_api)\n\n\n from colomoto_jupyter.upload import jupyter_upload\n def upload():\n return jupyter_upload(\"upload\", \"load\")\n\nelse:\n def upload():\n raise NotImplementedError\n\n","repo_name":"GINsim/GINsim-python","sub_path":"biolqm/jupyter.py","file_name":"jupyter.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"43"} +{"seq_id":"29504585461","text":"import hashlib\nimport uuid\n\nfrom fastapi_plus.service.base import BaseService\nfrom fastapi_plus.utils.obj2dict import obj2dict\nfrom fastapi_plus.utils.redis import RedisUtils\n\nfrom ..dao.user import UserDao\nfrom ..model.user import User\n\n\nclass UserService(BaseService):\n def __init__(self, auth_data: dict = {}):\n user_id = auth_data.get('user_id', 0)\n self.Model = User\n self.dao = UserDao(user_id)\n self.dao.Model = User\n self.redis = RedisUtils()\n # self.wxapp = WxappUtils()\n\n super().__init__(user_id, auth_data)\n\n def login_by_code(self, code: str):\n \"\"\"\n 通过微信登录code进行登录\n :param code:\n :return:\n \"\"\"\n\n # data = self.wxapp.jscode2session(code)\n #\n # if 'openid' not in data:\n # return {\n # 'code': 500,\n # 'message': '错误:jscode2session'\n # }\n #\n # return self.login_by_openid(data['openid'])\n pass\n\n def login_by_token(self, token: str):\n \"\"\"\n 通过自产token进行登录\n :param token:\n :return:\n \"\"\"\n\n data = self.redis.get('token:' + token)\n\n if not data:\n return {\n 'code': 500,\n 'message': '错误:token错误'\n }\n\n # 删除当前token,因为会重新创建\n self.redis.delete('token:' + token)\n\n return self._login_by_id(data['user']['id'])\n\n def login_by_openid(self, openid: str):\n \"\"\"\n 通过openid进行登录\n :param openid:\n :return:\n \"\"\"\n # user = self.dao.read_by_openid(openid)\n user = None\n\n if not user:\n user = User()\n user.openid = openid\n self.dao.create(user)\n\n return self._login_success(user)\n\n def _login_success(self, user):\n token = str(user.id) + str(uuid.uuid1())\n\n data = {\n 'token': token,\n 'user_id': user.id,\n 'user': obj2dict(user),\n }\n\n self.redis.set('token:' + token, data, 360000)\n\n return data\n\n def _login_by_id(self, id: int):\n \"\"\"\n 通过id进行登录\n :param openid:\n :return:\n \"\"\"\n\n user = self.dao.read(id)\n\n if not user:\n return {\n 'code': 2008061621,\n 'message': '用户不存在'\n }\n\n return self._login_success(user)\n\n def login_by_password(self, username: str, password: str):\n \"\"\"\n 通过username、password进行登录\n :param username:\n :param password:\n :return:\n \"\"\"\n\n user = self.dao.read_by_username(username)\n\n if not user:\n return {\n 'code': 2008061621,\n 'message': '用户不存在'\n }\n\n if user.password != hashlib.md5((user.name + password).encode(encoding='UTF-8')).hexdigest():\n return {\n 'code': 2008061622,\n 'message': '密码错误'\n }\n\n return self._login_success(user)\n","repo_name":"zhenqiang-sun/fastapi_demo","sub_path":"app/service/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"43"} +{"seq_id":"31632044504","text":"import xarray as xr\n\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport matplotlib.animation as animation \n\nfile = 'history.nc'\nvariable = 'p'\nxmin, xmax = 0, 4\nymin, ymax = 0, 2\n\nds = xr.open_dataset(file)\n\n# This part is a fast adaptation of the window shape\nny, nx = ds[variable][0].shape\nif nx == ny:\n shape_window = (8,8)\nelse:\n shape_window = (12,5)\n \nfps = 10 #Set up the number of image / second (animation speed)\nsnapshots = ds[variable]\n\n# First set up the figure, the axis, and the plot element we want to animate\nfig = plt.figure( figsize=shape_window )\na = snapshots[0]\nim = plt.imshow(a.T, cmap='coolwarm', extent=[xmin,xmax,ymin,ymax]) \nplt.xlabel('X')\nplt.ylabel('Y')\nplt.clim(-1,1) #Set up here the limits of colorbar\nplt.colorbar(label=variable)\n\ndef animate_func(i):\n if i % fps == 0:\n print( '.', end ='' )\n\n im.set_array(snapshots[i])\n return [im]\n\nanim = animation.FuncAnimation(\n fig, \n animate_func, \n frames = len(ds[variable]),\n interval = 1000 / fps, # in ms\n )\nanim.save('animation.gif', writer='PillowWriter')\n\nprint('Done!')","repo_name":"pvthinker/wave2d","sub_path":"script_read_netcdf.py","file_name":"script_read_netcdf.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"43"} +{"seq_id":"26621688248","text":"##word = ['a','e','b','e','c','g']\n## #e b e c g\n##c=0\n##a=1\n##\n##for i in range(c,len(word)):\n## #print(\"c= \",c,'\\n')\n## c+=1\n## for j in range(a,len(word)):\n## #print(\"a=\",a)\n## if (word[i] == word[j]): \n## print(\"This string does not contain all unique characters\")\n## break\n## else:\n## print(\"all unique\", word[i], word[j])\n## a+=1\n\n\n\n\ndef checkUnique(n):\n a = [] # create empty list \n for i in n: \n if i in a: #check to see if same element is in a. return true if it is\n return True\n else:\n a.append(i) # if not append the element from list to list a\n return False\n \nb = ['c','a','1']\n\nresult = checkUnique(b)\n\nif result:\n print(\"yes these characters are unique\")\nelse:\n print(\"no they are not unique\")\n \n \n\n\n","repo_name":"Gering112/Algorithms","sub_path":"Arrays and Strings/isUnique(1.1).py","file_name":"isUnique(1.1).py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"34441327260","text":"from django.contrib.auth.models import Group, User\nfrom rest_framework.permissions import IsAdminUser\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\n\nclass UserAnalytics(APIView):\n\n\n permission_classes = [IsAdminUser]\n\n\n def get(self, request: Request):\n\n totalCount = User.objects.all().count()\n adminCount = User.objects.filter(is_staff=True).count()\n coachGroup, created = Group.objects.get_or_create(name='Coach')\n coachCount = coachGroup.user_set.all().count()\n normal = User.objects.exclude(is_staff=True).exclude(groups__name__contains='Coach')\n normalCount = normal.count()\n\n data = {\n 'total_count': totalCount,\n 'admin_count': adminCount,\n 'coach_count': coachCount,\n 'normal_count': normalCount\n }\n\n return Response(data, status=200)\n\n\n","repo_name":"ThatGenericName/CSC309-Project-Full","sub_path":"PF/BackendFiles/accounts/Views/adminanalytics.py","file_name":"adminanalytics.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"7949131256","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy \nfrom flask_migrate import Migrate, MigrateCommand #to migrate the data with command db\n#from flask_script import Manager\nfrom flask_uploads import UploadSet, configure_uploads, IMAGES #uploads not working instead , reuploaded is working\nfrom flask_login import LoginManager\n\napp = Flask(__name__)\n\n#instantiate\nphotos = UploadSet('photos', IMAGES)\n\napp.config['UPLOADED_PHOTOS_DEST'] = 'images'\n#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///C:/Users/User/Desktop/twitter-clone/engage.db'\n#app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/new_clone'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://uhmmfxnusjcuzn:c2fe993a81dd023ab9017003349aff9e1c110f65239749cb8a2b3b16907eb058@ec2-44-205-112-253.compute-1.amazonaws.com:5432/dbpkmc0aiuhrba'\napp.config['DEBUG'] = True\napp.config['SECRET_KEY'] = 'ksdlfkdsofidsithnaljnfadksjhfdskjfbnjewrhewuirhfsenfdsjkfhdksjhfdslfjasldkj' #cross seite request handling\n\n#instantitate\nlogin_manager = LoginManager(app)\nlogin_manager.login_view = 'login'\n\nconfigure_uploads(app, photos)\n\n#instantitate\ndb = SQLAlchemy(app)\nmigrate = Migrate(app, db)\n\n@app.template_filter('time_since')\ndef time_since(delta):\n\n seconds = delta.total_seconds()\n\n days, seconds = divmod(seconds, 86400)\n hours, seconds = divmod(seconds, 3600)\n minutes, seconds = divmod(seconds, 60)\n\n if days > 0:\n return '%dd' % (days)\n elif hours > 0:\n return '%dh' % (hours)\n elif minutes > 0:\n return '%dm' % (minutes)\n else:\n return 'Just now'\n\n\nfrom views import *\n\n#command attached with db\n# manager = Manager(app)\n# manager.add_command('db', MigrateCommand)\n\nif __name__ == '__main__':\n app.run()","repo_name":"AshishAgnihotri996/project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"21176264794","text":"\"\"\"\nSaveSalstatNative\n\nA module to save in a native XML format for Salstat\n(c) 2013, Alan James Salmoni\n\"\"\"\n\nimport numpy\nimport datetime, pickle\nfrom BeautifulSoup import BeautifulStoneSoup\n\n\ndef MakeString(vector):\n # returns a string representation of a numpy vector\n return ','.join([str(scal) for scal in vector])\n\ndef MakeVector(string):\n return numpy.array([float(scal) for scal in string.split(',')])\n\ndef Label(key_value_pairs):\n num_labels = len(key_value_pairs)\n label_xml = ''\n for label in key_value_pairs:\n ln = '\\t\\t\\t\\n'%(label, key_value_pairs[label])\n label_xml = label_xml + ln\n return label_xml\n\ndef Data(data):\n data_str = pickle.dumps(data)\n ln = '\\t\\t\\t%s\\n\\t\\t\\t\\n'%(data_str)\n return ln\n\ndef Variable(name, ivdv, labels, missingvalues, align, measure, data):\n labels_xml = Label(labels)\n data_xml = Data(data)\n var_xml = '\\t\\t\\n\\t\\t\\t%s\\n'%(name)\n var_xml = var_xml + '\\t\\t\\t%s\\n'%(ivdv)\n var_xml = var_xml + labels_xml\n var_xml = var_xml + '\\t\\t\\t%s\\n'%(missingvalues)\n var_xml = var_xml + '\\t\\t\\t%s\\n'%(align)\n var_xml = var_xml + '\\t\\t\\t%s\\n'%(measure)\n var_xml = var_xml + data_xml + '\\t\\t\\n'\n return var_xml\n\ndef Variables(variables):\n vars_xml = '\\t\\n'\n for var in variables:\n var_xml = Variable(var.name, var.ivdv, var.labels, var.missingvalues, \\\n var.align, var.measure, var.data)\n vars_xml = vars_xml + var_xml\n vars_xml = vars_xml + '\\t\\n'\n return vars_xml\n\ndef NativeDoc(version, fname, variables):\n now = datetime.date.today()\n date_str = now.strftime(\"%Y-%m-%d\")\n # convert to human-readable format\n variables = Variables(variables)\n initial_xml = '\\n\\t%s\\n\\t%s\\\n \\n\\t%s\\n'%(version, fname, date_str)\n ending_xml = '%s'%variables\n return initial_xml + ending_xml\n\nclass variableobj(object):\n def __init__(self, name):\n self.name = name\n\ndef SaveNativeDoc(grid, filename):\n # default suffix is .xml\n ColsUsed, colnums = grid.GetUsedCols()\n vars = []\n for col in colnums:\n var_name = grid.GetColLabelValue(col)\n var = variableobj(var_name)\n var.labels = {}\n var.data = grid.CleanData(col)\n var.ivdv = \"Not set\"\n var.missingvalues = \"Not set\"\n var.measure = \"Not set\"\n var.align = \"Not set\"\n n = NativeDoc(\"20131022\", filename, vars)\n try:\n fout = open(filename, 'w')\n fout.write(n)\n fout.close()\n except:\n pass\n\ndef LoadNativeDoc(grid, filename):\n try:\n fin = open(filename, 'r')\n data = fin.read()\n fin.close()\n soup = BeautifulStoneSoup(data)\n vars = soup.findAll('variable')\n for idx, var in enumerate(vars):\n var_name = var('name')[0].text\n var_ivdv = var('ivdv')[0].text\n var_align = var('align')[0].text\n var_missingvalues = var('missingvalues')[0].text\n var_data = var('data')[0].text\n grid.SetColLabelValue(idx, var_name)\n vector = pickle.loads(var_data)\n for row in range(len(vector)):\n grid.SetCellValue(row, idx, vector[row])\n # cannot do any others just yet! \n # Need to have meta data in the grid\n except: # specific exception?\n data = \"\"\n\n\nif __name__ == '__main__':\n var1 = variableobj('Var001')\n var2 = variableobj('Var002')\n var3 = variableobj('Var003')\n var1.labels = {1: 'Label 1', 2: 'Label 2','a':'Label a'}\n var2.labels = {1: 'Label a', 2: 'Label b','a':'Label 123'}\n var3.labels = {1: 'Label 1', 2: 'Label 2','a':'Label 456'}\n #print Label(labels)\n var1.data = numpy.array(([2,3.4,4,3.565,7]))\n var2.data = numpy.array(([2,3.4,4,3.565,7]))\n var3.data = numpy.array(([2,3.4,4,3.565,7]))\n var1.ivdv = 'Not yet'\n var2.ivdv = 'IV'\n var3.ivdv = 'DV'\n var1.missingvalues = 'None yet'\n var2.missingvalues = '-99'\n var3.missingvalues = 'Missing'\n var1.align = 'left'\n var2.align = \"CENTRE\"\n var3.align = \"Right\"\n var1.measure = \"Ordinal\"\n var2.measure = \"INTERVAL\"\n var3.measure = \"nominal\"\n vars = [var1, var2, var3]\n \"\"\"\n n = NativeDoc(\"20131022\",'filename001',vars)\n fout = open('/Users/alansalmoni/sal.xml','w')\n fout.write(n)\n fout.close()\n \"\"\"\n vec = numpy.random.rand(400)\n vecstr = MakeString(vec)\n strvec = MakeVector(vecstr)\n\n","repo_name":"salmoni/Salstat","sub_path":"SaveSalstatNative.py","file_name":"SaveSalstatNative.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"43"} +{"seq_id":"3621335555","text":"with open(\"input.txt\", \"r\", encoding=\"koi8_r\") as f, open(\"output.txt\", \"w\", encoding=\"koi8_r\") as q:\n n = int(f.readline())\n p = [int(x) - 1 for x in f.readline().split()]\n s = f.readline().strip()\n m = len(s)\n t = [None for i in range(m)]\n g = (x for x in s)\n for i in range(n):\n for j in range(p[i], m, n):\n t[j] = next(g)\n q.write(''.join(t))\n","repo_name":"dm-alexi/acmp","sub_path":"0401_0500/0458/0458.py","file_name":"0458.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"25336841940","text":"import boto3\nimport logging\nfrom datetime import datetime\n\n\ndef lambda_handler(event, context):\n # Logging\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n # logger.setLevel(logging.DEBUG)\n logging.getLogger(\"botocore\").setLevel(logging.ERROR)\n\n logger.debug(f'event: {event}')\n logger.debug(f'context: {context}')\n\n # Setup Connection\n try:\n session = boto3.Session()\n ec2_client = session.client('ec2')\n except Exception as e:\n logger.error(f'Failed creating session')\n logger.error(f'e: {e}')\n raise e\n\n # Shutdown EC2 Instances\n try:\n instances = ec2_client.describe_instances()\n for res in instances['Reservations']:\n for instance in res['Instances']:\n instance_id = instance['InstanceId']\n instance_tags = instance['Tags']\n try:\n response = shut_down_instance(\n ec2_client,\n instance_id,\n instance_tags\n )\n if response:\n logger.info(f'Enforcing Stopped State {instance_id}...')\n tag_ec2(\n ec2_client,\n instance_id,\n \"LastAutomatedShutDownReason\",\n \"AutoShutDown - \" + str(datetime.now()) + ' UTC'\n )\n except Exception as e:\n logger.info(f'{instance_id} is already in a Stopped or Stopping state')\n logger.error(f'e: {e}')\n except Exception as e:\n logger.error(f'Failed describing instances')\n logger.error(f'e: {e}')\n raise e\n\n\ndef shut_down_instance(\n ec2_client,\n instance_id,\n tags\n):\n \"\"\"\n Execute API Stop command to any EC2 Instance with AutoShutDown:True in Tags\n :param ec2_client: boto3.client\n :param instance_id: (String) the instance to check for AutoShutDown tag value\n :param tags: (String) the instance's tags to parse through\n :return: bool\n \"\"\"\n for tag in tags:\n if \"AutoShutDown\" in tag['Key']:\n if tag['Value'].lower() == \"true\":\n ec2_client.stop_instances(\n InstanceIds=[\n instance_id\n ]\n )\n return True\n\n\ndef tag_ec2(\n ec2_client,\n instance_id,\n tag_name,\n tag_value\n):\n \"\"\"\n Added a specified tag to an EC2 instance\n :param ec2_client: boto3.client\n :param instance_id: (String) the EC2 instance to tag\n :param tag_name: (String) the Name for the tag being added\n :param tag_value: (String) the Value for the tag being added\n :return: None\n \"\"\"\n ec2_client.create_tags(\n Resources=[\n instance_id,\n ],\n Tags=[\n {\n 'Key': tag_name,\n 'Value': tag_value\n },\n ]\n )\n","repo_name":"danguerra8282/examples","sub_path":"python_scripts/autoshutdown_ec2.py","file_name":"autoshutdown_ec2.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"34747043068","text":"import socket\n\nTCP_PORT = 5005 # The port to use.\nBUFFER_SIZE = 1024 # Packet size - 1024 is standard.\n\n\ndef server_socket(tcp_ip, tcp_port):\n # Create a socket object\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:\n # bind the socket to the tcp address and port and start to listen\n sock.bind((tcp_ip, tcp_port))\n sock.listen()\n print(f'# Server Initialising on {tcp_ip}:{tcp_port}')\n print('# Awaiting connection...')\n tcp_ip = socket.gethostbyname(socket.gethostname())\n print(f'TCP IP is {tcp_ip}')\n # wait for a client to connect\n conn, addr = sock.accept()\n print(f'# A client on: {addr} has connected.')\n # process all incoming data from the client....\n while True:\n data = conn.recv(BUFFER_SIZE)\n message = input('Enter a message to send to the client: ')\n if data:\n print(f'# Received: {data.decode()}')\n # send a confirmation to the client\n conn.sendall(f'Server: {message}'.encode())\n # conn.sendall('Got that thanks!'.encode())\n else:\n print('# End of Data - Socket Exiting...')\n break\n\n conn.close()\n \n\ndef main():\n tcp_ip = socket.gethostbyname('localhost')\n server_socket(tcp_ip, TCP_PORT)\n\n\nif __name__ == '__main__':\n main()","repo_name":"Traverse-Technology/python_basic","sub_path":"Python Networking/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"21630199480","text":"import torch\nimport wandb\n\nfrom Trainer import Trainer\n\nMAX_SUMMARY_IMAGES = 4\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nassert torch.cuda.is_available()\n\n# LR = 2e-4\nEPOCHS = 100\n# BATCH_SIZE = 64\nNUM_WORKERS = 4\n# LAMBDA_L1 = 100\n\nsweep_config = {\n 'method': 'bayes', # grid, random\n 'metric': {\n 'name': 'loss_g',\n 'goal': 'minimize'\n },\n 'parameters': {\n 'lambda_l1': {\n 'values': [80, 90, 100, 110, 120, 130]\n },\n 'batch_size': {\n 'values': [64]\n },\n 'learning_rate': {\n 'values': [1e-5, 1e-4, 2e-4, 3e-4]\n }\n }\n}\n\nif __name__ == '__main__':\n def train_wrapper():\n wandb.init()\n config = wandb.config\n print(f'Config: {config}')\n\n trainer = Trainer(\n lr=config.learning_rate,\n device=DEVICE,\n batch_size=config.batch_size,\n epochs=EPOCHS,\n lambda_l1=config.learning_rate,\n dataloader_num_workers=NUM_WORKERS,\n max_summary_images=MAX_SUMMARY_IMAGES\n )\n trainer.train()\n\n sweep_id = wandb.sweep(sweep_config, project=\"poke-gan\")\n wandb.agent(sweep_id, train_wrapper)\n","repo_name":"Laleee/poke-gan","sub_path":"training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"29080375064","text":"# pylint: disable=no-member\n\"\"\"Ultimately prepares data.json with a few utility classes\"\"\"\n\nimport json\nfrom functools import reduce\n\nfrom pandas import read_csv\n\nprint(\">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n\n\nclass ProductProperty:\n \"\"\"Enum values.\"\"\"\n\n COMPOSITION = \"composition\"\n COST = \"cost\"\n DATE = \"date\"\n DEMAND = \"demand\"\n INGREDIENTS_wORTH = \"ingredientsWorth\"\n IS_WORTH_IT = \"isWorthIt\"\n MERCHANDISABLE = \"merchandisable\"\n NAME = \"name\"\n PROFIT = \"profit\"\n PRICE = \"price\"\n TOTAL_COST = \"totalCost\"\n TOTAL_PROFIT = \"totalProfit\"\n PRICE_ADJUSTMENT = \"priceAdjustment\"\n\nproducts = []\nmax_ingredients = 4\n\n\nclass Products:\n \"\"\"A utility class to prepare data.json from data.csv file.\"\"\"\n\n @staticmethod\n def prepare_products():\n \"\"\"Prepares products from a csv file.\"\"\"\n global products\n global max_ingredients\n\n converters = {\n \"cost\": int,\n \"date\": int,\n \"ingredient_1\": str,\n \"ingredient_2\": str,\n \"ingredient_3\": str,\n \"ingredient_4\": str,\n \"price\": int,\n \"manufacturedAt\": str,\n \"soldAt\": str\n }\n\n products = read_csv(\"src/data/products.csv\", delimiter='\\t',\n converters=converters).to_dict(orient=\"records\")\n\n for product in products:\n product[ProductProperty.COMPOSITION] = list()\n\n for i in range(1, max_ingredients + 1):\n ingredient = \"ingredient_\" + str(i)\n\n if product[ingredient] is not \"\":\n product[ProductProperty.COMPOSITION].append(\n product[ingredient])\n\n product.pop(ingredient, None)\n\n # Ingredients have been consolidated into an array so we can calculate\n # price points\n\n for index, product in enumerate(products):\n product[\"index\"] = index\n product[ProductProperty.DEMAND] = 1\n product[ProductProperty.PRICE_ADJUSTMENT] = 100\n\n product[ProductProperty.TOTAL_COST] = Products.total_cost(\n product[ProductProperty.NAME])\n product[ProductProperty.PROFIT] = product[\n ProductProperty.PRICE] - product[ProductProperty.TOTAL_COST]\n product[ProductProperty.TOTAL_PROFIT] = product[\n ProductProperty.PROFIT] * product[ProductProperty.DEMAND]\n product[ProductProperty.INGREDIENTS_wORTH] = Products.ingredients_worth(\n product[ProductProperty.NAME])\n product[ProductProperty.IS_WORTH_IT] = Products.is_worth_it(\n product[ProductProperty.NAME])\n\n index += 1\n\n with open(\"src/data/products.json\", \"w\") as file:\n json.dump(products, file, indent=\"\\t\")\n\n @staticmethod\n def get_composition(name):\n \"\"\"Returns the composition list of a product.\"\"\"\n\n return Products.get_property(name, ProductProperty.COMPOSITION)\n\n @staticmethod\n def get_cost(name):\n \"\"\"Returns the bare cost of manufacturing a product.\"\"\"\n\n return Products.get_property(name, ProductProperty.COST)\n\n @staticmethod\n def get_price(name):\n \"\"\"Returns the price of a product.\"\"\"\n\n return Products.get_property(name, ProductProperty.PRICE)\n\n @staticmethod\n def get_property(name, prop):\n \"\"\"Returns the value of a given property for a product.\"\"\"\n\n return Products.get_product(name)[prop]\n\n @staticmethod\n def get_product(name):\n \"\"\"Returns a product object from a name.\"\"\"\n\n for product in products:\n if product[\"name\"] == name:\n return product\n\n @staticmethod\n def total_cost(name):\n \"\"\"Returns the total cost of manufacturing a product.\"\"\"\n return reduce(lambda lastCost, newCost: lastCost + newCost, map(Products.total_cost, Products.get_composition(name)), Products.get_cost(name))\n\n @staticmethod\n def ingredients_worth(name):\n \"\"\"Returns the total price of the ingredients of a product.\"\"\"\n return reduce(lambda lastPrice, newPrice: lastPrice + newPrice, map(Products.get_price, Products.get_composition(name)), 0)\n\n @staticmethod\n def is_worth_it(name):\n \"\"\"Returns if a product is worth the cost of its ingredients.\"\"\"\n return Products.get_property(name, ProductProperty.PROFIT) >= Products.ingredients_worth(name)\n\nProducts.prepare_products()\n","repo_name":"kubarium/industry-giant-2","sub_path":"dataminer.py","file_name":"dataminer.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"27506278644","text":"#creating new arr square root using for loop\n\nfrom array import*\n\nvals=array('i',[10,20,30,40,50])\n\nnewArr=array(vals.typecode, (a*a for a in vals))\n\nfor i in newArr:\n print(i)","repo_name":"SatyamPrince/Python","sub_path":"Array/#creating new arr square root using for .py","file_name":"#creating new arr square root using for .py","file_ext":"py","file_size_in_byte":179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"5307610438","text":"import os\nimport csv\n\nelection_csv = (\"election_data.csv\")\n\n\ntotal_votes = 0\n#candidate = 0\ncandidate_list = []\n#vote_percent = []\nvote_count = []\n\n\nwith open (election_csv, 'r') as csvfile:\n\n csvreader = csv.reader(csvfile, delimiter=',')\n\n header = next(csvreader)\n\n for row in csvreader:\n\n total_votes = total_votes + 1\n candidate = row[2]\n\n if candidate in candidate_list:\n candidate_index = candidate_list.index(candidate)\n vote_count[candidate_index] = vote_count[candidate_index] + 1\n\n else:\n candidate_list.append(candidate)\n vote_count.append(1)\n\nvote_percent = []\nmax_votes = vote_count[0]\nmax_index = 0\n\nfor x in range(len(candidate_list)):\n total_vote_percent = round(vote_count[x]/total_votes*100, 2)\n vote_percent.append(total_vote_percent)\n\n if vote_count[x] > max_votes:\n max_votes = vote_count[x]\n max_index = x\n\nelection_winner = candidate_list[max_index]\n\nprint(\"Election Results\")\nprint(\"-----------------\")\nprint(f\"Total Votes: {total_votes}\")\nprint(\"-----------------\")\nfor x in range(len(candidate_list)):\n print(f\"{candidate_list[x]}: {vote_percent[x]}% ({vote_count[x]})\")\nprint(\"-----------------\")\nprint(f\"Winner: {election_winner}\")\nprint(\"-----------------\")\n\nwith open('PyPollAnalysis.txt', 'w') as text:\n text.write(\"Election Results\" + \"\\n\")\n text.write(\"-----------------\\n\")\n text.write(f\"Total Votes: {total_votes}\"\"\\n\")\n text.write(\"-----------------\\n\")\n for x in range(len(candidate_list)):\n text.write(f\"{candidate_list[x]}: {vote_percent[x]}% ({vote_count[x]})\"\"\\n\")\n text.write(\"-----------------\\n\")\n text.write(f\"Winner: {election_winner}\"\"\\n\")\n text.write(\"-----------------\\n\")","repo_name":"mrose115/Python-Challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"5915827539","text":"# define here what is a job\n# expect two different ones\n# - python function \n# - arbitrary executable\nfrom __future__ import print_function\nfrom . import server\nfrom .tools import get_uniq, minitee,mkdir_safe\nimport subprocess as sbp\nimport shlex\nimport time \nfrom . import pinc_defaults\nimport os.path as osp\nimport os\nimport re\nimport sys\nimport stat\nimport os\n\nclass extfile:\n def __init__(self,name,*agrs,**kargs):\n self.name=name\n def close(self):\n pass\n\nclass parfile(extfile):\n def __init__(self,name,sep = \"=\",listtype = \"concatenate\",listsep = \" \",list_counter = \"\",list_nm=\"\",list_startat=1):\n self.name = get_uniq(name,osp.exists)\n f=open(self.name,\"w\")\n f.close()\n self.pf = {}\n self.sep = sep\n self.listtype = listtype\n self.listsep = listsep\n self.list_nm = list_nm\n self.list_counter = list_counter\n self.list_startat = list_startat\n\n def set(self,**ka):\n self.pf.update(ka)\n def set_from(self,pars,*keys):\n self.set(**dict([(k,getattr(pars,k)) for k in keys if k in pars]))\n\n def close(self):\n f = open(self.name,\"w\")\n for k,vl in self.pf.items():\n if isinstance(vl,(str,int,float,bool,complex)):\n print(\"%s %s %s\"%(k,self.sep,vl),file=f)\n else:\n nvl = list(vl)\n if self.listtype == \"concatenate\":\n svl = self.listsep.join(str(v) for v in nvl)\n print(\"%s %s %s\"%(k,self.sep,svl),file=f)\n else:\n for i,v in itemize(nvl):\n print(\"%s%s%d %s %s\"%(k,self.list_nm,i+self.liststartat,self.sep,v),file=f)\n print(\"%s %s %d\"%(self.list_counter,self.sep,len(svl)))\n f.close()\n\n\nclass job:\n\n def incdb(self,fi,*content):\n f = open(osp.join(self.kargs[\"dirpath\"],fi),\"a\")\n print(*content,file=f)\n f.close()\n def logdb(self,pid):\n self.incdb(self.__class__.__name__+\".db\",self.get_label(),pid)\n\n def wait(self):\n return self.wrk.wait(self)\n\n def safe(self):\n wrk = self.wrk\n self.wrk = None\n return wrk\n def unsafe(self,buf):\n self.wrk = buf\n\n def get_dependency(self):\n dep = self.kargs.get(\"after\",())\n if isinstance(dep,str):\n return (dep,)\n return dep\n def get_label(self):\n return self.kargs[\"label\"]\n def get_alias(self):\n return self.kargs[\"alias\"]\n def get_logfile(self):\n return self.kargs[\"logfile\"]\n\n def set_cmd(self,cmd):\n self.kargs[\"cmd\"] = cmd\n\n def new_parfile(self,label,**kargs):\n self.kargs[\"extra\"][label] = parfile(self.create_file(\".par\"),**kargs)\n return self.kargs[\"extra\"][label]\n\n def new_file(self,label=\"\",ext=\"\",prefix=\"\",suffix=\"\",tmp=False):\n fi = (create_file(ext=ext,prefix=prefix,suffix=suffix,tmp=tmp))\n if label:\n self.kargs[\"extra\"][label] = fi\n return fi\n\n\n def __init__(self,wrk,**kargs):\n self.wrk = wrk\n self.kargs = {\n \"cmd\":\"sleep 10\",\n \"logfile\":\"\",\n \"after\":(),\n \"submit\":\"\",\n \"release\":\"\",\n \"kill\":\"\",\n \"extra\":{},\n \"alias\":[]\n }\n self.kargs.update(pinc_defaults.job_defaults)\n self.kargs.update(kargs)\n self.last_status = \"\"\n self.sbm = False\n mkdir_safe(self.get_dirpath())\n\n def add_alias(self,*alias):\n self.kargs[\"alias\"].extend(tuple(alias))\n\n def get_dirpath(self):\n return osp.join(self.kargs[\"dirpath\"],self.kargs[\"label\"])\n def get_tmp(self):\n return osp.join(self.kargs[\"dirpath\"],\"tmp\")\n def get_dirortmp(self,tmp):\n if tmp:\n return self.get_tmp()\n return self.get_dirpath()\n\n def get_cmd(self):\n cmd = self.kargs[\"cmd\"]\n if isinstance(cmd,str):\n cmd = [cmd]\n\n lcmd = []\n for rcmd in cmd:\n ccmd = rcmd\n if isinstance(rcmd,str):\n ccmd = shlex.split(rcmd)\n for i,cc in enumerate(ccmd):\n for ex,pf in self.kargs[\"extra\"].items():\n if isinstance(pf,extfile):\n pf.close()\n ccmd[i] = cc.replace(\"@%s\"%ex,pf.name)\n else:\n ccmd[i] = cc.replace(\"@%s\"%ex,pf)\n lcmd += [ccmd]\n return lcmd\n\n def register(self,master):\n buf = self.safe()\n msg = master.add_job(self)\n self.unsafe(buf)\n self.sbm=True\n return msg\n\n def create_file(self,ext=\"\",prefix=\"\",suffix=\"\",karg_name=\"\",tmp=False):\n dp = self.get_dirortmp(tmp)\n fn = get_uniq(osp.join(dp,prefix+self.kargs[\"label\"]+suffix),lambda l:osp.exists(l+ext))+ext\n if karg_name:\n self.kargs[karg_name] = fn\n return fn \n\n def create_srkfiles(self):\n submit_file = self.create_file(\".submit\",\"submit\")\n release_file = self.create_file(\".release\",\"release\")\n kill_file = self.create_file(\".kill\",\"kill\")\n return submit_file,release_file,kill_file\n\n def make_exec(self,fname,content,shebang=\"shell\"):\n shb = {\"shell\":\"#! /bin/sh\",\n \"python\":\"#! %s\"%sys.executable}\n\n content = shb.get(shebang,shebang).strip()+\"\\n\"+content\n f=open(fname,\"w\")\n print(content,file=f)\n f.close()\n os.chmod(fname,stat.S_IMODE(os.stat(fname)[0]) | stat.S_IXUSR)\n\n def submit(self,runnercmd):\n # this would submit the code\n # return None or a sbp.Popen object (to be clenedup) and an id string\n return None,\"\"\n\n def release(self,runnercmd,submitid):\n rchild = sbp.Popen(shlex.split(runnercmd))\n self.logdb(rchild.pid)\n return rchild,submitid\n\n def kill(self,submitid):\n return\n\nclass barrier(job):\n def __init__(self,wrk,**kargs):\n job.__init__(self,wrk,**kargs)\n self.kargs[\"cmd\"] = \"sleep 0\"\n def is_barrier(self):\n return True\n\nclass fakeqsubjob(job):\n \n def __init__(self,wrk,**kargs):\n job.__init__(self,wrk,**kargs)\n \n self.submit_file,self.release_file,self.kill_file = self.create_srkfiles()\n\n def submit(self,runnercmd):\n self.make_exec(self.submit_file,\"echo 1\")\n submitid = sbp.check_output([self.submit_file,runnercmd],shell=True).decode(\"utf-8\")\n return None,submitid\n\n def release(self,runnercmd,submitid):\n self.make_exec(self.release_file,\"nohup $2 1> /dev/null 2>/dev/null 14:\n label = label[:13]+\"X\"\n qsub_options[\"-N\"] = label\n qsub_options.update(self.kargs.get(\"qsub_options\",{}))\n self.kargs[\"qsub_options\"] = qsub_options\n self.kargs[\"qsub_env\"] = self.kargs.get(\"qsub_env\",{})\n self.kargs[\"qsub_before\"] = self.kargs.get(\"qsub_before\",[])\n self.kargs[\"qsub_after\"] = self.kargs.get(\"qsub_after\",[])\n\n def submit(self,runnercmd):\n batch_file = self.create_file(\".qsub\",\"qsub\")\n\n txt = \"\"\n\n for k in self.kargs[\"qsub_options\"]:\n txt+=\"#PBS %s %s\\n\"%(k,self.kargs[\"qsub_options\"][k])\n for k in self.kargs[\"qsub_env\"]:\n txt+=\"export %s=%s\\n\"%(k,self.kargs[\"qsub_env\"][k])\n txt+=\"cd %s\\n\"%os.getcwd()\n for l in self.kargs[\"qsub_before\"]:\n txt+=l+\"\\n\"\n txt+=runnercmd+\"\\n\"\n for l in self.kargs[\"qsub_after\"]:\n txt+=l+\"\\n\"\n self.make_exec(batch_file,txt)\n submitid = sbp.check_output([\"qsub\",\"-h\",batch_file]).decode(\"utf-8\")\n \n \n submitid = submitid.split(\".\")[0]\n self.incdb(\"qsubid\",submitid)\n self.logdb(submitid)\n return None,submitid \n\n def release(self,runnercmd,submitid):\n sbp.check_output([\"qrls\",submitid]).decode(\"utf-8\")\n return None,submitid\n\n def kill(self,submitid):\n sbp.check_output([\"qdel\",submitid]).decode(\"utf-8\")\n\n_python_rcmd = \"\"\"\nimport sys\nsys.path = %s+sys.path\nprint(sys.path)\nimport marshal\nimport types\nprint(\"toto\")\nfunc_code = marshal.loads(%s)#.decode(\"base64\"))\nargs = marshal.loads(%s)#.decode(\"base64\"))\nkargs = marshal.loads(%s)#.decode(\"base64\"))\nprint(\"tata\")\nfunc = types.FunctionType(func_code,globals())\nfunc(*args,**kargs)\nprint (\"toto\")\n\"\"\"\n\ndef python_cmd(func,args,kargs={},use_sys_path=True):\n import marshal\n #func_s = repr(marshal.dumps(func.__code__).encode(\"base64\"))\n #args_s = repr(marshal.dumps(args).encode(\"base64\"))\n #kargs_s = repr(marshal.dumps(kargs).encode(\"base64\"))\n func_s = repr(marshal.dumps(func.__code__))#.encode(\"base64\"))\n args_s = repr(marshal.dumps(args))#.encode(\"base64\"))\n kargs_s = repr(marshal.dumps(kargs))#.encode(\"base64\"))\n spath = []\n if use_sys_path:\n import sys\n spath = sys.path\n ext = _python_rcmd%(spath,func_s,args_s,kargs_s)\n cmd = [[sys.executable,\"-c\",ext]]\n return cmd\n","repo_name":"benabed/pinc","sub_path":"pinc/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"16066117519","text":" # -*- coding: utf-8 -*-\n\"\"\"\nDjango settings for zero project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\nDEV= DEBUG\nTEMPLATE_DEBUG = DEBUG\n#DEBUG_PROPAGATE_EXCEPTIONS = DEBUG\n\nALLOWED_HOSTS = []\n\nSITE_ID = 1\n\nADMINS = (\n ('maxime BARBIER', 'maxime.barbier1991@gmail.com'),\n)\n\nMANAGERS = ADMINS\n\n# Database\n# https://docs.djangoproject.com/en/1.6/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': os.path.join(BASE_DIR, 'dev.db'),\n }\n}\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'i_zxx4*b(^v@-n$880it-gm$hi90x$o!q60^x^tf=)t6gbmap_'\n\nLANGUAGE_CODE = 'en'\ngettext = lambda s:s\nLANGUAGES = (\n ('en',gettext(u'English')),\n ('fr',gettext(u'Français')),\n)\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = os.path.join(BASE_DIR,'public/media/')\nMEDIA_URL = '/media/'\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_ROOT = os.path.join(BASE_DIR,'public/static/')\nSTATIC_URL = '/static/'\n#ADMIN_MEDIA_PREFIX = '/static/admin/'\n\n# Additional locations of static files\n#STATICFILES_DIRS = (\n#)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# List of callables that know how to import templates from various sources.\n#TEMPLATE_LOADERS = (\n# 'django.template.loaders.filesystem.Loader',\n# 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n#)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n \"django.core.context_processors.static\", \n 'django.core.context_processors.request',\n)\n\nMIDDLEWARE_CLASSES = (\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 #'django.middleware.locale.LocaleMiddleware',\n)\n\n\n# Application definition\n\nINSTALLED_APPS = (\n #'admin_tools.theming',\n #'admin_tools.menu',\n #'admin_tools.dashboard',\n\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n\n #'django.contrib.comments',\n #'django.contrib.messages',\n #'django.contrib.markup',\n\n 'django.contrib.humanize',\n\n 'rosetta',\n\n 'debug_toolbar',\n #'raven.contrib.django.raven_compat',\n 'django_extensions',\n 'registration',\n\n #'taggit',\n\n 'website',\n)\nACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value\n\n#RAVEN_CONFIG = {\n #your api key\n #create account https://www.getsentry.com/register/\n #'dsn': 'https://530251f72c084179872589d80ba05e71:630e4c96dd694cb48a4385f66dc2be06@app.getsentry.com/27531',\n#}\n\nROOT_URLCONF = 'zero.urls'\n\nWSGI_APPLICATION = 'zero.wsgi.application'\n\n","repo_name":"Krozark/django-zero","sub_path":"zero/zero/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":4146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"28317310830","text":"#!/usr/local/bin/python3\nimport sys\n\n\ndef main():\n \"\"\"Identify prime numbers, or one set of factors for a non-prime number.\"\"\"\n for n in range(2, 10):\n for x in range(2, n):\n if n % x == 0:\n print(n, 'equals', x, '*', n//x)\n break\n else:\n print(n, 'is a prime number.')\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"cbohara/codewars","sub_path":"primes.py","file_name":"primes.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"13052599169","text":"from turtle import *\n\nclass hexagon(Turtle):\n\tdef __init__(self,size):\n\t\tTurtle.__init__(self)\n\t\tself.shapesize(size)\n\t\tself.begin_poly()\n\t\tfor i in range(0,6):\n\t\t\tself.forward(size)\n\t\t\tself.left(60)\n\t\tself.end_poly()\n\t\tregister_shape(\"hexagon\",self.get_poly())\n\t\tself.shape(\"hexagon\")\t\n\nhex1 = hexagon(150)\nprint(hex1)\n\nmainloop()\n","repo_name":"shellyw19-meet/yl1201718","sub_path":"lab6c.py","file_name":"lab6c.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"18718449414","text":"import os\nimport socket \nfrom flask import Flask, render_template, request, Response, jsonify\nfrom flask_bootstrap import Bootstrap\nfrom gevent import monkey\nfrom gevent.pywsgi import WSGIServer\nmonkey.patch_all()\n\nfrom src.VideoStream import *\n\nmodel_config = {\n \"model_path\": 'models/yolov8n-seg-coco.onnx', # model path\n \"classes_path\" : 'models/coco_label.txt', # classes path\n \"box_score\" : 0.4,\n \"box_nms_iou\" : 0.45,\n \"box_aspect_ratio\" : None,\n \"box_stretch\" : None,\n}\n\ncam_config = {\n \"cam_id\" : 0,\n 'exposure': -2, # init cam exposure\n 'contrast': 50 # init cam contrast\n}\n \napplication = Flask(__name__, \n static_folder='./src/templates/static', \n template_folder='./src/templates')\nBootstrap(application)\n\n\n\nVIDEO = VideoStreaming(cam_config=cam_config, model_config=model_config)\n\n@application.route('/')\ndef home():\n TITLE = 'Object Segmentation App'\n CAM_CONFIG = cam_config.copy()\n CAM_CONFIG[\"sensor_h\"] = int(VIDEO.sensorH)\n CAM_CONFIG[\"sensor_w\"] = int(VIDEO.sensorW)\n CAM_CONFIG[\"display_h\"] = int(VIDEO.displayH)\n CAM_CONFIG[\"display_w\"] = int(VIDEO.displayW)\n\n MODLE_CONFIG = model_config.copy()\n for key, value in model_config.items():\n if type(value) == str:\n MODLE_CONFIG[key] = os.path.basename(value)\n\n CLASSES_CONFIG = VIDEO.MODEL.colors_dict.copy()\n STYLE_CONFIG = VIDEO.style_dict.copy()\n return render_template('index.html', TITLE=TITLE, \n CAM_CONFIG = CAM_CONFIG, \n MODEL_CONFIG = MODLE_CONFIG, \n TARGETLIST = CLASSES_CONFIG,\n STYLELIST = STYLE_CONFIG)\n\n@application.route('/video_feed')\ndef video_feed():\n '''\n Video streaming route.\n '''\n return Response(\n VIDEO.show(),\n mimetype='multipart/x-mixed-replace; boundary=frame'\n )\n\n@application.route('/request_target_display')\ndef request_target_display():\n targets_list = request.args.get('targetList')\n print('*'*10)\n print(\"display targets :\", targets_list)\n print('*'*10)\n VIDEO.setViewTarget(targets_list) \n\n return \"nothing\"\n\n# Button requests called from ajax\n@application.route('/request_preview_switch')\ndef request_preview_switch():\n active = request.args.get('active')\n VIDEO.preview = active\n print('*'*10)\n print(\"display preview :\", VIDEO.preview)\n print('*'*10)\n return \"nothing\"\n\n@application.route('/request_background_video')\ndef request_background_video():\n # url = \"https://youtu.be/LtrtLL_8mLM\" # testing url\n url = request.args.get('url')\n print('*'*10)\n print(\"video url or path :\", url)\n print('*'*10)\n VIDEO.setBackGround(url)\n return \"nothing\"\n\n@application.route('/request_background_switch')\ndef request_background_switch():\n active = request.args.get('active')\n VIDEO.background = active\n print('*'*10, VIDEO.background)\n return \"nothing\"\n\n@application.route('/request_flipH_switch')\ndef request_flipH_switch():\n active = request.args.get('active')\n VIDEO.flipH = active\n print('*'*10)\n print(\"display flip :\", VIDEO.flipH)\n print('*'*10)\n return \"nothing\"\n\n@application.route('/request_model_switch')\ndef request_model_switch():\n type = request.args.get('type')\n VIDEO.detect = type\n print('*'*10)\n print(\"display type :\", type)\n print('*'*10)\n return \"nothing\"\n\n@application.route('/request_style_switch')\ndef request_style_switch():\n type = request.args.get('type')\n VIDEO.setViewStyle(type)\n print('*'*10)\n print(\"display style :\", type)\n print('*'*10)\n return \"nothing\"\n\n@application.route('/request_exposure')\ndef request_exposure():\n value = request.args.get('value')\n VIDEO.exposure = int(value)\n print('*'*10)\n print(\"display exposure :\", VIDEO.exposure)\n print('*'*10)\n return \"nothing\"\n\n\n@application.route('/request_contrast')\ndef request_contrast():\n value = request.args.get('value')\n VIDEO.contrast = int(value)\n print('*'*10)\n print(\"display contrast :\",VIDEO.contrast)\n print('*'*10)\n return \"nothing\"\n\n@application.route('/request_blur')\ndef request_blur():\n value = request.args.get('value')\n VIDEO.blur = int(value)\n print('*'*10)\n print(\"display blur (kernel):\",VIDEO.blur)\n print('*'*10)\n return \"nothing\"\n\n@application.route('/reset_camera')\ndef reset_camera():\n STATUS =VIDEO.InitCamSettings()\n active = request.args.get('active')\n VIDEO.flipH = active\n type = request.args.get('type')\n VIDEO.detect = type\n print('*'*10)\n print(\"reset :\",STATUS)\n print('*'*10)\n return \"nothing\"\n\n\nif __name__ == \"__main__\":\n hostname=socket.gethostname() \n IPAddr=socket.gethostbyname(hostname) \n print(\"Your Computer Name is:\"+hostname) \n print(\"Your Computer IP Address is:\"+IPAddr) \n\n http_server = WSGIServer(('0.0.0.0', 8080), application)\n print(\"==============================================================\")\n print(\"The server will be accessible at [ http://\"+ IPAddr +\":8080 ].\")\n print(\"==============================================================\")\n http_server.serve_forever()\n","repo_name":"jason-li-831202/Object-Segmentation-Web","sub_path":"Application.py","file_name":"Application.py","file_ext":"py","file_size_in_byte":5270,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"43"} +{"seq_id":"27395090183","text":"from tkinter import *\n\n\ndef button_clicked():\n # my_label.config(text=\"Button Got Clicked\")\n my_label.config(text=input_text.get())\n\n\nwindow = Tk()\nwindow.title(\"My First GUI Program\")\nwindow.minsize(width=500, height=300)\nwindow.config(padx=20, pady=20)\n\n# label\nmy_label = Label(text=\"I Am a Label\", font=(\"Arial\", 24, \"bold\"))\n# my_label.pack()\n# my_label.place(x=100, y=200)\nmy_label.grid(column=0, row=0)\n# my_label[\"text\"] = \"New Text\"\n# my_label.config(text=\"New Text\")\n\n# button\nbutton = Button(text=\"Click Me\", command=button_clicked)\n# button.pack()\nbutton.grid(column=1, row=1)\n\nnew_button = Button(text=\"New Button\", command=button_clicked)\nnew_button.grid(column=2, row=0)\n\n# entry\ninput_text = Entry(width=10)\n# input_text.pack()\ninput_text.grid(column=3, row=2)\n\nwindow.mainloop()\n\n\n# unlimited position argument\n# def add(*args):\n# sum = 0\n# for i in args:\n# sum += i\n# return sum\n#\n#\n# print(add(3, 4, 5, 6, 7))\n\n\n# def calculate(n, **kwargs):\n# n += kwargs[\"add\"]\n# n *= kwargs[\"multiply\"]\n# print(n)\n#\n#\n# calculate(2, add=3, multiply=5)\n","repo_name":"Sophia-PeiJin-SU/100-Days-of-Code","sub_path":"Day27-advanced arguments/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"27206413551","text":"\"\"\"Backfill playlist_routes table\n\nRevision ID: efafdb22df81\nRevises: 2fad3671bf9f\nCreate Date: 2023-01-05 17:01:47.805581\n\n\"\"\"\nimport sqlalchemy as sa\nfrom alembic import op\nfrom sqlalchemy.orm import sessionmaker\n\n# revision identifiers, used by Alembic.\nrevision = \"efafdb22df81\"\ndown_revision = \"2fad3671bf9f\"\nbranch_labels = None\ndepends_on = None\n\nSession = sessionmaker()\n\n\ndef upgrade():\n bind = op.get_bind()\n session = Session(bind=bind)\n session.execute(sa.text(\"TRUNCATE TABLE playlist_routes\"))\n\n # Bring over existing routes (current playlists)\n session.execute(\n sa.text(\n \"\"\"\n INSERT INTO playlist_routes (\n playlist_id\n , owner_id\n , slug\n , title_slug\n , collision_id\n , is_current\n , blockhash\n , blocknumber\n , txhash\n )\n SELECT\n playlist_id\n , playlist_owner_id\n , CONCAT(REPLACE(LOWER(playlist_name), ' ', '-'), '-', playlist_id)\n AS slug\n , CONCAT(REPLACE(LOWER(playlist_name), ' ', '-'), '-', playlist_id)\n AS title_slug\n , 0 AS collision_id\n , is_current\n , blockhash\n , blocknumber\n , txhash\n FROM playlists\n WHERE is_current\n GROUP BY\n playlist_owner_id\n , playlist_id\n , playlist_name\n , is_current\n , blockhash\n , blocknumber\n , txhash;\n \"\"\"\n )\n )\n\n # Bring over existing routes (non-current playlists)\n session.execute(\n sa.text(\n \"\"\"\n INSERT INTO playlist_routes (\n playlist_id\n , owner_id\n , slug\n , title_slug\n , collision_id\n , is_current\n , blockhash\n , blocknumber\n , txhash\n )\n SELECT\n p.playlist_id\n , p.playlist_owner_id\n , p.slug\n , p.title_slug\n , p.collision_id\n , p.is_current\n , p.blockhash\n , p.blocknumber\n , p.txhash\n FROM (\n SELECT\n nc.playlist_id\n , nc.playlist_owner_id\n , CONCAT(REPLACE(LOWER(nc.playlist_name), ' ', '-'), '-', nc.playlist_id) AS slug\n , CONCAT(REPLACE(LOWER(nc.playlist_name), ' ', '-'), '-', nc.playlist_id) AS title_slug\n , 0 AS collision_id\n , nc.is_current\n , nc.blockhash\n , nc.blocknumber\n , nc.txhash\n , ROW_NUMBER() OVER (\n PARTITION BY nc.playlist_name\n ORDER BY nc.blocknumber DESC\n ) AS rank\n FROM playlists AS c_playlists\n JOIN playlists AS nc\n ON c_playlists.playlist_id = nc.playlist_id\n WHERE NOT nc.is_current\n AND c_playlists.is_current\n AND NOT LOWER(nc.playlist_name) = LOWER(c_playlists.playlist_name)\n ) p\n WHERE p.rank = 1\n ON CONFLICT DO NOTHING;\n \"\"\"\n )\n )\n\n\ndef downgrade():\n pass\n","repo_name":"chinmaisiddhartha/audius-main","sub_path":"discovery-provider/alembic/versions/efafdb22df81_backfill_playlist_routes_table.py","file_name":"efafdb22df81_backfill_playlist_routes_table.py","file_ext":"py","file_size_in_byte":3579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"33774145302","text":"\"\"\"\npartition.py\n\nGeometry of Redistricting Conference 2017-10-14..15 Hackathon\n\nEnumerate all possible partitions of a small map into districts,\nto compare results with randomized district sampling algorithms.\n\"\"\"\n\nfrom __future__ import division # for Python 2.7\n\n\nimport networkx as nx\n\n\ndef calc_limits(graph, num_parts, max_ratio):\n \"\"\"Estimate min and max weights for partitioning graph into num_parts.\n \n Node weight of each subgraph may differ from the average by\n no more than a factor of max_ratio.\n \n graph: networkx.Graph\n num_parts: int\n max_ratio: float\n \n Returns: (min_weight, max_weight)\n \"\"\"\n nodes = graph.nodes(data='weight') # sequence of (id, weight)\n weights = [weight for id, weight in nodes]\n total_weight = sum(weights) # weight of all nodes\n \n avg_weight = total_weight / num_parts # average subgraph weight\n max_weight = avg_weight * max_ratio # largest allowed subgraph weight\n min_weight = avg_weight / max_ratio # smallest allowed subgraph weight\n return (min_weight, max_weight)\n\n\ndef all_partitions(graph, limits):\n \"\"\"Enumerate all partitions of graph into subgraphs within weight limits.\n \n graph: networkx.Graph\n limits: (min_weight, max_weight)\n \n Returns: \n list of partitions, each partition a list of subgraphs,\n each subgraph a list of node\n \"\"\"\n partitions = []\n \n # Find node with highest weight\n nodes = graph.nodes(data='weight') # iterator of (id, weight)\n weights = [weight for id, weight in nodes]\n highest_weight = max(weights)\n node_index = weights.index(highest_weight)\n heaviest = list(nodes)[node_index][0] # id of node with highest weight\n \n # Find all subgraphs containing heaviest node, within weight limits\n subgraphs = accrete(graph,\n subgraph={heaviest},\n subgraph_weight=highest_weight,\n ignore={heaviest},\n limits=limits)\n \n for subgraph in subgraphs:\n ### Check if subgraph splits graph into disconnected parts?\n ### If so, check parts for min_weight, \n ### discard subgraph if any are underweight.\n \n remainder = graph.copy()\n remainder.remove_nodes_from(subgraph)\n if len(remainder) == 0: # empty\n partitions.append([subgraph]) # add a 1-part partition\n else:\n subpartitions = all_partitions(remainder, limits)\n # add subgraph to each subpartition\n for subpartition in subpartitions:\n partitions.append(subpartition + [subgraph])\n \n return partitions \n\n\ndef accrete(graph, subgraph, subgraph_weight, ignore, limits):\n \"\"\"Find all subgraphs of graph which contain subgraph, within limits.\n \n Subgraphs must have weight (sum of node weights) within limits.\n Ignore any nodes in ignore.\n \n graph: networkx.Graph\n subgraph: set of node\n ignore: set of node\n limits: (min_weight, max_weight)\n \n Returns: list of subgraphs, each a set of node\n \"\"\"\n min_weight, max_weight = limits\n subgraphs = []\n \n # find all neighbors of subgraph, excluding nodes in ignore\n ### reuse this?\n nbrs = set()\n for node_id in subgraph:\n nbrs |= set(graph[node_id]) - ignore\n \n ### use neighbors of forward node only?\n # Try adding each neighbor to subgraph\n for nbr in nbrs:\n subgraph_weight += graph.nodes[nbr]['weight']\n if subgraph_weight > max_weight:\n ignore.add(nbr) # nbr too heavy to add to subgraph, skip it later\n else:\n new_subgraph = subgraph | {nbr}\n if subgraph_weight >= min_weight:\n subgraphs.append(new_subgraph)\n subgraphs += accrete(graph, \n new_subgraph,\n subgraph_weight,\n ignore | {nbr},\n limits)\n return subgraphs\n\n\nif __name__ == \"__main__\":\n # parseargs: graph_filename, num_parts, max_ratio\n ## ...\n num_parts = 3\n max_ratio = 1.1\n \n # read graph from file given by graph_filename\n ## ...\n \n limits = calc_limits(graph, num_parts, max_ratio)\n partitions = all_partitions(graph, limits)\n # display partitions or write to file\n\n\n# test data\nd = {0: {'weight': 8.0}, 1: {'weight': 15.0}, 2: {'weight': 0.2}, \n 3: {'weight': 6.2}, 4: {'weight': 4.4}, 5: {'weight': 0}}\ndt = [(0, {'weight': 8.0}), (1, {'weight': 15.0}), (2, {'weight': 0.2}),\n (3, {'weight': 6.2}), (4, {'weight': 4.4}), (5, {'weight': 0})]\ng = nx.Graph()\ng.add_nodes_from(dt)\ne = [(0, 1), (0, 4), (1, 2), (2, 3), (3, 4), (3, 5), (4, 5)]\ng.add_edges_from(e)\n \n \n ","repo_name":"gerrymandr/district-enumeration","sub_path":"partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"44091535481","text":"# https://www.hackerrank.com/challenges/picking-cards/problem\n\nt = int(input())\n\nfor _ in range(t):\n n = int(input())\n c = sorted(map(int, input().strip().split()), reverse=True)\n\n ans = 1\n for i, c in enumerate(c):\n val = n - c\n if val <= 0:\n print(0)\n break\n\n ans = (ans * (val - i)) % 1000000007\n else:\n print(ans % 1000000007)\n","repo_name":"JaredLGillespie/HackerRank","sub_path":"Python/picking-cards.py","file_name":"picking-cards.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"43"} +{"seq_id":"11455164314","text":"from picamera.array import PiRGBArray\nfrom picamera import PiCamera\nfrom time import time,sleep\nimport numpy as np\nimport errno\nimport sys\nimport cv2\nimport os\n\n\n\nclass VideoPlayer:\n \"\"\"\n \"\"\"\n def __init__(self,\n VIDEO_BASE_FOLDER='/home/pi/motionBasedVideoPlayer/data/picameraVideos/',\n resolution = (320, 256),\n framerate = 30,\n max_signal_length = 100):\n \"\"\"Definitions\"\"\"\n self.VIDEO_BASE_FOLDER = VIDEO_BASE_FOLDER\n self.current_time_ms = lambda: int(round(time() * 1000))\n self.camera = PiCamera()\n self.camera.resolution = resolution\n self.camera.framerate = framerate\n self.rawCapture = PiRGBArray(self.camera, size=resolution)\n sleep(0.1)\n \n def get_video_filename(self):\n \"\"\"Open a h264 file to write video frames and return the file name\"\"\"\n return self.VIDEO_BASE_FOLDER+str(self.clock)+'_video.h264'\n\n\n def motionDetector(self, poll_time = 0.03, cap = []):\n \"\"\"\n Thread for computing average red, green, blue and grey in video frames.\n Uses cv2 and numpy module to compute the average channel intensities\n \n Parameters\n ----------\n poll_time: float\n Expects a float value that specifies the sleep time between two Raspberry Pi Camera frames\n \"\"\"\n self.clock = self.current_time_ms()\n self.camera.start_recording(self.get_video_filename())\n cv2.startWindowThread()\n frameOld = np.zeros([self.camera.resolution[1], self.camera.resolution[0]], dtype=np.uint8)\n \n if (not cap.isOpened()):\n printf(\"Video object is not open...\")\n return\n \n idx = 1\n for frame in self.camera.capture_continuous(self.rawCapture,\n format=\"bgr\",\n use_video_port=True):\n \n frame = frame.array\n #frameb = frame[:,:,0] # Ignore Blue channel\n #frameg = frame[:,:,1] # Ignore Green channel\n #framer = frame[:,:,2] # Ignore Red channel\n framegs = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) # Extract Grayscale channel\n \n # Take the difference (frameDiff) between current frame (framegs) and the previous frame (frameOld)\n frameDiff = np.array(np.absolute(np.array(framegs, dtype=int) - np.array(frameOld, dtype=int)), dtype=np.uint8)\n \n # Assign current frame to frameOld to be used in next iteration\n frameOld = framegs\n\n # Compute baseline and scaled motion signal values for the current frame\n nonZeroPixelCount = np.count_nonzero(frameDiff)\n motionSignalBaseline = np.mean(np.mean(frameDiff))\n motionSignalScaled = np.sum(frameDiff)/nonZeroPixelCount\n \n # Modify below line to specify how many frames to skip based on the above motion signals.\n # I round the motionSignalScaled value and bound it within 1 and 50\n #print(int(motionSignalScaled))\n nFrameSkip = min(int(motionSignalScaled), 200)\n nFrameSkip = max(1, nFrameSkip)\n # Uncomment below to Binarize nFrameSkip\n #if (nFrameSkip > 15):\n # nFrameSkip = 100\n #else:\n # nFrameSkip = 0\n \n idx = idx + nFrameSkip\n \n # If display video has ended, then restart\n if (not cap.isOpened()):\n cap.release()\n # Copy the cloned archive back to the original variable\n return\n \n # Skip Video frames\n # Method 1: Very slow on RasPi\n #for ii in range(int(nFrameSkip)):\n # ret, dispFrame = cap.read()\n \n # Method 2: Seek idx^th frame\n cap.set(cv2.CAP_PROP_POS_FRAMES, idx)\n \n # If video has ended return\n if (not cap.isOpened()):\n cap.release()\n cv2.destroyAllWindows()\n self.camera.stop_recording()\n return\n \n # Skip nFrameSkip frames \n ret, dispFrame = cap.read()\n idx = idx + 1\n \n # If video has ended return\n if (not cap.isOpened()):\n cap.release()\n cv2.destroyAllWindows()\n self.camera.stop_recording()\n return\n \n # Get next frame\n ret, dispFrame = cap.read()\n idx = idx + 1\n \n # Show Video frame \n try:\n cv2.imshow('frame',dispFrame)\n except:\n # If video has ended return\n cap.release()\n cv2.destroyAllWindows()\n self.camera.stop_recording()\n return\n \n # Routine to exit \n k = cv2.waitKey(30) & 0xff\n if k == 27:\n print(\"Video Stream stops. Press Ctrl+C now.\")\n cv2.destroyAllWindows()\n self.camera.stop_recording()\n sys.exit(\"Ctrl-C was pressed\")\n\n self.rawCapture.truncate(0)\n # Optionally sleep for poll_time seconds\n #sleep(poll_time)\n\nif __name__ == \"__main__\":\n \n try:\n os.mkdir('/home/pi/motionBasedVideoPlayer/data/picameraVideos')\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n pass\n \n \n videoFile = '/home/pi/motionBasedVideoPlayer/data/displayVideos/test.mp4' \n \n while True:\n vidPlayer = VideoPlayer()\n cap = cv2.VideoCapture(videoFile)\n vidPlayer.motionDetector(poll_time = 0, cap = cap)","repo_name":"cliffordlab/motionBasedVideoPlayer","sub_path":"codes/motionBasedVideoPlayer.py","file_name":"motionBasedVideoPlayer.py","file_ext":"py","file_size_in_byte":5831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"36875145137","text":"import math\r\nimport time\r\nimport cv2\r\nimport numpy as np\r\nfrom dronekit import VehicleMode, connect\r\n\r\n#stelan warna\r\nhue_lower = 5\r\nhue_upper = 130\r\nsaturation_lower = 5\r\nsaturation_upper = 40\r\nvalue_lower = 60\r\nvalue_upper = 180\r\nmin_contour_area = 500 # piksel terkecil pada kontur sebelum itu terdaftar sebagai target\r\n\r\n#kamera\r\nhorizontal_resolution = 1280\r\nvertical_resolution = 720\r\n\r\ncamera = cv2.VideoCapture(0)\r\n\r\n#koneksi ke wahana\r\nconnection_string = \"/dev/ttyS0\"\r\nbaud_rate = 57600\r\n\r\nprint('connecting..')\r\nvehicle = connect(connection_string, baud=baud_rate, wait_ready=True)\r\n\r\nprint('start visual landing')\r\n\r\ndef send_land_message(x, y):\r\n msg = vehicle.message_factory.landing_target_encode(\r\n 0, \r\n 0, \r\n 0, \r\n (x-horizontal_resolution/2)*horizontal_fov/horizontal_resolution,\r\n (y-vertical_resolution/2)*vertical_fov/vertical_resolution,\r\n 0, \r\n 0,0) \r\n vehicle.send_mavlink(msg)\r\n vehicle.flush()\r\n\r\nwhile(1):\r\n _,capture = camera.read()\r\n hsv = cv2.cvtColor(capture,cv2.COLOR_BGR2HSV) \r\n inrangepixels = cv2.inRange(capture,np.array((hue_lower,saturation_lower,value_lower)),np.array((hue_upper,saturation_upper,value_upper)))#in opencv, HSV is 0-180,0-255,0-255\r\n tobecontourdetected = inrangepixels.copy()\r\n contours,hierarchy = cv2.findContours(tobecontourdetected,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\r\n \r\n contour_sizes=[]\r\n contour_centroids = []\r\n for contour in contours: \r\n real_area = cv2.contourArea(contour)\r\n if real_area > min_contour_area:\r\n M = cv2.moments(contour) #moment itu centroid\r\n cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00'])\r\n cv2.circle(capture,(cx,cy),5,(0,0,255),-1)\r\n contour_sizes.append(real_area)\r\n contour_centroids.append((cx,cy))\r\n \r\n #mendeeksi kontur terbesar (by area) \r\n biggest_contour_index = 0\r\n for i in range(1,len(contour_sizes)):\r\n if contour_sizes[i] > contour_sizes[biggest_contour_index]:\r\n biggest_contour_index = i\r\n biggest_contour_centroid=None\r\n if len(contour_sizes)>0:\r\n biggest_contour_centroid=contour_centroids[biggest_contour_index]\r\n \r\n #jika kontur terbesar sudah ditemukan dan itu berwarna merah\r\n if biggest_contour_centroid is not None:\r\n cv2.circle(capture,biggest_contour_centroid,5,(0,0,255),-1)\r\n x,y = biggest_contour_centroid\r\n vehicle.mode = VehicleMode(\"LAND\")\r\n send_land_message(x,y)\r\n\r\n \r\n cv2.imshow('capture',capture) \r\n \r\n if cv2.waitKey(1) == 27:\r\n break\r\n \r\ncv2.destroyAllWindows()\r\ncamera.release()\r\n","repo_name":"nofrijalf/My-Final-Project","sub_path":"fixcode.py","file_name":"fixcode.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"30188101039","text":"import numpy as np\n\n# x : 0 or 1\n# y : L or T\ndef get_data(x, y):\n # 20(あ~と) x 100(文字) x 64(メッシュ特徴量)\n mesh_data = np.zeros((20, 100, 64))\n for i in range(20):\n if i <= 9:\n text = np.loadtxt('Data/hira' + x + '_0'+ str(i) + y + '.dat', dtype='str')\n else:\n text = np.loadtxt('Data/hira' + x + '_' + str(i) + y + '.dat', dtype='str')\n \n temp = np.array([list(map(float, list(line.rstrip()))) for line in text])\n\n for j in range(100):\n for col in range(8):\n for row in range(8):\n block = temp[64*j + col*8 : 64*j + col*8 + 8, row*8: row*8 + 8]\n mesh_data[i, j, 8*col + row] = np.sum(block) / 64\n \n return mesh_data\n\ndef get_label():\n label = np.ndarray((20, 100, 20))\n for i in range(20):\n for j in range(100):\n for k in range(20):\n if i == k:\n label[i, j, k] = 1\n else:\n label[i, j, k] = 0\n return label","repo_name":"sbmtrntr/Tue5","sub_path":"data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"34387363171","text":"import unittest\r\nfrom core.setup_mapping import Cluster\r\nfrom core.logs import ComponentLog\r\ncluster = None\r\n\r\n\r\nclass TestResult(object):\r\n\r\n def startTestRun(self):\r\n \"\"\"\r\n Called once before any tests are executed.\r\n\r\n :return:\r\n \"\"\"\r\n global cluster\r\n cluster = Cluster()\r\n ComponentLog()\r\n\r\n setattr(unittest.TestResult, 'startTestRun', startTestRun)\r\n\r\n def stopTestRun(self):\r\n \"\"\"\r\n Called once after all tests are executed.\r\n\r\n :return:\r\n \"\"\"\r\n global cluster\r\n cluster.clear_cluster()\r\n\r\n setattr(unittest.TestResult, 'stopTestRun', stopTestRun)\r\n\r\n def load_tests(self):\r\n tests = unittest.defaultTestLoader.discover(\".\")\r\n suite = unittest.TestSuite()\r\n suite.addTests(tests)\r\n unittest.TextTestRunner(verbosity=2).run(suite)\r\n","repo_name":"xxDandelion/qwilCDN","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"35578193922","text":"import unittest\n\nimport upt\n\nfrom upt_macports.upt_macports import MacPortsPythonPackage\n\n\nclass TestMacPortsPythonPackage(unittest.TestCase):\n def setUp(self):\n self.package = MacPortsPythonPackage()\n self.package.upt_pkg = upt.Package('test-pkg', '13.37')\n\n def test_pkgname(self):\n expected = ['py-foo', 'py-py-foo', 'py-pyfoo', 'py-pyfoo']\n names = ['foo', 'py-foo', 'pyfoo', 'pyFoo']\n for (name, expected_name) in zip(names, expected):\n self.package.upt_pkg = upt.Package(name, '13.37')\n self.assertEqual(self.package._pkgname(), expected_name)\n\n def test_folder_name(self):\n expected = ['py-foo', 'py-py-foo', 'py-pyfoo', 'py-pyfoo']\n names = ['foo', 'py-foo', 'pyfoo', 'pyFoo']\n for (name, expected_name) in zip(names, expected):\n self.assertEqual(\n self.package._normalized_macports_folder(name), expected_name)\n\n def test_py_root_name(self):\n pypi_names = ['foo', 'Foo', 'pyFoo', 'pyfoo', 'py-Foo']\n expected_python_rootnames = [None, 'Foo', 'pyFoo', None, 'py-Foo']\n for (pypi_name, python_rootname) in zip(pypi_names,\n expected_python_rootnames):\n self.package.upt_pkg = upt.Package(pypi_name, '13.37')\n self.assertEqual(self.package._python_root_name(), python_rootname)\n\n def test_jinja2_reqformat(self):\n req = upt.PackageRequirement('Require')\n self.assertEqual(self.package.jinja2_reqformat(req),\n 'py${python.version}-require')\n\n def test_homepage(self):\n upt_homepages = [\n '',\n 'unknown',\n 'https://github.com/test-pkg'\n ]\n\n excpected_homepages = [\n 'https://pypi.org/project/test-pkg',\n 'https://pypi.org/project/test-pkg',\n 'https://github.com/test-pkg'\n ]\n\n for (upt_homepage, expected_homepage) in zip(upt_homepages,\n excpected_homepages):\n self.package.upt_pkg.homepage = upt_homepage\n self.assertEqual(self.package.homepage, expected_homepage)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"macports/upt-macports","sub_path":"upt_macports/tests/test_python_package.py","file_name":"test_python_package.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"43"} +{"seq_id":"36406068284","text":"import unittest\n\nclass TestEventsModel(unittest.TestCase):\n \n def setUp(self):\n global can\n can = lambda x,y: True\n execfile(\"applications/%s/controllers/events.py\" % appname, globals()) #add the validatons\n db(db.events.id>0).delete()\n db(db.event_types.id>0).delete()\n db.event_types.insert(id=1,name='Fitting')\n \n global formname, form, post_vars\n formname = 'create'\n db.events.type.writable=True\n form = SQLFORM(db.events) #form has to be created after the db is prepared\n post_vars = dict(name='Dummy',\n type='1',\n slots='10',\n date='08-08-2011',\n start_time='09:00',\n end_time='10:00', \n _formname=formname)\n \n def testRequiredFieldsShouldInsert(self):\n status = form.accepts(post_vars, formname=formname)\n self.assertTrue(status)\n \n def testEmptyNameShouldNotInsert(self):\n field = 'name'\n post_vars[field] = ''\n self.assertFalse(form.accepts(post_vars, formname=formname))\n self.assertEquals(form.errors[field], 'enter a value')\n \n def testEmptyTypeShouldNotInsert(self):\n field = 'type'\n post_vars[field] = ''\n self.assertFalse(form.accepts(post_vars, formname=formname))\n self.assertEquals(form.errors[field], 'value not in database')\n \n def testDummyTypeShouldNotInsert(self):\n field = 'type'\n post_vars[field] = '3'\n self.assertFalse(form.accepts(post_vars, formname=formname))\n self.assertEquals(form.errors[field], 'value not in database')\n \n def testEndTimeAfterStartTimeShouldNotInsert(self):\n field = 'end_time'\n post_vars[field] = '09:00'\n self.assertFalse(form.accepts(post_vars, formname=formname, onvalidation=event_form_processing))\n self.assertEquals(form.errors[field], 'End time must be after start time')\n \n\ndef add_tests():\n suite.addTest(unittest.makeSuite(TestEventsModel))\n\nif 'suite' not in globals():\n execfile('applications/%(application)s/tests/test_utils.py' % request, globals())\n setup_env()\n add_tests()\n run_tests()\nelse:\n #executed by tests/models/runner.py\n add_tests()\n","repo_name":"chandrabhushana/dfsa","sub_path":"applications/booking/tests/models/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"17044551222","text":"import requests\n#print(requests)\nr = requests.get('http://google.com') # fragt eine webseite an\n\n#print(r.text) # gibt inhalt der Datei aus, hier den html text der seite aus.\n\nf = open('google2.html','w') # öffnet datein mit namen google.html\nf.write(r.text) # schreibt die abfrage, hier ein text von dem request.get (r.text) in die geöffnete datei.\n\nf.flush() # rest aus dem buffer wird hier in die datei geschrieben\nf.close() # hier wird die datei geschlossen\n\n\n","repo_name":"Jamancode/Python3","sub_path":"Schmierheft/Sortieren_suchen/requests1.py","file_name":"requests1.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"3295310204","text":"import re\n\nimport web\nimport simplejson as json\n\nimport karesansui\nfrom karesansui.lib.rest import Rest, auth\nfrom karesansui.db.access.machine import findbyhost1\n\nfrom karesansui.lib.checker import Checker, \\\n CHECK_EMPTY, CHECK_VALID, CHECK_LENGTH, \\\n CHECK_CHAR, CHECK_MIN, CHECK_MAX, CHECK_ONLYSPACE, \\\n CHECK_UNIQUE\n\nfrom karesansui.lib.utils import is_param, is_empty, preprint_r, \\\n base64_encode, get_ifconfig_info\n\nfrom karesansui.lib.networkaddress import NetworkAddress\nfrom karesansui.lib.parser.staticroute import staticrouteParser as Parser\nfrom karesansui.lib.conf import read_conf, write_conf\n\ndef validates_staticroute(obj):\n checker = Checker()\n check = True\n\n _ = obj._\n checker.errors = []\n\n if not is_param(obj.input, 'target'):\n check = False\n checker.add_error(_('Specify target address for the route.'))\n else:\n check = checker.check_ipaddr(\n _('Target'), \n obj.input.target,\n CHECK_EMPTY | CHECK_VALID,\n ) and check\n\n if not is_param(obj.input, 'gateway'):\n check = False\n checker.add_error(_('Specify gateway address for the route.'))\n else:\n check = checker.check_ipaddr(\n _('Gateway'), \n obj.input.gateway,\n CHECK_VALID,\n ) and check\n\n obj.view.alert = checker.errors\n return check\n\nclass HostBy1StaticRoute(Rest):\n\n @auth\n def _GET(self, *param, **params):\n host_id = self.chk_hostby1(param)\n if host_id is None: return web.notfound()\n\n host = findbyhost1(self.orm, host_id)\n\n self.view.host_id = host_id\n\n # unremovable entries\n excludes = {\n \"device\": [\"^peth\",\"^virbr\",\"^sit\",\"^xenbr\",\"^lo\",\"^br\"],\n \"ipaddr\": [\"^0\\.0\\.0\\.0$\", \"^169\\.254\\.0\\.0$\"],\n }\n\n devices = []\n phydev_regex = re.compile(r\"^eth[0-9]+\")\n for dev,dev_info in get_ifconfig_info().iteritems():\n if phydev_regex.match(dev):\n try:\n if dev_info['ipaddr'] is not None:\n devices.append(dev)\n net = NetworkAddress(\"%s/%s\" % (dev_info['ipaddr'],dev_info['mask'],))\n excludes['ipaddr'].append(net.network)\n except:\n pass\n\n self.view.devices = devices\n\n parser = Parser()\n status = parser.do_status()\n routes = {}\n for _k,_v in status.iteritems():\n for _k2,_v2 in _v.iteritems():\n name = base64_encode(\"%s@%s\" % (_k2,_k,))\n routes[name] = {}\n routes[name]['name'] = name\n routes[name]['device'] = _k\n routes[name]['gateway'] = _v2['gateway']\n routes[name]['flags'] = _v2['flags']\n routes[name]['ref'] = _v2['ref']\n routes[name]['use'] = _v2['use']\n net = NetworkAddress(_k2)\n routes[name]['ipaddr'] = net.ipaddr\n routes[name]['netlen'] = net.netlen\n routes[name]['netmask'] = net.netmask\n\n removable = True\n for _ex_key,_ex_val in excludes.iteritems():\n ex_regex = \"|\".join(_ex_val)\n mm = re.search(ex_regex,routes[name][_ex_key])\n if mm:\n removable = False\n\n routes[name]['removable'] = removable\n\n self.view.routes = routes\n\n if self.is_mode_input():\n pass\n\n return True\n\n @auth\n def _POST(self, *param, **params):\n host_id = self.chk_hostby1(param)\n if host_id is None: return web.notfound()\n\n host = findbyhost1(self.orm, host_id)\n\n if not validates_staticroute(self):\n return web.badrequest(self.view.alert)\n\n modules = [\"staticroute\"]\n\n dop = read_conf(modules, self, host)\n if dop is False:\n return web.internalerror('Internal Server Error. (Timeout)')\n\n target = self.input.target\n net = NetworkAddress(target)\n ipaddr = net.ipaddr\n netmask = net.netmask\n netlen = net.netlen\n network = net.network\n target = \"%s/%s\" % (ipaddr,netlen,)\n gateway = self.input.gateway\n device = self.input.device\n\n dop.set(\"staticroute\", [device,target], gateway)\n\n from karesansui.lib.parser.staticroute import PARSER_COMMAND_ROUTE\n if net.netlen == 32:\n command = \"%s add -host %s gw %s dev %s\" % (PARSER_COMMAND_ROUTE,ipaddr,gateway,device,)\n command = \"%s add -host %s dev %s\" % (PARSER_COMMAND_ROUTE,ipaddr,device,)\n else:\n command = \"%s add -net %s netmask %s gw %s dev %s\" % (PARSER_COMMAND_ROUTE,network,netmask,gateway,device,)\n extra_args = {\"post-command\": command}\n\n retval = write_conf(dop, self, host, extra_args=extra_args)\n if retval is False:\n return web.internalerror('Internal Server Error. (Adding Task)')\n\n return web.accepted(url=web.ctx.path)\n\nurls = (\n '/host/(\\d+)/staticroute[/]?(\\.html|\\.part|\\.json)?$', HostBy1StaticRoute,\n )\n\n","repo_name":"karesansui/karesansui","sub_path":"karesansui/gadget/hostby1staticroute.py","file_name":"hostby1staticroute.py","file_ext":"py","file_size_in_byte":5260,"program_lang":"python","lang":"en","doc_type":"code","stars":107,"dataset":"github-code","pt":"43"} +{"seq_id":"19350322264","text":"#для удаления файла по указанному пути. Перед удалением проверьте наличие доступа и наличие заданного пути.\r\nimport os\r\n\r\nn = 'C:\\\\Users\\\\annalar\\Documents\\\\Unik\\Piton\\PP2_2022\\Lab6\\\\directories\\\\' #путь по которому проверка\r\n\r\nprint(\"\\nTest exists or not:\")\r\nprint(os.path.exists(n)) #проверит есть ли такой путь и возможен ли он\r\n\r\nif not os.path.exists(\"Letters\"): #если нет такой папки\r\n os.mkdir(\"Letters\") #то он создаст папку\r\n\r\n# потом он удалит файл сразу или сделать сначала первую функцию закомментив вторую и потом использовать вторую\r\n\r\nif os.path.exists(\"Letters\"): #если есть путь такой папки\r\n os.rmdir(\"Letters\") #то он удалит папку\r\n","repo_name":"Larionova-Anastassiya/PP2_2022","sub_path":"Lab6/directories/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"16156356225","text":"from game.controllers.singleton_controller import SingletonController\n\n\nclass FunStatController(SingletonController):\n def __init__(self):\n super().__init__()\n self.debug = False\n\n # Stats for decree correctness ratio\n self.total_disasters = 0\n self.disasters_correctly_protected = 0\n\n # Stats for average population\n self.total_population_ever = 0\n\n # Stats for average structure\n self.total_structure_ever = 0\n\n # Stats for effort successfully allocated\n self.total_effort_applied = 0\n self.effort_correctly_applied = 0\n\n # Stats for damage taken\n self.total_population_damage = 0\n self.total_structure_damage = 0\n\n def export(self):\n stats = dict()\n\n stats['total_disasters'] = self.total_disasters\n stats['disasters_correctly_protected'] = self.disasters_correctly_protected\n\n stats['total_population_ever'] = self.total_population_ever\n\n stats['total_structure_ever'] = self.total_structure_ever\n\n stats['total_effort_applied'] = self.total_effort_applied\n stats['effort_correctly_applied'] = self.effort_correctly_applied\n\n stats['total_population_damage'] = self.total_population_damage\n stats['total_structure_damage'] = self.total_structure_damage\n\n return stats\n","repo_name":"PixPanz/byte_le_royale_2020","sub_path":"game/controllers/fun_stat_controller.py","file_name":"fun_stat_controller.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"43"} +{"seq_id":"9224522129","text":"import db\n\nif __name__ == '__main__':\n db.initDb(\"test\")\n ids = db.getOrderIds(24021)\n for id in ids:\n label = db.getOrderLabel(id)\n if label is not None and len(label) > 1 :\n db.updateOrdersLabel(orderId=id, label=str(label.get(\"orderLable\")), labelDesc=label.get(\"orderLableComment\"))\n print(id)\n\n\n\n\n\n\n\n","repo_name":"wangjufeng1002/PythonTest","sub_path":"py/ju/order-data/UpdateLabel.py","file_name":"UpdateLabel.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"41989833134","text":"from __future__ import print_function\n\nimport grpc\n\nimport recognition_pb2\nimport recognition_pb2_grpc\n\n\ndef run():\n # NOTE(gRPC Python Team): .close() is possible on a channel and should be\n # used in circumstances in which the with statement does not fit the needs\n # of the code.\n with grpc.insecure_channel('localhost:50000') as channel:\n stub = recognition_pb2_grpc.RecognizeStub(channel)\n response = stub.Recognize(recognition_pb2.Request(\n imgPath='path/to/img', type=recognition_pb2.Request.ELECT))\n print(response)\n response = stub.Recognize(recognition_pb2.Request(\n imgPath='path/to/img', type=recognition_pb2.Request.WATER))\n print(response)\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"luoyunhe/paperCode","sub_path":"rpc/server/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"21644319378","text":"from fabric.api import local, task, lcd, env, run, roles, execute, cd, put\nimport datetime\n\n\nenv.roledefs = {\n 'dev': ['root@10.10.187.129'],\n 'test_spider': ['spider@10.10.95.70', 'spider@10.10.84.225', 'spider@10.10.48.27'],\n}\n\n\ndef _hello():\n local('echo \"hello\"')\n\n\ndef _build_dir():\n path = 'build_{0}'.format(datetime.datetime.now().strftime('%Y-%m-%d-T%H%M%S'))\n local('mkdir {0}'.format(path))\n return path\n\n\ndef _submodule_update():\n local('git submodule init')\n local('git submodule update')\n\n\ndef _build_old_spider(tag):\n local('git clone http://gitlab.uc.online/spider/slave_develop_new.git')\n local('cd slave_develop_new')\n with lcd('slave_develop_new'):\n local('git checkout {tag}'.format(tag=tag))\n _submodule_update()\n local('git submodule status')\n local('mkdir workspace/spider/SpiderClient/bin/start/slavepid')\n\n\ndef _build_new_spider(tag):\n local('mkdir tmp')\n with lcd('tmp'):\n local('git clone http://gitlab.uc.online/spider_new/Spider.git')\n with lcd('Spider'):\n local('git checkout {tag}'.format(tag=tag))\n _submodule_update()\n local('git submodule status')\n local('scp -r tmp/Spider/src/mioji slave_develop_new/workspace/spider/SpiderClient/bin/mioji')\n\n\n@task\ndef build(old_ver, new_ver, path=None):\n if not path:\n path = _build_dir()\n with lcd(path):\n local('pwd')\n _build_old_spider(old_ver)\n _build_new_spider(new_ver)\n local('mv slave_develop_new/workspace/spider/SpiderClient ./')\n file_name = '{0}_{1}_spider.tar.gz'.format(old_ver, new_ver)\n local('tar -zcvf {0} SpiderClient'.format(file_name))\n local('md5 {0}'.format(file_name))\n return path\n\n\ndef _deploy_spider():\n with cd('/search/test'):\n run('rm -rf slave_develop_new')\n put('{0}/spider_slave.tar.gz', './')\n\n\n@roles('test_spider')\ndef _deploy_totest():\n _deploy_spider()\n\n\ndef deploy(path, role=None):\n rs = {\n \"test_spider\": _deploy_spider\n }\n execute(rs[role], args=(path,))\n\n\nif __name__ == '__main__':\n # pull_source('http://gitlab.uc.online/spider_new/Spider.git', 'release_v1.0.0')\n # path = _build_dir()\n # path='build_2017-08-25-T21:04:46'\n # path = None\n # path = build('release_v1.0.2', 'release_v1.0.0')\n # deploy(path, 'test_spider')\n build('slave.20171220.a', 'Spider.20171221.a')\n","repo_name":"20113261/lave","sub_path":"workspace/spider/SpiderClient/bin/start/test_buliding/build_slave.py","file_name":"build_slave.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"15313549672","text":"import os\ninfile=open(\"lines.txt\",'r')#web ,python ,database\noutfile=open('out.txt','a')\n\nfor line in infile:\n print(line.strip(),file=outfile)\n print(\".\")\n \nif os.path.exists(\"out.txt\") :\n if os.path.getsize(\"out.txt\")>=os.path.getsize(\"lines.txt\"): \n print(\"file ready\")\nprint(os.path.getsize(\"lines.txt\")) #bytes\n \n#check file have some data or not ?\n#write only the line that have .mp3.?\n","repo_name":"shravan199/kgs_python_training","sub_path":"KPMG - Python Technical Training/Day5/Day5/Day5/files/read_writeFiles.py","file_name":"read_writeFiles.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"74765526209","text":"#!/usr/bin/env python3\n\n\"\"\"\nThis script adds or removes colons, or converts dashes to colons on the input\nstring. This is useful for converting MAC addresses to different formats.\n\"\"\"\n\nimport subprocess\nimport syslog\nfrom sys import stdin\n\n\ndef add_colon(mac):\n lines = []\n for _ in range(0, len(mac), 2): # xrange(, , step)\n lines.append(mac[_:_+2])\n return ':'.join(lines)\n\ndef rm_colon(mac):\n return mac.replace(':', '')\n\ndef convert_dash(mac):\n return mac.replace('-', ':')\n\ndef main():\n if \":\" in SELECTION:\n macaddy = rm_colon(SELECTION)\n elif '-' in SELECTION:\n macaddy = convert_dash(SELECTION)\n elif \":\" not in SELECTION:\n macaddy = add_colon(SELECTION)\n subprocess.run('pbcopy', input=macaddy.encode(), check=False)\n\nSELECTION = stdin.read()\n\ntry:\n main()\nexcept Exception as e:\n syslog.syslog(syslog.LOG_ALERT, f\"~km~ {e}\")\n exit(1)\n","repo_name":"bryanheinz/keyboard-maestro","sub_path":"text-manipulation/macaddr.py","file_name":"macaddr.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"20412675979","text":"import pytest\nfrom httpx import AsyncClient\n\nfrom infrastructure.ioc.container import Container\nfrom main import create_app\n\n\n@pytest.fixture(\n params=[\n pytest.param((\"asyncio\", {\"use_uvloop\": True}), id=\"asyncio+uvloop\"),\n ]\n)\ndef anyio_backend(request):\n return request.param\n\n\n@pytest.fixture(scope=\"session\")\ndef container():\n container = Container()\n container.init_resources()\n yield container\n container.shutdown_resources()\n\n\n@pytest.fixture(scope=\"session\")\ndef fastapi_app(container):\n return create_app(container)\n\n\n@pytest.fixture()\nasync def async_test_client(fastapi_app):\n async with AsyncClient(app=fastapi_app, base_url=\"http://test\") as client:\n yield client","repo_name":"VitalyDubovets/clean-architecture-template","sub_path":"{{cookiecutter.project_slug}}/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"43"} +{"seq_id":"16818284561","text":"n, m= map(int, input().split())\n#연속된 부분의 합이 m으로 나눠 떨어지는 구간의 개수?\nlst = list(map(int, input().split()))\nsm = [0]*n\nsm[0]= lst[0]\nfor i in range(1, n):\n sm[i]= sm[i-1]+lst[i]\nc=[0]*m\nanswer=0\nfor i in range(n):\n remainder = sm[i]%m\n #m으로 나눠 떨어지면 answer에 1더하기\n if remainder == 0:\n answer+=1\n c[remainder]+=1\nfor i in range(m):\n if c[i]>1:\n #2개 조합뽑기\n answer+=(c[i]*(c[i]-1)//2)\n","repo_name":"jiuumm/BICPie","sub_path":"유채빈/나머지합구하기.py","file_name":"나머지합구하기.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"8100580947","text":"\"\"\"\"\nVERSION: V_June22\naliquots a specific volume from 15mL tubes to 96 wells plates\n\nThis version works with api2.12 and includes labware offsets\n\n\n\"\"\"\n# VARIABLES TO SET#!!!=========================================================\n# =============================================================================\n# How many plates you want filled? (max 6 for now)\nnumber_of_plates = 1\n\n# How much volume (µL) to aliquot?\nvolume = 100\n\n# How much volume (µL) in 15mL tubes (all the same volume)\nreagent_volume = 15000\n\n# What is the starting position of the tips?\nstarting_tip_p200 = 'E1'\n\n# Do you want to simulate the protocol?\nsimulate = False\n ## True for simulating protocol, False for robot protocol \n# =============================================================================\n\n# IMPORT STATEMENTS AND FILES==================================================\n# =============================================================================\nfrom opentrons import protocol_api\n ## Import opentrons protocol API v2.\nimport pandas as pd\n ## For accessing offset .csv file\nimport math\n ## To do some calculations \n\n# If not simulated, import the .csv from the robot with robot_specific \n# labware off_set values\nif not simulate: #Robot\n offsets = pd.read_csv(\n \"data/user_storage/mollab_modules/labware_offset.csv\", sep=';'\n )\n ## import .csv\n offsets = offsets.set_index('labware')\n ## remove index column\n from data.user_storage.mollab_modules import volume_tracking_v1 as vt\n ## Volume_tracking module for robot\n\nif simulate: #Simulator\n from mollab_modules import volume_tracking_v1 as vt\n ## Volume_tracking module for simulator\n import json\n ## Import json to import custom labware with labware_from_definition,\n ## so that we can use the simulate_protocol with custom labware. \n# =============================================================================\n\n# CALCULATED VARIABLES=========================================================\n# =============================================================================\nnecessary_volume = volume * (number_of_plates * 96)\n ## How much water is needed for per sample\nnumber_of_tubes = math.ceil((necessary_volume + 2000) / reagent_volume) \n ## How many tubes of 15mL are needed (2mL extra)\n# =============================================================================\n\n# METADATA=====================================================================\n# =============================================================================\nmetadata = {\n 'protocolName': 'aliquoting_from15mL_to96plate.py',\n 'author': 'MB ',\n 'description': ('aliquot from 15mL to plate protocol'),\n 'apiLevel': '2.12'}\n\ndef run(protocol: protocol_api.ProtocolContext):\n \"\"\"\n aliquoting a specific volume from 15mL tubes to 96 wells plates\n \"\"\"\n# =============================================================================\n\n# LOADING LABWARE AND PIPETTES=================================================\n# =============================================================================\n labwares = {}\n ## empty dict to add labware and labware_names to, to loop through\n \n ##### Loading labware\n tips_200 = protocol.load_labware(\n 'opentrons_96_filtertiprack_200ul', \n 10, \n 'tips_200') \n labwares[tips_200] = 'filtertips_200'\n \n tubes_15mL = protocol.load_labware(\n 'opentrons_15_tuberack_falcon_15ml_conical',\n 7, \n 'tubes_15mL') \n labwares[tubes_15mL] = '15mL_tubes'\n \n plate_96_1 = protocol.load_labware(\n 'biorad_96_wellplate_200ul_pcr', \n 1, \n 'plate_96_1') \n labwares[plate_96_1] = 'plate_96'\n \n if number_of_plates >= 2:\n plate_96_2 = protocol.load_labware(\n 'biorad_96_wellplate_200ul_pcr', \n 2, \n 'plate_96_2') \n labwares[plate_96_2] = 'plate_96'\n if number_of_plates >= 3:\n plate_96_3 = protocol.load_labware(\n 'biorad_96_wellplate_200ul_pcr', \n 3, \n 'plate_96_3') \n labwares[plate_96_3] = 'plate_96'\n if number_of_plates >= 4:\n plate_96_4 = protocol.load_labware(\n 'biorad_96_wellplate_200ul_pcr', \n 4, \n 'plate_96_4') \n labwares[plate_96_4] = 'plate_96'\n if number_of_plates >= 5:\n plate_96_5 = protocol.load_labware(\n 'biorad_96_wellplate_200ul_pcr', \n 5, \n 'plate_96_5') \n labwares[plate_96_5] = 'plate_96'\n if number_of_plates >= 6:\n plate_96_6 = protocol.load_labware(\n 'biorad_96_wellplate_200ul_pcr', \n 6, \n 'plate_96_6') \n labwares[plate_96_6] = 'plate_96'\n \n ##### Loading pipettes\n p300 = protocol.load_instrument(\n 'p300_single_gen2', \n 'right', \n tip_racks=[tips_200]) \n# =============================================================================\n\n# LABWARE OFFSET=============================================================== \n# =============================================================================\n if not simulate:\n for labware in labwares:\n offset_x = offsets.at[labwares[labware],'x_offset']\n offset_y = offsets.at[labwares[labware],'y_offset']\n offset_z = offsets.at[labwares[labware],'z_offset']\n labware.set_offset(\n x = offset_x, \n y = offset_y, \n z = offset_z)\n# =============================================================================\n\n# SETTING LOCATIONS#!!!========================================================\n# ============================================================================= \n ##### Setting starting tip\n p300.starting_tip = tips_200.well(starting_tip_p200)\n ## The starting_tip is the location of first pipette tip in the box \n \n ##### Setting tube locations\n reagent = []\n for well in tubes_15mL.wells():\n reagent.append(well)\n reagent = reagent[:number_of_tubes]\n \n aliquots = []\n for well in plate_96_1.wells():\n aliquots.append(well)\n if number_of_plates > 1:\n for well in plate_96_2.wells():\n aliquots.append(well)\n if number_of_plates > 2:\n for well in plate_96_3.wells():\n aliquots.append(well)\n if number_of_plates > 3:\n for well in plate_96_4.wells():\n aliquots.append(well)\n if number_of_plates > 4:\n for well in plate_96_5.wells():\n aliquots.append(well)\n if number_of_plates > 5:\n for well in plate_96_6.wells():\n aliquots.append(well)\n ## Add all wells of all plates to a list \n\n\n# MESSAGE AT THE START=========================================================\n# =============================================================================\n protocol.pause(\"I need \"+ str(number_of_tubes) + \" 15mL tubes. Filled to \"\n + str(reagent_volume/1000) + \" mL with reagent.\") \n# ============================================================================= \n\n\n# TURN RAIL LIGHT ON===========================================================\n# =============================================================================\n protocol.set_rail_lights(True) \n# =============================================================================\n\n\n# ALIQUOTING ================================================================== \n# =============================================================================\n##### Variables for volume tracking and aliquoting\n counter = 0 # to count how many tubes already emptied\n source = reagent[counter]\n destination = aliquots\n start_height = vt.cal_start_height('tube_15mL', reagent_volume)\n current_height = start_height\n container = 'tube_15mL'\n \n ##### aliquoting\n for i, well in enumerate(destination):\n ## aliquot in the correct wells, for each well do the following: \n \n if i == 0: \n p300.pick_up_tip()\n ## If we are at the first well, start by picking up a tip. \n elif i % 24 == 0:\n p300.drop_tip()\n p300.pick_up_tip()\n ## Then, after every 24th well, drop tip and pick up new \n \n current_height, pip_height, bottom_reached = vt.volume_tracking(\n container, volume, current_height)\n ## call volume_tracking function, obtain current_height, \n ## pip_height and whether bottom_reached. \n \n if bottom_reached:\n ## continue with next tube, reset vt \n current_height = start_height\n current_height, pip_height, bottom_reached = (\n vt.volume_tracking(\n container, volume, current_height))\n counter = counter + 1\n source = reagent[counter]\n aspiration_location = source.bottom(current_height)\n protocol.comment(\n \"Continue with tube \" + str(counter + 1) + \" of reagent\")\n \n else:\n aspiration_location = source.bottom(pip_height)\n ## Set the location of where to aspirate from. \n \n #### The actual aliquoting\n p300.aspirate(volume, aspiration_location)\n ## Aspirate the set volume from the source \n p300.dispense(volume + 10, well)\n ## dispense the set volume + extra to avoid drops in the well \n p300.dispense(10, aspiration_location)\n ## Alternative for blow-out \n \n \n p300.drop_tip()\n ## when entire plate is full, drop tip \n# =============================================================================\n\n# TURN RAIL LIGHT OFF==========================================================\n# =============================================================================\n protocol.set_rail_lights(False) \n# ============================================================================= ","repo_name":"MolLabNIOZ/OT2","sub_path":"mollab_protocols/lab_general/aliquot_from15mL_to96plate_Voffsets.py","file_name":"aliquot_from15mL_to96plate_Voffsets.py","file_ext":"py","file_size_in_byte":11141,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"43"} +{"seq_id":"13484941468","text":"import BuildComposer.src.buildcomposer as bc_script\nimport unittest\nimport unittest.mock\nimport io\nimport os\n\nclass Test_TestDirectoryOperations(unittest.TestCase):\n def setUp(self):\n # release, path, wipe, verbose, start\n self.args = bc_script.Arguments(\"v2.0.0\", \"C:\\ComposerTests\", True, False, False)\n self.dir = \"Composer %s\" % self.args.release\n bc_script.change_dir(self.args)\n\n def test_mkdir_new(self):\n bc_script.make_composer_dir(self.args)\n self.assertTrue(os.path.isdir(os.path.join(self.args.path, self.dir)))\n\n @unittest.mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_mkdir_prev_exists(self, mock_stdout):\n bc_script.make_composer_dir(self.args)\n expected = \"[Composer %s directory already exists. Please specify -w/--wipe to delete and reinstall this release.]\\n\" % self.args.release\n self.assertEquals(mock_stdout.getvalue(), expected)\n\n def test_wipe(self):\n bc_script.wipe(self.args)\n self.assertFalse(os.path.isdir(os.path.join(self.args.path, self.dir)))\n\n @unittest.mock.patch('sys.stdout', new_callable=io.StringIO)\n def test_wipe_flag_not_set(self, mock_stdout):\n falseArg = bc_script.Arguments(\"v2.0.0\", \"C:\\ComposerTests\", False, False, False)\n bc_script.wipe(falseArg)\n expected = \"\\n[Wipe flag not set. Skipping Deletion]\\n\"\n self.assertEquals(mock_stdout.getvalue(), expected)\n\n","repo_name":"anishprasad01/MSFT-Bot-Scripts","sub_path":"tests/test_buildcomposer.py","file_name":"test_buildcomposer.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"74049163649","text":"import numpy as np\r\nimport cv2\r\n\r\n# Read the images\r\nimg1 = cv2.imread(r'C:\\Users\\Nina\\Documents\\Cours-TP\\PAF\\data\\test5.jpg')\r\nimg2 = cv2.imread(r'C:\\Users\\Nina\\Documents\\Cours-TP\\PAF\\data\\test7.jpg')\r\n\r\n# Convert images to Lab color space\r\nlab1 = cv2.cvtColor(img1, cv2.COLOR_BGR2Lab)\r\nlab2 = cv2.cvtColor(img2, cv2.COLOR_BGR2Lab)\r\n\r\n# Perform thresholding on the a and b channels\r\n_, a1, b1 = cv2.split(lab1)\r\n_, a2, b2 = cv2.split(lab2)\r\nret1, thresh1 = cv2.threshold(a1, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\r\nret2, thresh2 = cv2.threshold(a2, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)\r\n\r\n# Find contours in the thresholded images\r\ncontours1, _ = cv2.findContours(thresh1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\ncontours2, _ = cv2.findContours(thresh2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\nF_similarities = [] # List to store F similarities\r\na_similarities = [] # List to store a similarities\r\nb_similarities = [] # List to store b similarities\r\n\r\n# Iterate over each contour in the first image\r\nfor contour1 in contours1:\r\n # Create a separate mask for the current contour in the first image\r\n contour_mask1 = np.zeros_like(a1)\r\n cv2.drawContours(contour_mask1, [contour1], 0, 255, -1)\r\n\r\n # Apply the mask to the original image to obtain the segmented region in the first image\r\n segmented_region1 = cv2.bitwise_and(lab1, lab1, mask=contour_mask1)\r\n\r\n # Calculate the average Lab values for the segmented region in the first image\r\n avg_color1 = np.mean(segmented_region1, axis=(0, 1))\r\n\r\n # Iterate over each contour in the second image\r\n for contour2 in contours2:\r\n # Create a separate mask for the current contour in the second image\r\n contour_mask2 = np.zeros_like(a2)\r\n cv2.drawContours(contour_mask2, [contour2], 0, 255, -1)\r\n\r\n # Apply the mask to the original image to obtain the segmented region in the second image\r\n segmented_region2 = cv2.bitwise_and(lab2, lab2, mask=contour_mask2)\r\n\r\n # Calculate the average Lab values for the segmented region in the second image\r\n avg_color2 = np.mean(segmented_region2, axis=(0, 1))\r\n\r\n # Calculate the color similarity for each component (F, a, b)\r\n F_similarity = abs(avg_color1[0] - avg_color2[0]) / 100.0\r\n a_similarity = abs(avg_color1[1] - avg_color2[1]) / 128.0\r\n b_similarity = abs(avg_color1[2] - avg_color2[2]) / 128.0\r\n\r\n F_similarities.append(F_similarity)\r\n a_similarities.append(a_similarity)\r\n b_similarities.append(b_similarity)\r\n\r\n# Calculate the average color similarity for each component\r\navg_F_similarity = np.mean(F_similarities)\r\navg_a_similarity = np.mean(a_similarities)\r\navg_b_similarity = np.mean(b_similarities)\r\n\r\nprint('Average F Similarity:', avg_F_similarity)\r\nprint('Average a Similarity:', avg_a_similarity)\r\nprint('Average b Similarity:', avg_b_similarity)\r\n\r\n# Close all windows\r\ncv2.destroyAllWindows()","repo_name":"antoineverier/PAF-Namas","sub_path":"histo_similarity_Lab.py","file_name":"histo_similarity_Lab.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"40014060377","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom PIL import Image\n\n# Profile model to store image for all users \nclass profile(models.Model):\n\n # Here we are mapping(one-to-one) this model with User model to store a image with each user\n user = models.OneToOneField(User, on_delete = models.CASCADE)\n # Image bydefault if any one is not providing any image.\n image = models.ImageField(default = 'default.jpg', upload_to = 'profile_pics')\n\n # String when we query image for a loggedin user\n def __str__(self):\n return f'{self.user.username} profile'\n \n # Now reshape and save that image to database\n def save(self, *args, **kwargs):\n # This is a type of rule to write this\n super().save(*args, **kwargs)\n # Using python image library \n img = Image.open(self.image.path)\n rgb_im = img.convert('RGB')\n if rgb_im.height>300 or rgb_im.width>300:\n output=(300,300)\n rgb_im.thumbnail(output)\n rgb_im.save(self.image.path)","repo_name":"Pushpendra9350/Blog-website-for-job-opening-with-Django","sub_path":"userapp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"2856579278","text":"from itertools import product\nfrom mip import *\nfrom plotnine import *\nimport numpy as np\nimport pandas as pd\nimport random\nfrom copy import deepcopy\nimport time\nimport statistics\nfrom pulp import *\nimport matplotlib.pyplot as plt\n\n# simulation for the 1-dim feedback model\ndef feedbackSim(n_state, T, workerArriveProb, jobArriveProb, beta, rewards, transitions, bigK, C, LOCAL_PRICES=True,\n perc = 80, extraPriceAdjustment = 0):\n # UPDATE ON 5.21.2023: This is using the transitions matrix as, element i,j is the prob of moving from i to j\n # initializations #\n recordAfter = T * perc / 100\n eps, counter_conv, tot_reward = 1e-4, 0, 0\n queue, queue_mid, track_assgn = np.zeros(n_state), np.zeros(n_state), np.zeros(n_state)\n workerarrival = np.random.binomial(1, (np.ones(T) * workerArriveProb)) # vector of arrivals for workers\n jobarrival = np.random.binomial(1, (np.ones(T) * jobArriveProb)) # vector of arrivals for jobs\n track_mass, track_queues = np.zeros((int(T / 2), n_state + 1)), np.zeros((int(T / 2), n_state + 1))\n # initializations #\n for t in range(T):\n queue[0] += workerarrival[t]\n if (jobarrival[t] == 1) & (queue.sum() > 0): # to assign, I need a job and the system non-empty\n maxval = 0\n for i in range(n_state):\n if LOCAL_PRICES:\n price = (bigK - min(bigK, queue[i])) / bigK\n # if using optimal prices\n else:\n if i == 0:\n price = (1 - beta * transitions[0][0]) * (bigK - min(bigK, queue[0])) / bigK - \\\n beta * transitions[0][1] * (bigK - min(bigK, queue[1])) / bigK\n elif i == (n_state - 1):\n price = (1 - beta * transitions[i][i]) * (bigK - min(bigK, queue[i])) / bigK - \\\n beta * transitions[i][i - 1] * (bigK - min(bigK, queue[i - 1])) / bigK\n else:\n price = (1 - beta * transitions[i][i]) * (bigK - min(bigK, queue[i])) / bigK - \\\n beta * transitions[i][i + 1] * (bigK - min(bigK, queue[i + 1])) / bigK - \\\n beta * transitions[i][i - 1] * (bigK - min(bigK, queue[i - 1])) / bigK\n if (maxval < (rewards[i] - C * price + extraPriceAdjustment * (1 - i))) & (queue[i] > 0):\n maxval = rewards[i] - C * price + extraPriceAdjustment * (1 - i)\n assigned = i\n if maxval > 0:\n queue[assigned] -= 1 # remove the assigned worker\n if (queue < 0).any():\n print(\"oops, a non-existent worker left.\")\n break\n track_assgn[assigned] += 1 # keep track of the assignment, update the counter\n reward = np.random.binomial(1, rewards[assigned]) if rewards[assigned] > 0 \\\n else -1 * np.random.binomial(1, -rewards[assigned]) # sample its reward\n if t > recordAfter:\n tot_reward += reward\n stay = np.random.binomial(1, beta) # see if it will stay\n\n if stay == 1: # if the assigned worker is staying\n move = random.uniform(0, 1) # decide which way it will move\n if assigned < (n_state - 1):\n if move <= transitions[assigned][assigned + 1]: # it moves forward\n # if move <= transitions[assigned][0]: # it moves forward\n queue[assigned + 1] += 1\n elif (move > transitions[assigned][assigned + 1]) & \\\n (move <= transitions[assigned][assigned + 1] + transitions[assigned][assigned]):\n # elif (move > transitions[assigned][0]) & \\\n # (move <= transitions[assigned][0] + transitions[assigned][1]):\n queue[assigned] += 1\n else: # it moves backwards\n queue[assigned - 1] += 1\n else: # if the assigned worker is in the last state\n if move <= transitions[assigned][assigned]: # remains\n # if move <= transitions[assigned][0] + transitions[assigned][1]: # remains\n queue[assigned] += 1\n else: # it moves backwards\n queue[assigned - 1] += 1\n for j in range(n_state):\n queue[j] = min(bigK, queue[j])\n queue_mid[j] += queue[j]\n\n # keep track of assignments\n if int((t + 1) / 2) == ((t + 1) / 2):\n track_mass[counter_conv][0] = counter_conv + 1\n track_queues[counter_conv][0] = counter_conv + 1\n for j in range(n_state):\n track_mass[counter_conv][j + 1] = track_assgn[j] / (t + 1)\n track_queues[counter_conv][j + 1] = queue[j] # queue_mid[j] / (t + 1)\n counter_conv += 1\n tot_reward = tot_reward / (T - recordAfter)\n return track_mass, tot_reward, track_queues\n\n\ndef feedbackOptFixedPoint(n, lambd, mu, bounds, transitions, rewardMult, beta, slacks, whichobj):\n m = LpProblem(\"p\", LpMaximize)\n x = LpVariable.dicts(\"x\", (range(n)), lowBound=0)\n y = LpVariable(\"y\", 0)\n\n if whichobj == 1:\n m += lpSum([x[i] for i in range(n)])\n elif whichobj == 0:\n m += -y\n else:\n m += lpSum([x[i] * rewardMult[i] for i in range(n)])\n\n for ii in range(len(slacks)):\n j = slacks[ii]\n if j == 0:\n m += lambd + beta * transitions[0][0] * x[0] + beta * transitions[1][0] * x[1] - x[0] == 0\n elif j == (n - 1):\n m += beta * transitions[n - 2][n - 1] * x[n - 2] + \\\n beta * transitions[n - 1][n - 1] * x[n - 1] - x[n - 1] == 0\n else:\n m += beta * transitions[j - 1][j] * x[j - 1] + \\\n beta * transitions[j][j] * x[j] + beta * transitions[j + 1][j] * x[j + 1] - x[j] == 0\n\n m += x[0] <= lambd + beta * transitions[0][0] * x[0] + beta * transitions[1][0] * x[1]\n m += y >= lambd + beta * transitions[0][0] * x[0] + beta * transitions[1][0] * x[1] - x[0]\n m += x[n - 1] <= beta * transitions[n - 2][n - 1] * x[n - 2] + beta * transitions[n - 1][n - 1] * x[n - 1]\n m += y >= beta * transitions[n - 2][n - 1] * x[n - 2] + beta * transitions[n - 1][n - 1] * x[n - 1] - x[n - 1]\n for j in range(n):\n m += x[j] <= bounds[j]\n for j in range(1, n - 1):\n m += x[j] <= beta * transitions[j - 1][j] * x[j - 1] + \\\n beta * transitions[j][j] * x[j] + beta * transitions[j + 1][j] * x[j + 1]\n m += y >= beta * transitions[j - 1][j] * x[j - 1] + \\\n beta * transitions[j][j] * x[j] + beta * transitions[j + 1][j] * x[j + 1] - x[j]\n\n m += lpSum([x[j] for j in range(n)]) == mu\n # m.writeLP(\"lp.txt\")\n\n res = not m.solve(PULP_CBC_CMD(msg=False)) == LpSolutionOptimal\n\n soln_sub = np.zeros(n)\n obj_ = 0\n for i in range(n):\n soln_sub[i] = value(x[i])\n obj_ += soln_sub[i] * rewardMult[i]\n return soln_sub, obj_, res\n\n\n# use fixed point alg\ndef feedbackFixedPoint(n, lambd, mu, transition, rewardMult, beta, verbal=True):\n # I need x_0 positive, so I can move things faster if I initially start with a setting where x_0 > 0 the first time\n rewardMult_sortedIndices = np.argsort(rewardMult)[::-1]\n # start with making everybody before, and including, 0 positive\n position_0 = np.where(rewardMult_sortedIndices == 0)[0][0]\n check_feasible = True\n include_until = position_0 + 1\n soln, soln_b, soln_c = 0, 0, 0\n returnObj = -100\n returnSoln = np.zeros(n)\n\n while check_feasible & (include_until <= n + 1): # solve for the variables until and including position_0\n ubs = np.zeros(n)\n force_slacks = rewardMult_sortedIndices[0:(include_until - 1)]\n for i in range(min(include_until, n)): # give upper bounds of one for the states I want to include\n ubs[rewardMult_sortedIndices[i]] = mu\n if verbal:\n print(\"Upper bounds on masses\", ubs)\n print(\"Force\", force_slacks, \"to have zero slacks\")\n soln, obj, res = feedbackOptFixedPoint(n, lambd, mu, ubs, transition, rewardMult, beta, force_slacks, 1)\n soln_b, obj_b, res_b = feedbackOptFixedPoint(n, lambd, mu, ubs, transition, rewardMult, beta, force_slacks, 0)\n soln_c, obj_c, res_c = feedbackOptFixedPoint(n, lambd, mu, ubs, transition, rewardMult, beta, force_slacks, -1)\n if not res:\n if verbal:\n print(\"Maximize sums of masses\", obj, end=\"; \")\n print(soln)\n if obj > returnObj:\n returnObj = obj\n returnSoln = soln\n else:\n if verbal:\n print(\"Maximize sums of masses infeasible\")\n if verbal:\n print()\n if not res_b:\n if verbal:\n print(\"Minimize the slacks\", obj_b, end=\"; \")\n print(soln_b)\n if obj_b > returnObj:\n returnObj = obj_b\n returnSoln = soln\n else:\n if verbal:\n print(\"Minimize the slacks infeasible\")\n if verbal:\n print()\n if not res_c:\n if verbal:\n print(\"Maximize the reward\", obj_c, end=\"; \")\n print(soln_c)\n if obj_c > returnObj:\n returnObj = obj_c\n returnSoln = soln\n else:\n if verbal:\n print(\"Maximize the reward infeasible\")\n if verbal:\n print()\n include_until += 1\n\n return returnSoln, returnObj\n\n\n# direct dual of the feedback model\ndef feedbackDual(n, lambd, mu, transitions, rewardMult, beta):\n # UPDATE ON 5.21.2023: This is using the transitions matrix as, element i,j is the prob of moving from i to j\n m = LpProblem(\"p\", LpMinimize)\n g = LpVariable.dicts(\"gamma\", (range(n)), lowBound=0)\n alpha = LpVariable(\"alpha\", 0)\n m += lpSum(g[0] * lambd + alpha * mu)\n\n # m = Model()\n # g = [m.add_var(name='gamma({})'.format(i + 1), lb=0) for i in range(n)]\n # alpha = m.add_var(name='cap', lb=0)\n # m.objective = minimize(g[0] * lambd + alpha * mu)\n\n for j in range(n):\n if j == 0:\n m += alpha >= g[0] * (beta * transitions[0][0] - 1) + g[1] * (beta * transitions[0][1]) + rewardMult[0]\n elif j == (n - 1):\n m += alpha >= g[n - 2] * (beta * transitions[n - 1][n - 2]) + \\\n g[n - 1] * (beta * transitions[n - 1][n - 1] - 1) + rewardMult[n - 1]\n else:\n m += alpha >= g[j - 1] * (beta * transitions[j][j - 1]) + g[j + 1] * (beta * transitions[j][j + 1]) + \\\n g[j] * (beta * transitions[j][j] - 1) + rewardMult[j]\n\n # m.optimize()\n m.solve(PULP_CBC_CMD(msg=False))\n\n print('Optimal dual objective value is ', value(g[0]) * lambd + value(alpha) * mu)\n for i in range(n):\n print(value(g[i]), end=\"\")\n print(\", \", end=\"\") if i < n - 1 else print(\".\")\n print(\"alpha\", value(alpha))\n soln = np.zeros(n)\n for i in range(n):\n soln[i] = value(g[i])\n return soln\n\n\n# dual of the feedback model using a fixed point\ndef feedbackDualUseFixedPoint(n, lambd, mu, transitions, rewardMult, beta, x):\n rhs = np.zeros(n)\n rhs[0] = lambd + beta * transitions[0][0] * x[0] + beta * transitions[1][0] * x[1]\n rhs[n - 1] = beta * transitions[n - 2][n - 1] * x[n - 2] + beta * transitions[n - 1][n - 1] * x[n - 1]\n for j in range(1, n - 1):\n rhs[j] = beta * transitions[j - 1][j] * x[j - 1] + beta * transitions[j][j] * x[j] + \\\n beta * transitions[j + 1][j] * x[j + 1]\n\n m = LpProblem(\"p\", LpMinimize)\n g = LpVariable.dicts(\"gamma\", (range(n)), lowBound=0)\n alpha = LpVariable(\"alpha\", 0)\n m += lpSum([g[i] * rhs[i] for i in range(n)] + alpha * mu)\n\n for j in range(n):\n m += g[j] + alpha >= rewardMult[j]\n\n m.solve(PULP_CBC_CMD(msg=False))\n soln = np.zeros(n)\n obj = 0\n for i in range(n):\n soln[i] = value(g[i])\n obj += value(g[i]) * rhs[i]\n obj += value(alpha) * mu\n print('Dual objective value is ', obj, 'dual solution alpha is', value(alpha))\n return soln\n\n\n# lp of the feedback model\ndef feedbackOpt(n, lambd, mu, prevSoln, usePrevSoln, transitions, rewardMult, beta):\n m = LpProblem(\"p\", LpMaximize)\n x = LpVariable.dicts(\"x\", (range(n)), lowBound=0)\n m += lpSum([x[i] * rewardMult[i] for i in range(n)])\n\n if ~usePrevSoln:\n m += x[0] <= lambd + beta * transitions[0][0] * x[0] + beta * transitions[1][0] * x[1]\n m += x[n - 1] <= beta * transitions[n - 2][n - 1] * x[n - 2] + beta * transitions[n - 1][n - 1] * x[n - 1]\n for j in range(1, n-1):\n m += x[j] <= beta * transitions[j - 1][j] * x[j - 1] + \\\n beta * transitions[j][j] * x[j] + beta * transitions[j + 1][j] * x[j + 1]\n else:\n m += x[0] <= lambd + beta * transitions[0][0] * prevSoln[0] + beta * transitions[1][0] * prevSoln[1]\n m += x[n - 1] <= beta * transitions[n - 2][n - 1] * prevSoln[n - 2] + \\\n beta * transitions[n - 1][n - 1] * prevSoln[n - 1]\n for j in range(1, n - 1):\n m += x[j] <= beta * transitions[j - 1][j] * prevSoln[j - 1] + beta * transitions[j][j] * prevSoln[j] + \\\n beta * transitions[j + 1][j] * prevSoln[j + 1]\n\n m += lpSum([x[j] for j in range(n)]) <= mu\n\n m.solve(PULP_CBC_CMD(msg=False))\n soln_sub = np.zeros(n)\n obj_ = 0\n capacity = 0\n\n slacks = np.zeros(n)\n slacks[0] = lambd + beta * transitions[0][0] * value(x[0]) + beta * transitions[1][0] * value(x[1]) - value(x[0])\n slacks[n - 1] = beta * transitions[n - 2][n - 1] * value(x[n - 2]) + \\\n beta * transitions[n - 1][n - 1] * value(x[n - 1]) - value(x[n - 1])\n for j in range(1, n - 1):\n slacks[j] = beta * transitions[j - 1][j] * value(x[j - 1]) + beta * transitions[j][j] * value(x[j]) + \\\n beta * transitions[j + 1][j] * value(x[j + 1]) - value(x[j])\n\n for i in range(n):\n soln_sub[i] = value(x[i])\n obj_ += soln_sub[i] * rewardMult[i]\n print(\"Objective is \", obj_)\n for i in range(n):\n print(\"State \", i, \" has \", value(x[i]), \" with slack \", slacks[i])\n capacity += value(x[i])\n print(\"Using capacity \", capacity)\n\n return soln_sub, obj_, capacity\n\n\ndef simModuleLinear(state, numsim, workerArrivalProb = 1, jobArrivalProb = 1, wsp = 0.99): # to get the histograms of price deviations for ML-A and ML-B instances\n willPrint = False # for printing result to a csv\n vocal = True # for printing extra information about each instance\n wantToPlot = True # plotting prices (and saving them)\n MLmodel = \"B\" # \"A\" or \"B\" ; to pick the ordering of the rewards\n\n if numsim > 5:\n willPrint = True\n print(\"Will print results to a csv.\")\n keepRewards = np.zeros((numsim + 10, 8))\n objThing = False\n if MLmodel == \"B\":\n objThing = True\n if objThing:\n print(\"Must be doing ML-B.\")\n else:\n print(\"Must be doing ML-A.\")\n\n\n ss = 0\n while ss < numsim:\n print(\"\\nIteration\", ss + 1, end=\", \")\n if numsim > 1:\n workerArrivalProb = random.uniform(0.15, 0.25)\n if numsim > 1:\n jobArrivalProb = random.uniform(0.5, 0.75)\n if numsim > 1:\n wsp = random.uniform(0.8, 0.98)\n # rewardMultipliers = [-0.5, 1]\n # cC = 2 * max(rewardMultipliers)\n # transition = np.zeros((state, 3))\n # transition[0][0] = 1\n # transition[1][1] = 1\n extraPriceAdjustment = 0 # 0.75\n ############################################################################################################\n rewardMultipliers = np.array(sorted(random.sample(range(10, 100), state), reverse=objThing))\n rewardMultipliers = rewardMultipliers / (max(rewardMultipliers) + min(rewardMultipliers))\n if vocal:\n print(\"Rewards\\n\", rewardMultipliers)\n print(\"ML-A model!\") if rewardMultipliers[0] < rewardMultipliers[1] else print(\"ML-B model!\")\n else:\n print(\"ML-A model!\") if rewardMultipliers[0] < rewardMultipliers[1] else print(\"ML-B model!\")\n cC = 2 * max(rewardMultipliers)\n transition = np.zeros((state, 3))\n for j in range(1, state - 1):\n rands = np.array(sorted(random.sample(range(1, 10), 3), reverse=True))\n rands = rands / sum(rands)\n transition[j][0], transition[j][1], transition[j][2] = rands[0], rands[1], rands[2]\n rands = np.array(sorted(random.sample(range(1, 10), 2), reverse=True))\n rands = rands / sum(rands)\n transition[0][0], transition[0][1] = rands[0], rands[1]\n rands = np.array(sorted(random.sample(range(1, 10), 2), reverse=True))\n rands = rands / sum(rands)\n transition[state - 1][1], transition[state - 1][2] = rands[0], rands[1]\n # last state either remains or goes backward\n # first state either remains or goes forward\n ############################################################################################################\n # now change transitions so that it's of size state X state and each element gives the movement from state\n # i to state j\n transitionProper = np.zeros((state, state))\n # first column of transition is forward probs\n for i in range(state - 1):\n transitionProper[i][i + 1] = transition[i][0]\n # second column of transition is remain probabilities\n for i in range(state):\n transitionProper[i][i] = transition[i][1]\n # third column of transition is backward probabilities\n for i in range(1, state):\n transitionProper[i][i - 1] = transition[i][2]\n\n # print(transition)\n if vocal:\n print(\"Transitions\\n\", transitionProper)\n transition = transitionProper\n # exit()\n ############################################################################################################\n\n print(\"lambda\", workerArrivalProb, \", mu\", jobArrivalProb, \" beta\", wsp, \"\\n\")\n # solve for the optimal\n print(\"Optimal solution\")\n optSoln, opt_obj_val, jobcon = feedbackOpt(state, workerArrivalProb, jobArrivalProb, np.zeros(state), False,\n transition, rewardMultipliers, wsp)\n # optDualSoln = feedbackDual(state, workerArrivalProb, jobArrivalProb, transition, rewardMultipliers, wsp)\n if jobcon > jobArrivalProb - 1e-8:\n # fixed point\n print(\"\\nLooking at the fixed point\", end=\", \")\n fixedPointSoln, obj_valFixedPoint = feedbackFixedPoint(state, workerArrivalProb, jobArrivalProb,\n transition, rewardMultipliers, wsp, verbal=False)\n print(\"LME/OPT is\", obj_valFixedPoint / opt_obj_val)\n # obj_valFixedPoint = 0\n # for i in range(state):\n # obj_valFixedPoint += fixedPointSoln[i] * rewardMultipliers[i]\n\n print(\"Dual prices using FP with the solution\", fixedPointSoln)\n fixedPointDual = feedbackDualUseFixedPoint(state, workerArrivalProb, jobArrivalProb, transition,\n rewardMultipliers, wsp, fixedPointSoln)\n print(\"fixedPointDual prices\", fixedPointDual)\n maxDualPrice = max(fixedPointDual)\n\n # simulation\n print(\"\\nDoing the simulation\")\n timeHorz = 250000 # number of time periods of each instance\n percent = 90 # exclude the first percent many iterations for reward tracking\n bigK = 1e3\n pathMass, empirical_reward, total_queues = feedbackSim(state, timeHorz, workerArrivalProb, jobArrivalProb,\n wsp, rewardMultipliers, transition, bigK, cC, True,\n percent, extraPriceAdjustment)\n df_qs = pd.DataFrame(total_queues, columns=['Time'.split() + ['State' + str(i) for i in range(state)]],\n dtype=float)\n\n if vocal:\n print(\"Final masses, first column is time\")\n print(pathMass[-1])\n print(\"\\nFinal queue lengths and prices after shaving earlier parts off\")\n # print(df_qs)\n df_qs = df_qs.tail(int(timeHorz / 5))\n # print(df_qs)\n for i in range(state):\n name = 'State' + str(i)\n df_qs[name] = df_qs[name].astype(int)\n namep = 'Price' + str(i)\n df_qs[namep] = df_qs.apply(lambda x: cC * (bigK - min(bigK, x[name])) / bigK, axis=1)\n if vocal:\n print(df_qs)\n print(\"\\n The simulated prices\")\n pricesFromSim = np.zeros(state)\n pricesFromSimActual = np.zeros(state)\n for i in range(state):\n name = 'State' + str(i) # 'Price' + str(i)\n mid = df_qs[name]\n # print(mid)\n midd = mid[mid.columns[0]].values\n # print(midd)\n # pricesFromSimActual[i] = statistics.mean(midd[-int((timeHorz * (1 - percent / 100)) / 2 - 1):])\n pricesFromSimActual[i] = cC * (1 - min(1, statistics.mean(midd[-int((timeHorz * (1 - percent / 100)) / 2 - 1):]) / bigK))\n if MLmodel == 'A':\n if fixedPointDual[i] != 0:\n pricesFromSim[i] = pricesFromSimActual[i]\n\n print(\"Doing ML-B pricing trick!!\")\n if MLmodel == 'B':\n enter = True\n index = -1\n interim = -1e4\n for i in range(state):\n if fixedPointDual[i] == 0 and enter:\n enter = False\n interim = pricesFromSimActual[i]\n index = i\n for i in range(index + 1):\n pricesFromSim[i] = pricesFromSimActual[i] - interim\n\n\n\n\n print(\"Actual prices from simulation\", pricesFromSimActual)\n print(\"Prices I will use to compare the LME\", pricesFromSim)\n print(\"State rewards\", rewardMultipliers)\n # print(fixedPointDual)\n # sth = False\n # for jj in range(state):\n # if fixedPointDual[jj] == 0:\n # sth = True\n # if sth:\n # pricesFromSim[jj] = 0\n # print(pricesFromSim)\n diffprices = np.abs(fixedPointDual - pricesFromSim)\n maxdiff = diffprices.max()\n # pos = np.argmax(diffprices, axis=None)\n keepRewards[ss][0] = opt_obj_val\n keepRewards[ss][1] = empirical_reward\n keepRewards[ss][2] = obj_valFixedPoint / opt_obj_val\n keepRewards[ss][3] = maxdiff / maxDualPrice\n keepRewards[ss][4] = workerArrivalProb\n keepRewards[ss][5] = jobArrivalProb\n keepRewards[ss][6] = wsp\n keepRewards[ss][7] = ss + 1 # index\n ss += 1\n print(keepRewards[max(0, ss - 5):ss,])\n if wantToPlot and keepRewards[ss - 1][3] > 0.5:\n plt.figure(figsize=(7, 5), dpi=100)\n plt.rc('axes', axisbelow=True)\n plt.grid(lw=1.1)\n plt.plot(df_qs['Time'].to_numpy(), df_qs['Price0'].to_numpy(), color='green',\n label='State 0')\n plt.plot(df_qs['Time'].to_numpy(), df_qs['Price1'].to_numpy(), color='red',\n label='State 1')\n plt.plot(df_qs['Time'].to_numpy(), df_qs['Price2'].to_numpy(), color='blue',\n label='State 2')\n # plt.plot(df_qs['Time'].to_numpy(), df_qs['Price3'].to_numpy(), color='purple',\n # label='State 3')\n plt.ylabel('Prices')\n plt.xlabel('Time')\n plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n plt.tight_layout()\n # plt.savefig(\"newFeedbackFigs/instance\" + str(ss - 1) + \"_priceRatio\" + str(keepRewards[ss - 1][3])[:6]\n # + \"_\" + str(state) + \"states.eps\", format='eps', bbox_inches='tight')\n plt.show()\n plt.cla()\n\n # use optimal prices and check performance\n print(\"Doing optimal pricing simulation.\")\n _, _, total_queues = feedbackSim(state, timeHorz, workerArrivalProb, jobArrivalProb, wsp,\n rewardMultipliers, transition, bigK, cC, False)\n df_qs = pd.DataFrame(total_queues, columns=['Time'.split() + ['State' + str(i) for i in range(state)]],\n dtype=float)\n for i in range(state):\n name = 'State' + str(i)\n\n name_forward = 'State' + str(i + 1)\n name_backward = 'State' + str(i - 1)\n namep = 'Price' + str(i)\n\n if 0 < i < state - 1:\n df_qs[namep] = df_qs.apply(\n lambda x: cC * ((1 - wsp * transition[i][i]) * (bigK - min(bigK, x[name])) / bigK -\n wsp * transition[i][i + 1] * (bigK - min(bigK, x[name_forward])) / bigK -\n wsp * transition[i][i - 1] * (bigK - min(bigK, x[name_backward])) / bigK),\n axis=1)\n elif i == 0:\n df_qs[namep] = df_qs.apply(\n lambda x: cC * ((1 - wsp * transition[i][i]) * (bigK - min(bigK, x[name])) / bigK -\n wsp * transition[i][i + 1] * (bigK - min(bigK, x[name_forward])) / bigK),\n axis=1)\n elif i == state - 1:\n df_qs[namep] = df_qs.apply(\n lambda x: cC * ((1 - wsp * transition[i][i]) * (bigK - min(bigK, x[name])) / bigK -\n wsp * transition[i][i - 1] * (bigK - min(bigK, x[name_backward])) / bigK),\n axis=1)\n plt.figure(figsize=(7, 5), dpi=100)\n plt.rc('axes', axisbelow=True)\n plt.grid(lw=1.1)\n plt.plot(df_qs['Time'].to_numpy(), df_qs['Price0'].to_numpy(), color='green',\n label='State 0')\n plt.plot(df_qs['Time'].to_numpy(), df_qs['Price1'].to_numpy(), color='red',\n label='State 1')\n plt.plot(df_qs['Time'].to_numpy(), df_qs['Price2'].to_numpy(), color='blue',\n label='State 2')\n # plt.plot(df_qs['Time'].to_numpy(), df_qs['Price3'].to_numpy(), color='purple',\n # label='State 3')\n plt.ylabel('Prices')\n plt.xlabel('Time')\n plt.legend(bbox_to_anchor=(1.04, 1), loc=\"upper left\")\n plt.tight_layout()\n # plt.show()\n # plt.savefig(\"newFeedbackFigs/instance\" + str(ss - 1) + \"_OptPrices_\" + str(state) + \"states.eps\",\n # format='eps', bbox_inches='tight')\n plt.show()\n plt.cla()\n else:\n print(\"\\nIter \", ss + 1, \" won't give a fixed point b/c the capacity constraint not tight, try again\\n\")\n if willPrint:\n np.savetxt(\"feedbackLMEvsOPTobjvalsAndPriceRatiosML-\" + MLmodel + \"_\" + str(numsim) + \"sims_\" + str(state) +\n \"states.csv\", keepRewards, delimiter=\",\")\n\n\ndef main():\n start = time.time()\n # state = 2 # there are this many states in total\n # numsims = 50\n # simModule(state, numsims)\n # raise SystemExit(0)\n\n # # still large price diff with T = 5M and bigK = 1e4, b/c not enough accumulation in state with theoretical price = 0\n # # which is state 2, price0 = 0.29090909, price1 = 0.08181818; x0 = 0.31798, x1 = 0.26721, x2 = 0.14772\n # # this doesn't really work with smaller or larger bigK and longer sim, I guess beta is too small\n # # the example below this one shows that beta can be dealt with using a smaller bigK\n # # T = 5M and bigK = 1e3 is okay; T = 2M and bigK = 1e3 does not cut it, simulated price0 is still too high\n # T = 5M and bigK = 5e3 is not good, 10% off, needs longer\n # rewards = [0.75454545, 0.54545455, 0.46363636, 0.32727273, 0.24545455]\n # transition = [[0.66666667, 0.33333333, 0],\n # [0.5, 0.3125, 0.1875],\n # [0.42857143, 0.33333333, 0.23809524],\n # [0.5, 0.41666667, 0.08333333],\n # [0.64285714, 0.21428571, 0.14285714]]\n # lambd = 0.1918405227361316\n # muu = 0.7329132945412744\n # beta = 0.8081096159529555\n\n ################## these two are similar in nature, but their fixes are opposite ##################\n # # T = 2M and bigK = 1e4 doesn't work, price3 = 0 but simulated price3 > 0 and everybody is shifted by that amount\n # # price0 = 0.36190476, price1 = 0.11428571, price2 = 0.08571428\n # # x0 = 0.26255719, x1 = 0.18525647, x2 = 0.08721418, x3 = 0.03656579, x4 = 0\n # # T = 1M and bigK = 1e3 works well, so maybe beta is not the main culprit\n # rewards = [0.8, 0.55238095, 0.52380952, 0.43809524, 0.2]\n # transition = [[0.55555556, 0.44444444, 0],\n # [0.42857143, 0.35714286, 0.214285711],\n # [0.5, 0.28571429, 0.214285711],\n # [0.52941176, 0.35294118, 0.11764706],\n # [0.39130435, 0.34782609, 0.2608695711]]\n # lambd = 0.13698232960816656\n # muu = 0.571593636687612\n # beta = 0.8029601749722973\n # T = 1M, bigK = 1e3 is not good because price0 = 0.01, price1 = 0 -- small movements in x1 queue causes simulated\n # price1 to go above zero and so price0 = 0.01 + simPrice1\n # T = 1M, bigK = 1e4 alleviates this a bit, price1 is a lot closer to zero, T = 2M is obviously better\n # T = 5M, bigK = 1e3 doesn't work, price0 = 0.015\n # T = 5M, bigK = 5e3 is okay-ish, price0 = 0.0113\n # rewards = [0.85, 0.84, 0.62, 0.38, 0.15]\n # transition = [[0.9, 0.1, 0],\n # [0.5, 0.42857143, 0.07142857],\n # [0.5, 0.4, 0.1],\n # [0.53333333, 0.4, 0.06666667],\n # [0.375, 0.33333333, 0.29166667]]\n # lambd = 0.24030096207304935\n # muu = 0.5547624676429614\n # beta = 0.8304121604778487\n ################## these two are similar in nature, but their fixes are opposite ##################\n\n state = 3\n rewards = [0.11, 0.1, 1]\n transition = [[0, 1, 0],\n [0, 0, 1],\n [0, 0, 1]]\n lambd = 0.75\n muu = 1\n beta = 0.5\n\n optSoln, opt_obj_val, _ = feedbackOpt(state, lambd, muu, np.zeros(state), False, transition, rewards, beta)\n print(\"Looking at the fixed point\")\n fixedPointSoln = feedbackFixedPoint(state, lambd, muu, transition, rewards, beta)\n print(fixedPointSoln)\n print(\"Looking at the dual prices using fixed point\")\n fixedPointDual = feedbackDualUseFixedPoint(state, lambd, muu, transition, rewards, beta, fixedPointSoln)\n print(fixedPointDual)\n raise SystemExit(0)\n\n cC = 2 * max(rewards)\n timeHorz = 5000000 # number of time periods of each instance\n percent = 80 # exclude the first percent many iterations for reward tracking\n bigK = 5e3\n pathMass, empirical_reward, total_queues = feedbackSim(state, timeHorz, lambd, muu,\n beta, rewards, transition, bigK, cC, True,\n percent)\n print(\"Final masses\")\n print(pathMass[-1])\n df_qs = pd.DataFrame(total_queues, columns=['Time'.split() + ['State' + str(i) for i in range(state)]],\n dtype=float)\n df_qs = df_qs.tail(int(timeHorz / 5))\n print(df_qs)\n for i in range(state):\n name = 'State' + str(i)\n df_qs[name] = df_qs[name].astype(int)\n namep = 'Price' + str(i)\n df_qs[namep] = df_qs.apply(lambda x: cC * (bigK - min(bigK, x[name])) / bigK, axis=1)\n print(df_qs)\n # df_qs.to_csv(\"gettingcorrectprices.csv\", index=False)\n mid = df_qs['Price0']\n midd = mid[mid.columns[0]].values\n # np.savetxt(\"this.csv\", midd[-int((timeHorz * (1 - percent / 100)) / 10):], delimiter=\",\")\n print(\"Price of 0 \", statistics.mean(midd[-int((timeHorz * (1 - percent / 100)) / 2 - 1):]))\n\n end = time.time()\n print(\"It took \", end - start, \" seconds for the whole thing\")\n raise SystemExit(0)\n\n ##### simulation module #####\n state = 5 # there are this many states in total\n ## update lambda, mu and beta as well and get different runs?\n workerArrivalProb = 0.1 # lambda: at each time period, a new worker arrives with this probability\n jobArrivalProb = 0.5 # mu: at each time period, a job arrives with this probability\n wsp = 0.95 # workerstayprobability: probability of worker staying in the system after completing a job\n\n rewardMultipliers = np.array(sorted(random.sample(range(10, 100), state), reverse=True))\n rewardMultipliers = rewardMultipliers / (max(rewardMultipliers) + min(rewardMultipliers))\n print(rewardMultipliers)\n cC = 2 * max(rewardMultipliers)\n transition = np.zeros((state, 3))\n for j in range(1, state):\n rands = np.array(sorted(random.sample(range(1, 10), 3), reverse=False))\n rands = rands / sum(rands)\n transition[j][0], transition[j][1], transition[j][2] = rands[0], rands[1], rands[2]\n rands = np.array(sorted(random.sample(range(1, 10), 2), reverse=False))\n rands = rands / sum(rands)\n transition[0][0], transition[0][1] = rands[0], rands[1]\n print(transition)\n\n sims = 100 # number of different runs\n timeHorz = 250000 # number of time periods of each instance\n percent = 80 # exclude the first percent many iterations for reward tracking\n bigK = 1e3\n empRewards = np.zeros(sims)\n # solve for the optimal\n optSoln, opt_obj_val = feedbackOpt(state, workerArrivalProb, jobArrivalProb, np.zeros(state), False,\n transition, rewardMultipliers, wsp)\n\n for i in range(sims):\n pathMass, empirical_reward, total_queues = feedbackSim(state, timeHorz, workerArrivalProb, jobArrivalProb,\n wsp, rewardMultipliers, transition, bigK, cC, True, percent)\n empRewards[i] = empirical_reward\n # df_mass = pd.DataFrame(pathMass, columns=['Time'.split() + ['State' + str(i) for i in range(state)]], dtype=float)\n # df_mass['Time'] = df_mass['Time'].astype(int)\n # for j in range(state):\n # name = 'State' + str(j)\n # plot = ggplot(df_mass) + aes(x='Time', y=name) + geom_line() + geom_hline(yintercept=optSoln[j], color=\"red\")\n # name = \"T\" + str(i) + ', State' + str(j)\n # ggsave(plot, filename=name)\n print(\"Iter \", i + 1)\n print(pathMass[-1])\n print(total_queues[-1])\n print()\n print(\"Optimal reward is \", opt_obj_val)\n print(\"Empirical rewards are\")\n print(empRewards)\n diff1 = (opt_obj_val - empRewards) / opt_obj_val * 100\n print(\"Empirical rewards compared to the optimal reward (in terms of percentage difference):\")\n print(diff1)\n diff2 = empRewards / opt_obj_val * 100\n print(\"\\n Empirical rewards compared to the optimal reward (in terms of ratio to optimal value):\")\n print(diff2)\n ##### simulation module #####\n end = time.time()\n print(\"It took \", end - start, \" seconds for the whole thing\")\n print(\"Rewards are\")\n print(rewardMultipliers)\n print(\"Transitions are\")\n print(transition)\n raise SystemExit(0)\n\n state = 5 # there are this many states in total\n timeHorz = 10000000 # number of time periods\n workerArrivalProb = 0.1 # lambda: at each time period, a new worker arrives with this probability\n jobArrivalProb = 0.45 # mu: at each time period, a job arrives with this probability\n wsp = 0.95 # workerstayprobability: probability of worker staying in the system after completing a job\n bigK = 1e3\n usingLocalPrices = True\n # rewardMultipliers = [(i + 1) / (i + 2) for i in range(state)]\n rewardMultipliers = [(i + 3) / (2 * i + 4) for i in range(state)]\n # rewardMultipliers = [((state / 3 - (state / 2 - i) * (state / 2 - i) / state) / (state / 3))\n # / (i % 2 + 1) for i in range(state)]\n # rewardMultipliers[0] = 0.8\n print(rewardMultipliers)\n cC = 2 * max(rewardMultipliers) # / (1 - wsp)\n transition = np.zeros((state, 3))\n transition[0][0], transition[0][1] = 1 / 2, 1 / 2\n transition[state - 1][0], transition[state - 1][1], transition[state - 1][2] = 1 / 2, 3 / 8, 1 / 8\n for i in range(1, state - 1):\n transition[i][0], transition[i][1] = 1 / 2, 1 / 3\n transition[i][2] = 1 - (transition[i][0] + transition[i][1])\n print(transition)\n print()\n\n # first call the algorithm to find a/the fixed point\n print('doing alg results')\n fixedPoint = feedbackFixedPoint(state, workerArrivalProb, jobArrivalProb, transition, rewardMultipliers, wsp)\n # print(fixedPoint)\n # raise SystemExit(0)\n obj_val = 0\n for i in range(state):\n obj_val += fixedPoint[i] * rewardMultipliers[i]\n print()\n\n # then solve the dual for the fixed point\n print('doing fixed point dual results')\n fixedPointDual = feedbackDualUseFixedPoint(state, workerArrivalProb, jobArrivalProb, transition,\n rewardMultipliers, wsp, fixedPoint)\n print(fixedPointDual)\n print()\n\n # then call the optimization problem to find a/the fixed point using it\n print('solving the optimization problem')\n usePreviousSoln = False\n previousSoln = np.zeros(state)\n tolerance = 1e-8\n max_abs_diff = 1\n max_iter = 10\n iteration = 0\n # loop over the iterations #\n while (max_abs_diff > tolerance) & (iteration < max_iter):\n print(\"iteration \", iteration + 1)\n optSoln, opt_obj_val = feedbackOpt(state, workerArrivalProb, jobArrivalProb, previousSoln, usePreviousSoln,\n transition, rewardMultipliers, wsp)\n max_abs_diff = np.max(np.abs(previousSoln - optSoln))\n previousSoln = deepcopy(optSoln)\n usePreviousSoln = True\n iteration += 1\n print(\"Did \", iteration, \" iterations\")\n # loop over the iterations #\n\n raise SystemExit(0)\n print('do the simulation')\n pathMass, empirical_reward, total_queues = feedbackSim(state, timeHorz, workerArrivalProb, jobArrivalProb,\n wsp, rewardMultipliers, transition, bigK, cC, usingLocalPrices)\n # dataframes\n df_mass = pd.DataFrame(pathMass, columns=['Time'.split() + ['State' + str(i) for i in range(state)]], dtype=float)\n df_qs = pd.DataFrame(total_queues, columns=['Time'.split() + ['State' + str(i) for i in range(state)]], dtype=float)\n print()\n print('Fixed point objective value is ', obj_val, 'Empirical average reward is ', empirical_reward / timeHorz,\n \", off by %.4f%%\" % (np.abs(obj_val - empirical_reward / timeHorz) / obj_val * 100))\n print()\n df_mass['Time'] = df_mass['Time'].astype(int)\n df_qs['Time'] = df_qs['Time'].astype(int)\n print(df_qs)\n for i in range(state):\n name = 'State' + str(i)\n df_qs[name] = df_qs[name].astype(int)\n namep = 'Price' + str(i)\n if usingLocalPrices:\n df_qs[namep] = df_qs.apply(lambda x: cC * (bigK - min(bigK, x[name])) / bigK, axis=1)\n else:\n name_p = 'State' + str(i + 1)\n name_m = 'State' + str(i - 1)\n if i == 0:\n df_qs[namep] = df_qs.apply(lambda x: cC * ((bigK - min(bigK, x[name])) / bigK - wsp *\n transition[i][0] * (bigK - min(bigK, x[name_p])) / bigK), axis=1)\n elif i == (state - 1):\n df_qs[namep] = df_qs.apply(lambda x: cC * ((bigK - min(bigK, x[name])) / bigK - wsp *\n transition[i][2] * (bigK - min(bigK, x[name_m])) / bigK), axis=1)\n else:\n df_qs[namep] = df_qs.apply(lambda x: cC * ((bigK - min(bigK, x[name])) / bigK - wsp *\n transition[i][0] * (bigK - min(bigK, x[name_p])) / bigK - wsp *\n transition[i][2] * (bigK - min(bigK, x[name_m])) / bigK), axis=1)\n namepap = 'PriceAdjPayoff' + str(i)\n df_qs[namepap] = rewardMultipliers[i] - df_qs[namep]\n\n df_qs_sub = df_qs[(df_qs['Time'] > 1000).to_numpy()]\n # print(df_mass)\n print(df_qs_sub)\n\n # ggplot part\n for i in range(state):\n name = 'State' + str(i)\n plot = ggplot(df_mass) + aes(x='Time', y=name) + geom_line() + geom_hline(yintercept=fixedPoint[i], color=\"red\")\n ggsave(plot, filename=name)\n plot_queue = ggplot(df_qs_sub) + aes(x='Time', y=name) + geom_point(size=0.005)\n nameq = 'Queue' + str(i)\n ggsave(plot_queue, filename=nameq)\n namep = 'Price' + str(i)\n plot_price = ggplot(df_qs_sub) + aes(x='Time', y=namep) + geom_point(size=0.005) + \\\n geom_hline(yintercept=fixedPointDual[i], color=\"red\")\n ggsave(plot_price, filename=namep)\n namepap = 'PriceAdjPayoff' + str(i)\n plot_pap = ggplot(df_qs_sub) + aes(x='Time', y=namepap) + geom_point(size=0.005)\n ggsave(plot_pap, filename=namepap)\n\n # dd = df_qs_sub.iloc[-1:].to_numpy()\n # for i in range(len(dd)):\n # print(dd[i])\n # trying matplotlib\n # giving ValueError: x must be a label or position, talking about Time column, what??\n # df_mass.plot(kind='line', x='Time', y='State0')\n # plt.show()\n","repo_name":"erenozbay/exploreMarket","sub_path":"simEnvironmentsLinear.py","file_name":"simEnvironmentsLinear.py","file_ext":"py","file_size_in_byte":42477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"15926826510","text":"#!/usr/bin/env python3\nimport unittest\n\nfrom storage.role_access import RoleAccess\nfrom storage.role import Role\nfrom storage.exceptions import ConfigError\n\n\nclass TestRoleAccess(unittest.TestCase):\n roles = [\n Role(path='/user1/A/B/', users={'user2'}),\n Role(path='/user1/B/', users={'user2', 'user3'}),\n Role(path='/user2/A/B', users={'user1'}),\n Role(path='/user2/A/B', users={'user1'})\n ]\n\n def test_query(self):\n roles = RoleAccess(storage=None, config_path='data/roles_1.json')\n\n user1_own = roles.by_owner(\"user1\")\n user2_own = roles.by_owner(\"user2\")\n user3_own = roles.by_owner(\"user3\")\n\n self.assertSetEqual(set(user1_own), set(self.roles[:2]))\n self.assertSetEqual(set(user2_own), set(self.roles[2:]))\n self.assertSetEqual(set(user3_own), set())\n\n def test_errors(self):\n with self.assertRaises(ConfigError):\n RoleAccess(None, 'data/not_existing.json')\n with self.assertRaises(ConfigError):\n RoleAccess(None, 'data/roles_wrong.json')\n\n def test_prefixes(self):\n roles = RoleAccess(storage=None, config_path='data/roles_1.json')\n role1 = roles.by_path(\"/user1/A/B/\")\n role1_1 = roles.by_path(\"/user1/A/B/C/D\")\n\n self.assertEqual(role1, self.roles[0])\n self.assertEqual(role1_1, self.roles[0])\n\n role2 = roles.by_path('/user2/A/B')\n self.assertEqual(role2, self.roles[2])\n role2_1 = roles.by_path('/user2/A/')\n self.assertEqual(role2_1, self.roles[3])\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"alexeyden/Project-MSF","sub_path":"src/tests/role_access_test.py","file_name":"role_access_test.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"27492957760","text":"from tools import *\n\ninitial_snr_range = (90., 100.)\nfinal_snr_range = (5., 15.)\nsnr_steps = 17\n\n### single SNR range training\ninitial_snr_range = final_snr_range\nsnr_steps = 0\n\n\n# compute the list of SNR ranges\nlower_snrs = np.linspace(initial_snr_range[0], final_snr_range[0], snr_steps+1)\nupper_snrs = np.linspace(initial_snr_range[1], final_snr_range[1], snr_steps+1)\n# snr_ranges = [(lower_snrs[i], upper_snrs[i]) for i in range(len(lower_snrs))]\nsnr_ranges = list(zip(lower_snrs, upper_snrs))\n\n\nCLSchedClass = PlateauCLScheduler\nCLSched_kwargs = {}\n","repo_name":"gwastro/ml-training-strategies","sub_path":"Pytorch/scheduler_pars.py","file_name":"scheduler_pars.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"43"} +{"seq_id":"2134666580","text":"import sys\ninput = sys.stdin.readline\n\nh,w=(int(x) for x in input().split())\n\nsl=[]\n\nfor _ in range(h):\n s = input()\n sl.append(s[:-1])\n\nfor i in range(h):\n for j in range(w):\n mc=0\n #print(\"in j:\",i,j,\":sl:\",sl[i][j])\n if sl[i][j]!=\"#\":\n for k in range(-1,2):\n #print(\"in k:\",k)\n for l in range(-1,2):\n if (i==0 and k==-1) or (j==0 and l==-1) or (i==h-1 and k==1) or (j==w-1 and l==1):\n continue\n #print(\"in l:\",k,l,\":sl:\",sl[i+k][j+l])\n if sl[i+k][j+l]==\"#\":\n mc+=1\n #print(\"mc\",str(mc))\n if (i==0 and k==-1) or (j==0 and l==-1) or (i==h and k==1) or (i==w and l==1):\n continue\n if j == 0:\n sl[i]=sl[i][j].replace('.',str(mc))+sl[i][j+1:]\n elif j == w-1:\n sl[i]=sl[i][:j]+sl[i][j].replace('.',str(mc))\n else:\n #print(\"else\",sl[i][:j-1])\n sl[i]=sl[i][:j]+sl[i][j].replace('.',str(mc))+sl[i][j+1:]\n #print(\"replaced:\",sl[i],\"sl:\",sl)\n\n#print(sl)\n\nfor i in range(h):\n print(sl[i])","repo_name":"kobayu0902art/AtCoder","sub_path":"Minesweeper.py","file_name":"Minesweeper.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"1990969595","text":"import heapq\nfrom random import randint\nfrom math import dist\nfrom typing import List\nfrom simulation.orbsim_simulation_structs.quadtree import QTNode\nfrom sprites_and_graph_ent.earth import Sphere\nfrom sprites_and_graph_ent.satellite import Satellite\nfrom sprites_and_graph_ent.space_agent import SpaceAgent, AgentActionData\nfrom simulation.a_star import a_star, eucl_dist_qtnode\nimport random\nfrom sprites_and_graph_ent.space_debris import SpaceDebris\n\nMOVE_RANDOMLY = 'move randomly to empty space'\nMOVE_TOWARDS_DEBRIS = 'move towards debris'\nBECOME_DEBRIS = 'become debris'\nCOLLECT_DEBRIS = 'collect debris'\nMOVE_TO_SATELLITE = 'move to satellite'\nIDLE = 'idle'\n\nclass SpaceDebrisCollector(SpaceAgent):\n\n\tdef __init__(self, pos_x: int, pos_y: int, life_time: float, capacity: int, fuel: float, perception_range=8, vel = 20):\n\t\tsuper().__init__(pos_x, pos_y, perception_range)\n\t\tself.life_time = life_time if life_time else random.randint(50, 80) + random.random()\n\t\tself.capacity = capacity if capacity else random.randint(200, 300)\n\t\tself.fuel = fuel if fuel else random.randint(500, 1000) + random.random()\n\t\tself.collected_debris = []\n\t\tself.vel = vel\n\t\tself.action_target: AgentActionData = AgentActionData(-2, None, None, IDLE)\n\t\tself.path_to_target: List = []\n\t\tself.qt_node_target: QTNode = None\n\t\tself.id = id(self)\n\n\n\tdef __str__(self):\n\t\treturn f'SpaceDebrisCollector{self.id}(Lifetime:{self.life_time}, Capacity:{self.capacity}, Fuel:{self.fuel}, PerceptionRange:{self.perception_range}, Vel:{self.vel}'\n\n\t@property\n\tdef empty_fuel_tank(self):\n\t\treturn self.fuel <= 0\n\n\t@property\n\tdef unusable(self):\n\t\treturn self.life_time <= 0\n\n\tdef options(self):\n\t\tif self.desires:\n\t\t\tself.desires.clear()\n\n\t\tvisited: List[QTNode] = []\n\t\tpossible_random_moves = []\n\t\tperceived_env = [(self.beliefs, 0)]\n\t\tself.desires = []\n\n\t\tif self.life_time:\n\t\t\twhile(perceived_env):\n\t\t\t\tcurr_env, at_range = perceived_env.pop(0)\n\t\t\t\tif at_range < self.perception_range:\n\t\t\t\t\tfor qt_node in curr_env.neighbors:\n\t\t\t\t\t\tif qt_node not in visited:\n\t\t\t\t\t\t\tvisited.append(qt_node)\n\t\t\t\t\t\t\tself_object = False\n\t\t\t\t\t\t\tif qt_node.objects:\n\t\t\t\t\t\t\t\tfor object in qt_node.objects:\n\t\t\t\t\t\t\t\t\tif object != self:\n\t\t\t\t\t\t\t\t\t\tdistance = dist((self.pos_x, self.pos_y), object.rect.center)\n\t\t\t\t\t\t\t\t\t\tif isinstance(object, SpaceDebris):\n\t\t\t\t\t\t\t\t\t\t\tif object.area < self.capacity:\n\t\t\t\t\t\t\t\t\t\t\t\tif self.fuel*5 >= distance:\n\t\t\t\t\t\t\t\t\t\t\t\t\theapq.heappush(self.desires, AgentActionData(distance, qt_node, object,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tCOLLECT_DEBRIS if at_range == 0 else MOVE_TOWARDS_DEBRIS))\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tself_object = True \n\t\t\t\t\t\t\t\t\t\tperceived_env.append((qt_node, 0))\n\n\t\t\t\t\t\t\telse: possible_random_moves.append(qt_node)\n\n\t\t\t\t\t\t\tif not self_object:\n\t\t\t\t\t\t\t\tperceived_env.append((qt_node, at_range + 1))\n\t\t\t\t\n\t\tif not self.desires:\n\t\t\tif not self.empty_fuel_tank and not self.unusable:\n\t\t\t\t# print(f'random_move to {random_move}')\n\t\t\t\trandom_move = randint(0, len(possible_random_moves) - 1)\n\t\t\t\theapq.heappush(self.desires, AgentActionData(-3, possible_random_moves[random_move], None, MOVE_RANDOMLY))\n\t\t\t\n\t\t\telse:\n\t\t\t\theapq.heappush(self.desires, AgentActionData(-3, None, None, BECOME_DEBRIS))\n\t\t\n\t\ttop_priority_target: 'AgentActionData' = heapq.heappop(self.desires)\n\n\t\tif self.action_target.action == IDLE:\n\t\t\tself.action_target = top_priority_target\n\t\t\tself.pursue_goal()\n\n\t\telif top_priority_target.best_action_to_change(self.action_target):\n\t\t\tself.action_target = top_priority_target\n\t\t\tself.pursue_goal()\n\n\tdef pursue_goal(self):\n\t\tif self.action_target.action == MOVE_RANDOMLY or self.action_target.action == MOVE_TOWARDS_DEBRIS:\n\t\t\tif not any(isinstance(object, Sphere) for object in self.action_target.qt_node.objects):\n\t\t\t\tself.path_to_target = a_star(self.beliefs, self, eucl_dist_qtnode, self.action_target.qt_node)\n\t\t\t\tif self.path_to_target:\n\t\t\t\t\tself.qt_node_target = self.path_to_target.pop(0)\n\t\t\t\t\n\t\t\t\telse: self.action_target = AgentActionData(-2, None, None, IDLE)\n\n\t\telif self.action_target.action == COLLECT_DEBRIS:\n\t\t\tself.capacity -= self.action_target.object.area\n\t\t\tself.fuel -= self.action_target.object.area/2\n\t\t\tself.collected_debris.append(self.action_target.object)\n\t\t\tself.action_target = AgentActionData(-2, None, None, IDLE)\n\n\t\telif self.action_target.action == BECOME_DEBRIS:\n\t\t\tself.action_target = AgentActionData(-2, None, None, IDLE)\n\t\t\treturn self\n\t\n\tdef update(self):\n\t\tself.life_time -= 0.01\n\n\t\tif (self.action_target and (self.action_target.action == MOVE_TOWARDS_DEBRIS or self.action_target.action == MOVE_RANDOMLY)):\n\t\t\tdiff_x = self.qt_node_target.center_x - self.pos_x\n\t\t\tdiff_y = self.qt_node_target.center_y - self.pos_y\n\t\t\tnorm = dist(((self.pos_x), (self.pos_y)), (self.qt_node_target.center_x, self.qt_node_target.center_y))\n\n\t\t\tif norm:\n\t\t\t\tnormalize = (diff_x/round(norm), diff_y/round(norm))\n\t\t\t\t\n\t\t\t\tspeed = (round(normalize[0]*self.vel), round(normalize[1]*self.vel))\n\t\t\t\tnew_pos_x = self.pos_x + speed[0] if abs(speed[0]) < abs(diff_x) else self.qt_node_target.center_x\n\t\t\t\tnew_pos_y = self.pos_y + speed[1] if abs(speed[1]) < abs(diff_y) else self.qt_node_target.center_y\n\t\t\t\t\n\t\t\t\tdist_traveled = dist((new_pos_x, new_pos_y), (self.pos_x, self.pos_y))\n\t\t\t\tself.fuel -= dist_traveled/5\n\t\t\t\tself.rect.center = [new_pos_x, new_pos_y]\n\n\t\t\telse:\n\t\t\t\tif self.path_to_target:\n\t\t\t\t\tself.qt_node_target = self.path_to_target.pop(0)\n\t\t\t\t\n\t\t\t\telse: self.action_target = AgentActionData(-2, None, None, IDLE)\n\t\t\t\t\t\n\n\n\n\t\t\n\n\n\t\t\n\n\n","repo_name":"dmguezjaviersnet/IA-Sim-Comp-Project","sub_path":"orb_simulator/sprites_and_graph_ent/space_debris_collector.py","file_name":"space_debris_collector.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"43"} +{"seq_id":"35887108143","text":"# code8.py\n\nimport threading\nimport logging\nimport time\n\nlogging.basicConfig(level=logging.DEBUG, format='(%(threadName)-10s)'\n ' %(message)s')\n\nclass DaemonThread(threading.Thread):\n \n def __init__(self, t):\n super().__init__()\n self.t = t\n self.daemon = True\n \n def run(self):\n logging.debug('Starting')\n time.sleep(self.t)\n logging.debug('Exiting')\n\n\nclass NonDaemonThread(threading.Thread):\n \n def __init__(self, t):\n super().__init__()\n self.t = t\n self.daemon = True\n \n def run(self):\n logging.debug('Starting')\n time.sleep(self.t)\n logging.debug('Exiting')\n\n# Creating threads\nd = DaemonThread(2)\nt = NonDaemonThread(1)\n\n# Executing threads\nd.start()\nt.start()\n\n# Waiting for the threads finish\nd.join()\nt.join()\n","repo_name":"advancedpythonprogramming/chapter_codes","sub_path":"codes_ch7/code8.py","file_name":"code8.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"43"} +{"seq_id":"19471154453","text":"from dataclasses import replace\nfrom gettext import find\nimport os\nimport shutil\nimport sys\noriPath = os.path.dirname(os.path.abspath(__file__))\nnewPath = oriPath+\"/gen\"\nisExists=os.path.exists(newPath)\n# 判断结果\nprint (newPath)\nif not isExists:\n # 如果不存在则创建目录\n os.makedirs(newPath) \n print (newPath)\nelse:\n print (newPath)\n\nnewInitFileName = newPath+\"/\"+sys.argv[3]\nos.mknod(newInitFileName)\nnewInitFile = open(newInitFileName, 'a', encoding='utf-8')\nfilelist = os.listdir(oriPath)\nfileInitlist = []\nfor filterFile in filelist: \n filename, extension = os.path.splitext(filterFile)\n if (sys.argv[1] in filterFile) & (extension == \".c\") & (filterFile not in sys.argv[2]):\n print(filterFile)\n src = os.path.join(oriPath, filterFile)\n dst = os.path.join(newPath, filterFile)\n shutil.copy(src, dst)\n readFile = open(dst, 'r+', encoding='utf-8')\n content = readFile.read() \n readFile.close\n replaceInitText = filterFile.rstrip(\"\\.c\") + \"_init(void)\"\n newContent = content.replace(\"_init(void)\",replaceInitText)\n if \"_init(void)\" in content: # 判断要替换的内容是否在文本文件中\n writeFile = open(dst, 'w', encoding='utf-8')\n writeFile.write(newContent)\n writeFile.close \n newInitFile.write(\"extern \" + \"void \" + replaceInitText + \";\\n\")\n fileInitlist.append(filterFile.rstrip(\"\\.c\") + \"_init\" + \"();\\n\")\nnewInitFile.write(\"void init_\"+sys.argv[4]+\"(void);\\n\")\nnewInitFile.write(\"void init_\"+sys.argv[4]+\"(void)\\n{\\n\")\nfor fileInitName in fileInitlist:\n newInitFile.write(fileInitName)\nnewInitFile.write(\"}\")\nnewInitFile.close","repo_name":"laiyoufafa/third_party_iptables","sub_path":"extensions/genInit.py","file_name":"genInit.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"40515209980","text":"from ..model import userModel\nfrom ..DictValidate import validateDict\nfrom ..Response import getResponseBaseDict, getResponseMsgString, Enum_ResponseMsg, Enum_ResponseType\n\n\ndef createAccount(registerData):\n _retDict = getResponseBaseDict()\n\n _retDict['type'] = Enum_ResponseType.UserRegister.value\n\n # Verify register data.\n if not validateDict(registerData, ['account', 'name', {'socialInfo': ['facebook', 'github', 'instagram', 'twitter']}, 'password', 'userImage']) or \\\n not userModel.verifyRegisterData(registerData['account'], registerData['password'], registerData['name']):\n _retDict['msg'] = Enum_ResponseMsg.RequestDataInvalid.value\n return (False, _retDict, None)\n\n # Check register account is not exists.\n if userModel.isAccountExists(registerData['account']):\n _retDict['msg'] = Enum_ResponseMsg.RegisterAccountAlreadyExists.value\n return (False, _retDict, None)\n\n # Create account\n _flag, _userId = userModel.createUser(\n registerData['account'], registerData['password'], registerData['name'], registerData['socialInfo'], registerData['userImage'])\n\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.RegisterAccountWasFailed.value\n return (False, _retDict, None)\n\n # Successed\n _retDict['msg'] = Enum_ResponseMsg.Successed.value\n return (True, _retDict, _userId)\n\n\ndef setFollower(userId, targetFollowerId, followStatus):\n \"\"\"\n return True when set follower successed \n retrun False when set follower failed\n\n return format =>(flag , retDict)\n retDict['targetFollowerId]= target id\n retDict['currentStatus'] = is followed? type of bool\n \"\"\"\n _retDict = getResponseBaseDict()\n _retDict['type'] = Enum_ResponseType.UserSetFollower.value\n _targetFollowerId = 0\n # verify function parameters\n try:\n _targetFollowerId = int(targetFollowerId)\n except ValueError:\n _retDict['msg'] = Enum_ResponseMsg.RequestDataInvalid.value\n return (True, _retDict)\n _retDict['targetFollowerId'] = _targetFollowerId\n\n # check user exists and was login.\n if userId is None:\n _retDict['msg'] = Enum_ResponseMsg.NotLogin.value\n return(False, _retDict)\n _flag, _user = userModel.getUser(userId)\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.SessionNotFound.value\n return (False, _retDict)\n\n # set follower\n _flag, _curStatus = userModel.setFollower(\n _user, _targetFollowerId, followStatus)\n\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.UserSetFollowerFailed.value\n return (False, _retDict)\n\n _retDict['msg'] = Enum_ResponseMsg.Successed.value\n _retDict['currentStatus'] = _curStatus\n return (True, _retDict)\n\n\ndef getAuthorInfo(userId, targetAuthorId):\n \"\"\"\n return true when get authorInfo successed \n return false when get authorInfo failed \n return format =>(flag , retDict)\n \"\"\"\n _retDict = getResponseBaseDict()\n _retDict['type'] = Enum_ResponseType.UserGetAuthorInfo.value\n\n _targetAuthorId = 0\n # verify function parameters\n try:\n _targetAuthorId = int(targetAuthorId)\n except ValueError:\n _retDict['msg'] = Enum_ResponseMsg.RequestDataInvalid.value\n return (False, _retDict)\n\n # get user\n _flag, _reader = userModel.getUser(userId)\n\n _flag, _userInfoDict = userModel.getTargetUserInfo(\n _reader, _targetAuthorId)\n\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.UserGetAuthorInfoFailed.value\n return (False, _retDict)\n\n _retDict['userInfo'] = _userInfoDict\n _retDict['msg'] = Enum_ResponseMsg.Successed.value\n return (True, _retDict)\n\n\ndef getUserProfile(userId):\n \"\"\"\n retrun True when get user profile successed\n return Flase when get user profile failed\n\n\n return format =>(flag , retDict)\n retDict['userProfile']\n \"\"\"\n _retDict = getResponseBaseDict()\n _retDict['type'] = Enum_ResponseType.UserProfileGet.value\n\n # check was login\n _flag, _user = userModel.getUser(userId)\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.NotLogin.value\n return (False, _retDict)\n\n # get Profile\n _flag, _userProfileDict = userModel.getUserProfile(_user)\n\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.UserProfileGetFailed.value\n return (False, _retDict)\n\n _retDict['msg'] = Enum_ResponseMsg.Successed.value\n _retDict['userProfile'] = _userProfileDict\n return(True, _retDict)\n\n\ndef udpateUserProfile(userId, userProfileData):\n \"\"\"\n return true when update user-profile successed\n return false when udpate user-profile failed\n\n return format =>(falg , retDict)\n \"\"\"\n\n _retDict = getResponseBaseDict()\n _retDict['type'] = Enum_ResponseType.UserProfileUpdate.value\n _profileData = {\n\n }\n # verify function parmeters\n if not validateDict(userProfileData, ['userImage', {'socialInfo': ['facebook', 'github', 'instagram', 'twitter']}]):\n _retDict['msg'] = Enum_ResponseMsg.RequestDataInvalid.value\n return (False, _retDict)\n\n # check was login\n _flag, _user = userModel.getUser(userId)\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.NotLogin.value\n return (False, _retDict)\n\n # update Profile\n _flag = userModel.updateUserProfile(\n _user, userProfileData)\n\n if not _flag:\n _retDict['msg'] = Enum_ResponseMsg.UserProfileUpdateFailed.value\n return (False, _retDict)\n\n _retDict['msg'] = Enum_ResponseMsg.Successed.value\n return(True, _retDict)\n","repo_name":"SyunSie/sywek_net-back","sub_path":"sywek/controller/userController.py","file_name":"userController.py","file_ext":"py","file_size_in_byte":5578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"18647393068","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2017-10-04\n\n@author: dougashton\n\nThis is one of the more complicated scripts in the suite. It does he following\\\n for every csv file:\n 1. For each column decide a parent child relationship with every other.\n 2. Column A is a parent of column B if:\n a. B is only present when A is present\n b. A is sometimes present when B is not present\n c. If A and B are only seen together then the left-most column in the\\\n data frame is the parent\n 3. Once edges have been defined they are pruned so that grand parents are\\\n not mistaken for parents\n\"\"\"\n\n# %% setup\n\nimport pandas as pd\nimport numpy as np\nimport glob\nimport itertools\nimport os.path\n\n# %% Check correct columns - copied from csvcheck\n\n\ndef check_headers(df, csv):\n \"\"\"This is copied from csv check but the primary goal is to check that\n the csv headers are appropriate for edge detection\"\"\"\n status = True\n cols = df.columns\n\n if cols[0] != 'Year':\n status = False\n print(csv, ': First column not called \"Year\"')\n if cols[-1] != 'Value':\n status = False\n print(csv, ': Last column not called \"Value\"')\n\n return status\n\n# %% Detect the edges\n\n\ndef x_without_y(x, y):\n \"\"\"\n Args:\n x (pandas Series): Left hand column\n y (pandas Series): Right hand column\n \"\"\"\n return np.any(y.isnull() & x.notnull())\n\n\ndef detect_all_edges(df, csv):\n \"\"\"Loop over the data frame and try all pairs\"\"\"\n cols = df.columns\n # Remove the protected columns\n cols = cols[[x not in ['Year', 'Units', 'Value'] for x in cols]]\n\n edges = pd.DataFrame(columns=['From', 'To'])\n\n # Loop over all pairs\n for a, b in itertools.combinations(cols, 2):\n # Check if a and b are ever present without each other\n a_without_b = x_without_y(df[a], df[b])\n b_without_a = x_without_y(df[b], df[a])\n\n if a_without_b and not b_without_a:\n # A is a parent of B\n edges = edges.append(pd.DataFrame({'From': [a], 'To': [b]}))\n elif b_without_a and not a_without_b:\n # B is a parent of A\n edges = edges.append(pd.DataFrame({'From': [b], 'To': [a]}))\n elif not a_without_b and not b_without_a:\n # Co-Depedent. Choose A as left-most.\n edges = edges.append(pd.DataFrame({'From': [a], 'To': [b]}))\n\n return edges\n\n\n# %% Remove Grand Parents\n\n\ndef prune_grand_parents(edges):\n \"\"\"Prune edges that shortcut a parent-child relationship\n\n Args:\n edges (DataFrame): The edges data frame\n\n Returns:\n The data frame with grand parent edges removed\n \"\"\"\n for group in edges['To'].unique():\n\n parents0 = list(edges['From'][edges['To'] == group])\n\n grand_parents = list()\n\n while len(parents0) > 0:\n for p in parents0:\n parents = list(edges['From'][edges['To'] == p])\n if len(parents) > 0:\n grand_parents = grand_parents + parents\n parents0 = parents\n\n keep = ~(edges['From'].isin(grand_parents) & (edges['To'] == group))\n\n edges = edges[keep]\n return edges\n\n\n# %% Write out edges for one csv\n\n\ndef run_edge_detection(csv):\n \"\"\"Check dependencies between columns and write out the edges\n\n If there are any problems return False as this is part of the build.\n\n Args:\n csv (str): The file name that we want to check\n\n Returns:\n bool: Status\n \"\"\"\n status = True\n\n try:\n df = pd.read_csv(csv)\n except Exception as e:\n print(csv, e)\n return False\n\n # Run through the check functions\n if not check_headers(df, csv):\n return False\n\n # Get the edges\n try:\n edges = detect_all_edges(df, csv)\n edges = prune_grand_parents(edges)\n except Exception as e:\n print(csv, e)\n return False\n\n # Write out the edges\n try:\n # Build the new filename\n csv_file = os.path.split(csv)[-1]\n edge_file = csv_file.replace('indicator', 'edges')\n edge_path = os.path.join('data', 'edges', edge_file)\n # Write out\n edges.to_csv(edge_path, index=False, encoding='utf-8')\n except Exception as e:\n print(csv, e)\n return False\n\n return status\n\n\n# %% Read each csv and run the checks\n\n\ndef main():\n \"\"\"Run csv checks on all indicator csvs in the data directory\"\"\"\n status = True\n # Create the place to put the files\n os.makedirs(\"data/edges\", exist_ok=True)\n \n csvs = glob.glob(\"data/indicator*.csv\")\n print(\"Running edge detection for \" + str(len(csvs)) + \" csv files...\")\n\n for csv in csvs:\n status = status & run_edge_detection(csv)\n return(status)\n\nif __name__ == '__main__':\n status = main()\n if(not status):\n raise RuntimeError(\"Failed edge detection\")\n else:\n print(\"Success\")\n","repo_name":"dougmet/inequalities-audit","sub_path":"scripts/build/edge_detect.py","file_name":"edge_detect.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"21089453114","text":"import cbmpy as cbm\n\nfrom examples_and_results.helpers_ECM_calc import *\n\n\"\"\"CONSTANTS\"\"\"\nmodel_name = \"iND750\"\n# For a bigger computation, try:\n# input_file_name = \"bacteroid_ECMinputAll.csv\"\n\n# Define directories for finding models\nmodel_dir = os.path.join(os.getcwd(), \"models\")\n\nmodel_path = os.path.join(model_dir, model_name + \".xml\")\nmod = cbm.readSBML3FBC(model_path)\n\n#\npairs = cbm.CBTools.findDeadEndReactions(mod)\nexternal_metabolites, external_reactions = list(zip(*pairs)) if len(pairs) else (\n list(zip(*cbm.CBTools.findDeadEndMetabolites(mod)))[0], [])\n\n# External according to Urbanczik\next_urbanczik = ['ac', 'acald', 'ala__L', 'co2', 'csn', 'ergst', 'etoh', 'gam6p', 'glc__D', 'hdcea', 'ocdcea', 'ocdcya',\n 'so4', 'xylt', 'zymst', 'nh4', 'asp__L', 'ser__L', 'fum', 'gly', 'thr__L']\nforce_feed = ['ac']\n\next_urbanczik_inds = [ind for ind, metab in enumerate(external_metabolites) if metab[2:-2] in ext_urbanczik]\nforce_urbanczik_inds = [ind for ind, metab in enumerate(external_metabolites) if metab[2:-2] in force_feed]\nfor ind, re_id in enumerate(external_reactions):\n if ind in ext_urbanczik_inds:\n mod.setReactionBounds(re_id, -10, 10)\n else:\n mod.setReactionBounds(re_id, 0, 0)\n if ind in force_urbanczik_inds:\n mod.setReactionBounds(re_id, 0.1, 0.1)\n\n\n\n# Get exchange reactions\nexch_inds = [(ind, reac.id) for ind, reac in enumerate(mod.reactions) if reac.id[:4] == 'R_EX']\nmedium_list = []\n","repo_name":"SystemsBioinformatics/ecmtool","sub_path":"examples_and_results/analysis_iND750.py","file_name":"analysis_iND750.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"43"} +{"seq_id":"75330560770","text":"import random\r\nfrom datetime import datetime\r\nimport math\r\n\r\n# func to trunctate float to specified digits\r\ndef truncate(number, digits) -> float:\r\n stepper = 10.0 ** digits\r\n return math.trunc(stepper * number) / stepper\r\n\r\n\r\n### open file\r\nf = open(\"dummyData.csv\", \"a\")\r\n\r\n### write timestamp\r\n# Returns a datetime object containing the local date and time\r\ndateTimeObj = datetime.now()\r\nf.write(\"'\")\r\nf.write(str(dateTimeObj))\r\nf.write(\"\\n\")\r\n\r\n### write in random data \r\n\r\nfor pp in range(32):\r\n f.write(\"Sns_\")\r\n f.write(str(pp + 1))\r\n f.write(\",\")\r\n for qq in range(16):\r\n f.write(str(truncate(random.random(), 3)))\r\n if qq < 15:\r\n f.write(\",\")\r\n else:\r\n f.write(\"\\n\")\r\n\r\nf.close()\r\n\r\n### Create copy and corrupt an entry in the dataset\r\n\r\n# Read in the file\r\nwith open('dummyData.csv', 'r') as file :\r\n filedata = file.read()\r\n\r\n## Replace the target string\r\nsnsId = str(random.randint(1,32))\r\nstrQQ = 'Sns_' + snsId + ','\r\n# find occurance, replace value immediately after it\r\nposStt = filedata.find(strQQ) + len(strQQ)\r\nposNxt = filedata.find(',', posStt, posStt + 7)\r\nfiledata = filedata[:posStt] + 'err' + filedata[posNxt:]\r\n\r\n# Write the file out again\r\nwith open('corruptData.csv', 'w') as file:\r\n file.write(filedata)\r\n\r\n#close\r\nfile.close()\r\n\r\n\r\n### Test for error, write log\r\n## Function to test for error\r\ndef testError(fileName='corruptData.csv'):\r\n\r\n with open(fileName, 'r') as file :\r\n filedata = file.read()\r\n \r\n errStartPos = filedata.find('err')\r\n errSensorStr = filedata[errStartPos - 7:errStartPos-1]\r\n crLfPostn = errSensorStr.find('\\n')\r\n errSensorStr = errSensorStr[crLfPostn+1:]\r\n \r\n with open('errorLog.txt', 'a') as file:\r\n dateTimeObj = datetime.now()\r\n file.write(\"'\")\r\n file.write(str(dateTimeObj))\r\n file.write(' [Error in ')\r\n file.write(errSensorStr)\r\n file.write(' data]\\n')\r\n\r\n file.close()\r\n\r\n#function call\r\ntestError('corruptData.csv')\r\n\r\n","repo_name":"FrancisMugerwa/Python-Summative-Francis-","sub_path":"AIIP_Python Summative Assessment -MUGERWA FRANCIS.py","file_name":"AIIP_Python Summative Assessment -MUGERWA FRANCIS.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"42744302686","text":"from django.shortcuts import render, redirect\nfrom .models import *\nfrom django.core.files.images import ImageFile\nfrom django.http import HttpResponse\n\n\ndef receipe(request):\n if request.method == \"POST\":\n receipe_image = request.FILES.get(\"receipe_image\")\n receipe_name = request.POST.get(\"receipe_name\")\n receipe_description = request.POST.get(\"receipe_description\")\n\n print(receipe_name)\n print(receipe_description)\n print(receipe_image)\n\n image_file = ImageFile(receipe_image)\n\n recipe = Receipe.objects.create(\n receipe_name=receipe_name,\n receipe_description=receipe_description,\n receipe_image=image_file,\n )\n return redirect(\"/receipe\")\n \n queryset = Receipe.objects.all()\n \n # if request.GET.get('search'):\n # queryset = queryset.filter(receipe_name__icontains = request.GET.get('search'))\n \n if request.GET.get('search'):\n search_term = request.GET.get('search')\n queryset = queryset.filter(receipe_name__icontains=search_term)\n \n \n context = {'receipes': queryset}\n\n return render(request, \"receipe.html\",context)\n\n\ndef delete_receipe(request,id):\n print(id)\n \n queryset = Receipe.objects.get(id = id)\n queryset.delete()\n return redirect(\"/receipe/\")\n\ndef update_receipe(request,id):\n queryset = Receipe.objects.get(id = id)\n if request.method == \"POST\":\n receipe_name = request.POST.get(\"receipe_name\")\n receipe_description = request.POST.get(\"receipe_description\")\n receipe_image = request.FILES.get(\"receipe_image\")\n \n \n queryset.receipe_name = receipe_name\n queryset.receipe_description = receipe_description\n\n if receipe_image:\n queryset.receipe_image = receipe_image\n \n queryset.save() \n return redirect(\"/receipe/\")\n \n \n context = {'receipe': queryset}\n return render(request, \"update_receipe.html\",context)","repo_name":"kingmzk/django-receipe-app-CRUD","sub_path":"vege/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"11807096895","text":"import keras\nfrom keras.datasets import mnist\nfrom keras import backend as k\nfrom keras import layers\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, MaxPooling2D, Dropout, Flatten\nimport os\n\ndef mLearning(num):\n (X_train, y_train), (X_test, y_test) = mnist.load_data()\n fig = plt.figure()\n for i in range(9):\n plt.subplot(3,3,i+1)\n plt.tight_layout()\n plt.imshow(X_train[i], cmap='gray', interpolation='none')\n plt.title(\"Digit: {}\".format(y_train[i]))\n plt.xticks([])\n plt.yticks([])\n fig.show()\n\n img_rows, img_cols = 28, 28\n\n if k.image_data_format() == 'channels_first':\n X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)\n X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)\n input_shape = (1, img_rows, img_cols)\n else:\n X_train = X_train.reshape(X_train.shape[0], img_rows, img_cols, 1)\n X_test = X_test.reshape(X_test.shape[0], img_rows, img_cols, 1)\n input_shape = (img_rows, img_cols, 1)\n\n X_train = X_train.astype('float32')\n X_test = X_test.astype('float32')\n X_train /= 255\n X_test /= 255\n print('X_train shape:', X_train.shape)\n\n num_category = 10\n\n y_train = keras.utils.to_categorical(y_train, num_category)\n y_test = keras.utils.to_categorical(y_test, num_category)\n\n model = Sequential()\n\n model.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\n\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(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(num_category, activation='softmax'))\n\n model.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\n batch_size = 128\n num_epoch = num #number of iterations over the dataset\n model_log = model.fit(X_train, y_train,\n batch_size=batch_size,\n epochs=num_epoch,\n verbose=1,\n validation_data=(X_test, y_test))\n\n score = model.evaluate(X_test, y_test, verbose=0)\n print('Test loss:', score[0])\n print('Test accuracy:', score[1])\n\n fig = plt.figure()\n plt.subplot(2,1,1)\n plt.plot(model_log.history['accuracy'])\n plt.plot(model_log.history['val_accuracy'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='lower right')\n plt.subplot(2,1,2)\n plt.plot(model_log.history['loss'])\n plt.plot(model_log.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper right')\n plt.tight_layout()\n fig.show()\n","repo_name":"Aleks-gdb/Sound-Recognizer","sub_path":"sprints/sprint3/backend/MachineLearning.py","file_name":"MachineLearning.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"17412709998","text":"#!/usr/bin/python3\nfrom pprint import pprint\nimport sys\nimport os\nimport time\nimport json\n\nimport requests\nimport arrow\nimport sh\n\nif len(sys.argv) > 1:\n cfg_path = sys.argv[1]\nelse:\n cfg_path = os.path.expanduser(\"~\") + \"/.config/github-notifier.json\"\n\nCLIENT_ID = \"2cdcb6911fa2bd088826\"\n\nif not os.path.isfile(cfg_path):\n print(cfg_path, \"missing, generating token via oauth device flow...\")\n\n res = requests.post(\"https://github.com/login/device/code\", headers={\n 'Accept': 'application/json'\n }, data={\n 'client_id': CLIENT_ID,\n 'scope': 'notifications read:user',\n })\n data = res.json()\n # print(json.dumps(data, indent=4))\n print(f\"User Verification Code: {data['user_code']}\")\n\n print(\"Go to this url https://github.com/login/device and enter the code.\")\n sh.Command(\"xdg-open\")(\"https://github.com/login/device\")\n print(\"Press any key to continue\")\n input()\n\n\n res = requests.post('https://github.com/login/oauth/access_token', headers={\n 'Accept': 'application/json'\n }, data={\n 'client_id': CLIENT_ID,\n 'device_code': data['device_code'],\n 'grant_type': 'urn:ietf:params:oauth:grant-type:device_code'\n })\n # print(json.dumps(res.json(), indent=4))\n\n token = res.json()['access_token']\n\n # print(\"\\n\\nUser Info:\\n\")\n res = requests.get(\n \"https://api.github.com/user\", headers={'Authorization': 'token ' + res.json()['access_token']})\n\n # print(json.dumps(res.json(), indent=4) + '\\n\\n\\n')\n username = res.json()[\"login\"]\n\n print(f\"Check your authorization at https://github.com/settings/connections/applications/{CLIENT_ID}\")\n\n with open(cfg_path, \"w\") as f:\n json.dump({\n \"token\": token,\n \"username\": username,\n \"data\": {},\n \"last_event\": str(arrow.now())\n }, f)\n\nwith open(cfg_path, \"r\") as f:\n cfg = json.load(f)\n\netag = None\nlast_event = arrow.get(cfg[\"last_event\"])\nauth = \"token \" + cfg[\"token\"]\n\ndef actorName(d):\n return d[\"actor\"][\"login\"]\n\ndef repoName(d):\n return d[\"repo\"][\"name\"]\n\ndef createDeleteEvent(d):\n s = \"{} {} {} \".format(actorName(d), \"created\" if d[\"type\"] == \"CreateEvent\" else \"deleted\", d[\"payload\"][\"ref_type\"])\n if d[\"payload\"][\"ref_type\"] == \"repository\":\n s += d[\"repo\"][\"name\"]\n elif d[\"payload\"][\"ref_type\"] in [\"branch\", \"tag\"]:\n s += d[\"payload\"][\"ref\"]\n else:\n s += d[\"payload\"][\"ref_type\"]\n return s\n\ndef shortened(msg, length=55):\n msg = msg.strip(\"\\n\")\n if len(msg.split(\"\\n\")) < 2 and len(msg) <= length:\n return msg\n return msg.split(\"\\n\")[0][:length] + \" [...]\"\n\nknown_types = {\n \"PushEvent\": lambda d: \"\\n\".join([c[\"author\"][\"name\"] + \": \" + shortened(c[\"message\"]) for c in d[\"payload\"][\"commits\"]]) + \"\\n@\" + d[\"repo\"][\"name\"],\n \"WatchEvent\": lambda d: \"{} starred {}\".format(actorName(d), d[\"repo\"][\"name\"]),\n \"CreateEvent\": createDeleteEvent,\n \"DeleteEvent\": createDeleteEvent,\n \"IssuesEvent\": lambda d: \"{} {} '{}'\\n@{}\".format(actorName(d), d[\"payload\"][\"action\"], shortened(d[\"payload\"][\"issue\"][\"title\"]), repoName(d)),\n \"IssueCommentEvent\": lambda d: \"{} commented '{}'\\non '{}'\\n@{}\".format(actorName(d), shortened(d[\"payload\"][\"comment\"][\"body\"]), shortened(d[\"payload\"][\"issue\"][\"title\"]), repoName(d)),\n \"CommitCommentEvent\": lambda d: \"{} commented '{}'\\non '{}'\\n@{}\".format(actorName(d), shortened(d[\"payload\"][\"comment\"][\"body\"]), shortened(d[\"payload\"][\"comment\"][\"path\"]), repoName(d)),\n \"PullRequestEvent\": lambda d: \"{} {} '{}'\\n@{}\".format(actorName(d), d[\"payload\"][\"action\"], shortened(d[\"payload\"][\"pull_request\"][\"title\"]), repoName(d)),\n \"ForkEvent\": lambda d: \"{} forked {}\".format(actorName(d), repoName(d)),\n \"ReleaseEvent\": lambda d: \"{} {} '{}'\\n@{}\".format(actorName(d), d[\"payload\"][\"action\"], shortened(d[\"payload\"][\"release\"][\"name\"]), repoName(d)),\n \"GollumEvent\": lambda d: \"{}\\n{}\\n@{}\".format(actorName(d), \"\\n\".join([\"{} '{}'\".format(p['action'], p['title']) for p in d['payload']['pages']]), repoName(d)),\n \"PullRequestReviewCommentEvent\": lambda d: \"{} reviewed '{}'\".format(actorName(d), shortened(d[\"payload\"][\"pull_request\"][\"title\"])),\n \"MemberEvent\": lambda d: \"{} {} {}\\n@{}\".format(actorName(d), d[\"payload\"][\"action\"], d[\"payload\"][\"member\"][\"login\"], repoName(d)),\n \"PublicEvent\": lambda d: \"{} made {} public\".format(actorName(d), repoName(d)),\n}\n\ndef tostring(d):\n if d[\"type\"] in known_types:\n return known_types[d[\"type\"]](d), True\n return \"'{}'\".format(d[\"type\"]), False\n\ndef notify(d):\n title = \"Github Notification\"\n message, type_found = tostring(d)\n private = not d[\"public\"]\n if not type_found:\n pprint(d)\n print(title + \" - Private\" if private else title)\n print(message + \"\\n\")\n sh.notify_send(title, message, urgency=\"normal\" if private else \"low\")\n\nprint(\"Started ({})\".format(time.strftime(\"%Y-%m-%d %H:%M:%S\")))\nsh.notify_send('github_notifier started', urgency=\"low\")\nwhile True:\n headers = {\"Accept\": \"application/vnd.github.v3+json\", \"Authorization\": auth}\n if etag:\n headers[\"If-None-Match\"] = etag\n try:\n r = requests.get(\"https://api.github.com/users/\" + cfg[\"username\"] + \"/received_events\", headers=headers)\n except requests.exceptions.ConnectionError as e:\n print(e)\n time.sleep(60)\n continue\n if r.status_code == 304:\n time.sleep(30)\n continue\n\n for elem in r.json()[::-1]:\n if (last_event - arrow.get(elem[\"created_at\"])).total_seconds() < 0:\n last_event = arrow.get(elem[\"created_at\"])\n notify(elem)\n cfg[\"last_event\"] = str(last_event)\n with open(cfg_path, \"w\") as f:\n json.dump(cfg, f)\n\n etag = r.headers[\"etag\"]\n try:\n time.sleep(int(r.headers[\"x-poll-interval\"]))\n except KeyboardInterrupt:\n exit()\n","repo_name":"Mrmaxmeier/stuff","sub_path":"github-notifier.py","file_name":"github-notifier.py","file_ext":"py","file_size_in_byte":5922,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"43"} +{"seq_id":"35593268563","text":"import argparse\nimport re\nimport subprocess\nfrom typing import Dict, List, Optional, Tuple, Type\n\nfrom dstack._internal.cli.utils.common import console\nfrom dstack._internal.core.errors import ConfigurationError\nfrom dstack._internal.core.models.configurations import (\n BaseConfiguration,\n BaseConfigurationWithPorts,\n ConfigurationType,\n DevEnvironmentConfiguration,\n PortMapping,\n)\n\n\nclass BaseRunConfigurator:\n TYPE: ConfigurationType = None\n\n @classmethod\n def register(cls, parser: argparse.ArgumentParser):\n parser.add_argument(\n \"-e\",\n \"--env\",\n type=env_var,\n action=\"append\",\n help=\"Environment variables\",\n dest=\"envs\",\n metavar=\"KEY=VALUE\",\n )\n\n @classmethod\n def apply(cls, args: argparse.Namespace, conf: BaseConfiguration):\n if args.envs:\n for k, v in args.envs:\n conf.env[k] = v\n\n\nclass RunWithPortsConfigurator(BaseRunConfigurator):\n @classmethod\n def register(cls, parser: argparse.ArgumentParser):\n super().register(parser)\n parser.add_argument(\n \"-p\",\n \"--port\",\n type=port_mapping,\n action=\"append\",\n help=\"Exposed port or mapping\",\n dest=\"ports\",\n metavar=\"MAPPING\",\n )\n\n @classmethod\n def apply(cls, args: argparse.Namespace, conf: BaseConfigurationWithPorts):\n super().apply(args, conf)\n if args.ports:\n conf.ports = list(merge_ports(conf.ports, args.ports).values())\n\n\nclass TaskRunConfigurator(RunWithPortsConfigurator):\n TYPE = ConfigurationType.TASK\n\n\nclass DevEnvironmentRunConfigurator(RunWithPortsConfigurator):\n TYPE = ConfigurationType.DEV_ENVIRONMENT\n\n @classmethod\n def apply(cls, args: argparse.Namespace, conf: DevEnvironmentConfiguration):\n super().apply(args, conf)\n if conf.ide == \"vscode\" and conf.version is None:\n conf.version = _detect_vscode_version()\n if conf.version is None:\n console.print(\n \"[secondary]Unable to detect the VS Code version and pre-install extensions. \"\n \"Fix by opening [code]Command Palette[/code], executing [code]Shell Command: \"\n \"Install 'code' command in PATH[/code], and restarting terminal.[/]\\n\"\n )\n\n\nclass ServiceRunConfigurator(BaseRunConfigurator):\n TYPE = ConfigurationType.SERVICE\n\n\ndef env_var(v: str) -> Tuple[str, str]:\n r = re.match(r\"^([a-zA-Z_][a-zA-Z0-9_]*)=(.*)$\", v)\n if r is None:\n raise ValueError(v)\n key, value = r.groups()\n return key, value\n\n\ndef port_mapping(v: str) -> PortMapping:\n return PortMapping.parse(v)\n\n\ndef merge_ports(conf: List[PortMapping], args: List[PortMapping]) -> Dict[int, PortMapping]:\n unique_ports_constraint([pm.container_port for pm in conf])\n unique_ports_constraint([pm.container_port for pm in args])\n\n ports = {pm.container_port: pm for pm in conf}\n for pm in args: # override conf\n ports[pm.container_port] = pm\n\n unique_ports_constraint([pm.local_port for pm in ports.values() if pm.local_port is not None])\n return ports\n\n\ndef unique_ports_constraint(ports: List[int]):\n used_ports = set()\n for i in ports:\n if i in used_ports:\n raise ConfigurationError(f\"Port {i} is already in use\")\n used_ports.add(i)\n\n\ndef _detect_vscode_version(exe: str = \"code\") -> Optional[str]:\n try:\n run = subprocess.run([exe, \"--version\"], capture_output=True)\n except FileNotFoundError:\n return None\n if run.returncode == 0:\n return run.stdout.decode().split(\"\\n\")[1].strip()\n return None\n\n\nrun_configurators_mapping: Dict[ConfigurationType, Type[BaseRunConfigurator]] = {\n cls.TYPE: cls\n for cls in [\n TaskRunConfigurator,\n DevEnvironmentRunConfigurator,\n ServiceRunConfigurator,\n ]\n}\n","repo_name":"dstackai/dstack","sub_path":"src/dstack/_internal/cli/services/configurators/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","stars":859,"dataset":"github-code","pt":"43"} +{"seq_id":"33794403810","text":"#Circle\n\nfrom Ellipse_function import *\n\ncolors = ['r', 'c', 'k', 'g', 'b']\n\n\nphi11_, Exact_phi_, m11_, Exact_m11 = Ellipse_Circle(1, 1, N_list)\n\n# Comparing analytical and numerical results for the potential\nfor i in range(len(N_list)):\n\tplot(phi11_[i], '-', color=colors[i], label='N=%d' % N_list[i])\n\tplot(Exact_phi_[i], '-', color=colors[i+1], label='Analytical solution')\n\ttitle('Analytical vs Numerical solution for the potential ' '$\\phi_1$')\n\txlabel('$Number$ $of$ $segments$ $N$', fontsize=18)\n\tylabel('$\\phi_1$', fontsize=24)\n\tlegend(loc='upper right', numpoints = 1)\n\tsavefig('Analytical_vs_numerical.png')\n\tshow()\n\n\nfor i in range(len(N_list)):\n\tplot(1.0/N_list[i], m11_[i]/Exact_m11,'*', color=colors[i], markersize=16, linewidth=10, label='N=%d' %N_list[i])\n\ttitle('Computed added mass ' '$m_{11}$' ' divided by the analytical ' '$m_{11}$')\n\thold(True)\n\txlim((0, 0.011))\n\tylabel('$m_{11}$' '/' ' Exact ' '$m_{11}$', fontsize=16)\n\txlabel('1/N', fontsize=20)\n\tlegend(loc='upper right', numpoints = 1)\nshow()\n\n\n\"\"\"\nOutput:\n\nFor a circle with radius R0 = 1.00\n\nWith 100 segments we have:\nThe maximum error between the exact and the numerical potential is 0.01452\nThe maximum error between the exact and the numerical added mass coefficient m11 is 0.04460\n\nWith 200 segments we have:\nThe maximum error between the exact and the numerical potential is 0.00710\nThe maximum error between the exact and the numerical added mass coefficient m11 is 0.02204\n\nWith 400 segments we have:\nThe maximum error between the exact and the numerical potential is 0.00351\nThe maximum error between the exact and the numerical added mass coefficient m11 is 0.01095\n\nWith 1000 segments we have:\nThe maximum error between the exact and the numerical potential is 0.00139\nThe maximum error between the exact and the numerical added mass coefficient m11 is 0.00437\n\"\"\"","repo_name":"frh-uio/MEK4420","sub_path":"MandatoryAssignment1/codes/circle.py","file_name":"circle.py","file_ext":"py","file_size_in_byte":1854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"13412642223","text":"n, m = map(int, input().split())\nnums = sorted(list(map(int, input().split())))\nnumlist = []\n\n# N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.\n# N개의 자연수는 모두 다른 수이다.\n# N개의 자연수 중에서 M개를 고른 수열\n\ndef dfs(k):\n if k == m:\n print(' '.join(map(str, numlist)))\n return\n\n for i in nums:\n if i not in numlist:\n numlist.append(i)\n dfs(k + 1)\n numlist.pop()\n\ndfs(0)","repo_name":"SeungAh-Hong/algorithm-study-hyundai","sub_path":"Baekjoon/초급자_백트래킹/N과M5_김설희.py","file_name":"N과M5_김설희.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"ko","doc_type":"code","dataset":"github-code","pt":"43"} +{"seq_id":"18932315214","text":"#!/usr/bin/python -B\n#-*- encoding: utf-8 -*-\n\n#\n# Author: Zhang Li, HUST (algorithm partially from http://leeing.org/2009/11/01/mmseg-chinese-segmentation-algorithm)\n#\nimport sys\nimport dictionary\n\n\nclass Word(object):\n def __init__(self, content, length, frequency):\n self.content = content\n self.length = length\n self.frequency = frequency\n return\n def __cmp__(self, obj):\n return cmp(self.content, obj.content)\n pass\n\nclass Chunk(object):\n def __init__(self, *args):\n self.words = args\n return\n\n def total_frequency(self):\n return sum(x.frequency for x in self.words)\n\n def total_length(self):\n return sum(x.length for x in self.words)\n\n def empty_count(self):\n return reduce(lambda count, x: count + int(x.length == 0), self.words, 0)\n\n pass\n\nclass Splitter(object):\n def __retrieve_starting_words(self, pos):\n if pos >= self.length:\n return [Word(unicode(), length = 0, frequency = 0)]\n\n # process English words\n if ord(self.content[pos]) < 128 and self.content[pos].isalnum():\n words = [Word(self.content[pos], 0, 0)]\n pos += 1\n while pos < self.length and ord(self.content[pos]) < 128 and self.content[pos].isalnum():\n words[0].content += self.content[pos]\n pos += 1\n words[0].length = len(words[0].content)\n words[0].frequency = 1000 / words[0].length\n return words\n\n # process Chinese words by looking up dictionary\n words = []\n maxlen = min(dictionary.words_maxlen, (self.length - pos))\n\n for length in range(1, 1 + maxlen):\n segment = self.content[pos : pos + length]\n if dictionary.words.has_key(segment):\n words.append(Word(segment, length, dictionary.words[segment]))\n\n if len(words) == 0:\n words.append(Word(self.content[pos], length = 1, frequency = 0))\n return words\n\n def __filter_chunks(self, chunks, filter_func):\n maxval = max(map(filter_func, chunks))\n chunks = filter(lambda x: filter_func(x) == maxval, chunks)\n return chunks\n\n def process(self, content = unicode()):\n self.content, self.length = content, len(content)\n pos = 0\n words = []\n\n while pos < self.length:\n chunks = []\n\n # generate all possible 3-word chunks\n for x1 in self.__retrieve_starting_words(pos):\n for x2 in self.__retrieve_starting_words(pos + x1.length):\n for x3 in self.__retrieve_starting_words(pos + x1.length + x2.length):\n chunks.append(Chunk(x1, x2, x3))\n\n # filter bad chunks\n if len(chunks) > 1: chunks = self.__filter_chunks(chunks, Chunk.total_length)\n if len(chunks) > 1: chunks = self.__filter_chunks(chunks, Chunk.empty_count)\n if len(chunks) > 1: chunks = self.__filter_chunks(chunks, Chunk.total_frequency)\n\n # got a word\n words.append(chunks[0].words[0])\n pos += words[-1].length\n return words\n","repo_name":"lyx030405/cnsplit","sub_path":"splitter.py","file_name":"splitter.py","file_ext":"py","file_size_in_byte":3152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"1826691295","text":"# -*- coding: utf-8 -*-\n\nimport sys\nname = sys.argv.pop(0)\nif len(sys.argv) == 0 or len(sys.argv) > 1:\n sys.stderr.write('usage: {} INT < STDIN > STDOUT\\n'.format(name))\n sys.exit()\nelse:\n feat = int(sys.argv.pop(0))\n\nnline = 0\nfor l in sys.stdin:\n nline += 1\n toks = l.strip().split()\n for i in range(len(toks)):\n #print('tok: {}'.format(toks[i]))\n feats = toks[i].split('│')\n #print('feats: {}'.format(feats))\n if feat >= len(feats):\n sys.stderr.write('not enough features in token {} of line {}\\n'.format(toks[i], nline))\n toks[i] = '-'\n elif len(feats[feat]):\n toks[i] = feats[feat]\n else:\n toks[i] = '-'\n print(' '.join(toks))\n","repo_name":"jmcrego/corpora-tools","sub_path":"SpacCy/spacy2feat.py","file_name":"spacy2feat.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"18851849118","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nfrom utils.func import *\nfrom tqdm import tqdm\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nimport time\nimport networkx as nx\nfrom model import *\nimport random\n\nif __name__ == '__main__': \n\n for dataSource in ['gowalla']:\n arg = {}\n\n start_time = time.time()\n\n arg['epoch'] = 20\n arg['beamSize'] = 100\n arg['embedding_dim'] = 1024\n arg['userEmbed_dim'] = 1024\n arg['hidden_dim']= 1024\n arg['classification_learning_rate'] = 0.0001\n arg['classification_batch'] = 32\n arg['dropout'] = 0.9\n arg['dataFolder'] = 'processedFiles'\n\n print()\n print(dataSource)\n print()\n print(arg)\n\n # ==================================Spatial Temporal graphs================================================\n arg['temporalGraph'] = nx.read_edgelist('data/' + arg['dataFolder'] + '/' + dataSource + '_temporal.edgelist', nodetype=int,\n create_using=nx.Graph())\n\n arg['spatialGraph'] = nx.read_edgelist(\n 'data/' + arg['dataFolder'] + '/' + dataSource + '_spatial.edgelist', nodetype=int,\n create_using=nx.Graph())\n # ==================================Spatial Temporal graphs================================================\n\n userFileName = 'data/' + arg['dataFolder'] + '/' + dataSource + '_userCount.pickle'\n\n with open(userFileName,\n 'rb') as handle:\n arg['numUser'] = pickle.load(handle)\n\n print('Data loading')\n\n # ==================================geohash related data================================================\n for eachGeoHashPrecision in [6,5,4,3,2]:\n poi2geohashFileName = 'data/' + arg['dataFolder'] + '/' + dataSource + '_poi2geohash' + '_' + str(\n eachGeoHashPrecision)\n geohash2poiFileName = 'data/' + arg['dataFolder'] + '/' + dataSource + '_geohash2poi' + '_' + str(\n eachGeoHashPrecision)\n geohash2IndexFileName = 'data/' + arg['dataFolder'] + '/' + dataSource + '_geohash2Index' + '_' + str(\n eachGeoHashPrecision)\n\n with open(poi2geohashFileName + '.pickle', 'rb') as handle:\n arg['poi2geohash'+'_'+str(eachGeoHashPrecision)] = pickle.load(handle)\n with open(geohash2poiFileName + '.pickle', 'rb') as handle:\n arg['geohash2poi'+'_'+str(eachGeoHashPrecision)] = pickle.load(handle)\n with open(geohash2IndexFileName + '.pickle', 'rb') as handle:\n arg['geohash2Index'+'_'+str(eachGeoHashPrecision)] = pickle.load(handle)\n\n arg['index2geoHash'+'_'+str(eachGeoHashPrecision)] = {v: k for k, v in arg['geohash2Index'+'_'+str(eachGeoHashPrecision)].items()}\n\n beamSearchHashDictFileName = 'data/' + arg['dataFolder'] + '/' + dataSource + '_beamSearchHashDict'\n with open(beamSearchHashDictFileName + '.pickle', 'rb') as handle:\n arg['beamSearchHashDict'] = pickle.load(handle)\n # ==================================geohash related data================================================\n\n classification_dataset = classificationDataset(arg['numUser'], dataSource, arg)\n\n classification_dataloader = DataLoader(classification_dataset, batch_size=arg['classification_batch'],\n shuffle=True, pin_memory=True,\n num_workers=0)\n print('Data loaded')\n print('init model')\n\n classification = hmt_grn(arg).float().cuda()\n\n classification_optim = Adam(classification.parameters(), lr=arg['classification_learning_rate'])\n\n print('init model done')\n\n criterion = nn.NLLLoss(reduction='mean', ignore_index=0)\n\n nextGeoHashCriterion_2 = nn.NLLLoss(reduction='mean', ignore_index=0)\n nextGeoHashCriterion_3 = nn.NLLLoss(reduction='mean', ignore_index=0)\n nextGeoHashCriterion_4 = nn.NLLLoss(reduction='mean', ignore_index=0)\n nextGeoHashCriterion_5 = nn.NLLLoss(reduction='mean', ignore_index=0)\n nextGeoHashCriterion_6 = nn.NLLLoss(reduction='mean', ignore_index=0)\n\n for epoch in range(1, arg['epoch'] + 1):\n\n avgLossDict = {}\n\n print()\n print('Epoch: ' + str(epoch))\n\n avgLossDict['Next POI Classification'] = []\n\n classification_pbar = tqdm(classification_dataloader)\n\n classification_pbar.set_description('[' + dataSource + \"_Classification-Epoch {}]\".format(epoch))\n\n for x, user, y in classification_pbar:\n\n actualBatchSize = x.shape[0]\n\n batchLoss = 0\n\n x_geoHash2 = LT([]).cuda()\n x_geoHash3 = LT([]).cuda()\n x_geoHash4 = LT([]).cuda()\n x_geoHash5 = LT([]).cuda()\n x_geoHash6 = LT([]).cuda()\n for eachBatch in range(x.shape[0]):\n sample = x[eachBatch].tolist()\n\n mappedGeohash = [ arg['geohash2Index'+'_2'][arg['poi2geohash'+'_2'][i]] for i in sample]\n x_geoHash2 = t.cat((x_geoHash2,LT(mappedGeohash).unsqueeze(0).cuda()),dim=0)\n\n mappedGeohash = [arg['geohash2Index' + '_3'][arg['poi2geohash' + '_3'][i]] for i in sample]\n x_geoHash3 = t.cat((x_geoHash3, LT(mappedGeohash).unsqueeze(0).cuda()), dim=0)\n\n mappedGeohash = [arg['geohash2Index' + '_4'][arg['poi2geohash' + '_4'][i]] for i in sample]\n x_geoHash4 = t.cat((x_geoHash4, LT(mappedGeohash).unsqueeze(0).cuda()), dim=0)\n\n mappedGeohash = [arg['geohash2Index' + '_5'][arg['poi2geohash' + '_5'][i]] for i in sample]\n x_geoHash5 = t.cat((x_geoHash5, LT(mappedGeohash).unsqueeze(0).cuda()), dim=0)\n\n mappedGeohash = [arg['geohash2Index' + '_6'][arg['poi2geohash' + '_6'][i]] for i in sample]\n x_geoHash6 = t.cat((x_geoHash6, LT(mappedGeohash).unsqueeze(0).cuda()), dim=0)\n\n\n input = (x, user, y, x_geoHash2, x_geoHash3, x_geoHash4, x_geoHash5, x_geoHash6)\n\n logSoftmaxScores,nextgeohashPred_2,nextgeohashPred_3,nextgeohashPred_4,nextgeohashPred_5,nextgeohashPred_6= classification(input, 'train', arg)\n\n truth = LT(y).cuda()\n\n #map truth to geohash\n truthDict={}\n for eachGeoHashPrecision in [6,5, 4, 3, 2]:\n name = 'nextGeoHashTruth'+'_'+ str(eachGeoHashPrecision)\n behind = '_' + str(eachGeoHashPrecision)\n truthDict[name] = LT([]).cuda()\n for eachBatch in range(truth.shape[0]):\n sample = truth[eachBatch].tolist()\n mappedNextGeohashTruth = [ arg['geohash2Index'+behind][arg['poi2geohash'+behind][i]] for i in sample]\n truthDict[name] = t.cat((truthDict[name],LT(mappedNextGeohashTruth).unsqueeze(0).cuda()),dim=0)\n\n\n class_size = logSoftmaxScores.shape[2]\n\n classification_loss = criterion(logSoftmaxScores.view(-1, class_size), truth.view(-1))\n nextGeoHash_loss_2 = nextGeoHashCriterion_2(nextgeohashPred_2.view(-1, len(arg['geohash2Index_2'])), truthDict['nextGeoHashTruth_2'].view(-1))\n nextGeoHash_loss_3 = nextGeoHashCriterion_3(nextgeohashPred_3.view(-1, len(arg['geohash2Index_3'])), truthDict['nextGeoHashTruth_3'].view(-1))\n nextGeoHash_loss_4 = nextGeoHashCriterion_4(nextgeohashPred_4.view(-1, len(arg['geohash2Index_4'])), truthDict['nextGeoHashTruth_4'].view(-1))\n nextGeoHash_loss_5 = nextGeoHashCriterion_5(nextgeohashPred_5.view(-1, len(arg['geohash2Index_5'])), truthDict['nextGeoHashTruth_5'].view(-1))\n nextGeoHash_loss_6 = nextGeoHashCriterion_6(nextgeohashPred_6.view(-1, len(arg['geohash2Index_6'])), truthDict['nextGeoHashTruth_6'].view(-1))\n\n batchLoss = (classification_loss + nextGeoHash_loss_2 + nextGeoHash_loss_3 + nextGeoHash_loss_4 + nextGeoHash_loss_5 + nextGeoHash_loss_6) / 6 / actualBatchSize\n\n classification_optim.zero_grad()\n batchLoss.backward(retain_graph=False)\n classification_optim.step()\n classification_pbar.set_postfix(loss=classification_loss.item()/actualBatchSize)\n\n avgLossDict['Next POI Classification'].append(classification_loss.item()/actualBatchSize)\n\n\n avgLossDict['Next POI Classification'] = np.average(avgLossDict['Next POI Classification'])\n\n print('Next POI Classification Avg Loss: ' + str(avgLossDict['Next POI Classification']))\n\n print()\n\n sys.stdout.flush()\n\n print()\n print(\"----- END SAVING : %s seconds ---\" % (time.time() - start_time))\n print()\n\n\n if epoch % 20 == 0:\n\n print()\n print('Epoch ' + str(epoch) + ' Evaluation Start!')\n print()\n model = classification\n\n arg['novelEval'] = False\n evaluate(model, dataSource, arg)\n\n arg['novelEval'] = True\n evaluate(model, dataSource, arg)\n\n sys.stdout.flush()\n","repo_name":"poi-rec/HMT-GRN","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9386,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"43"} +{"seq_id":"21658172793","text":"class Game:\n team1 = 0\n team2 = 0\n round = {\n 'inHole': [0, 0],\n 'onBoard': [0, 0]\n }\n winner = ''\n\n def __init__(self):\n pass\n \n\n def scoreRound(self):\n print(self.round)\n team1_roundScore = self.round['inHole'][0]*3 + self.round['onBoard'][0]\n team2_roundScore = self.round['inHole'][1]*3 + self.round['onBoard'][1]\n print(team1_roundScore, team2_roundScore)\n netScore = team1_roundScore - team2_roundScore\n if(netScore > 0):\n self.team1 += netScore\n else:\n self.team2 += netScore * -1\n \n if(self.team1 > 21):\n self.team1 = 13\n if(self.team2 > 21):\n self.team2 = 13\n\n if(self.team1 == 21):\n self.winner = 'Team 1'\n if(self.team2 == 21):\n self.winner = 'Team 2'\n self.resetRound()\n\n\n def resetRound(self):\n self.round = {\n 'inHole': [0, 0],\n 'onBoard': [0, 0]\n }\n\n\n def addOnBoard(self, team):\n if(team == 1 and self.round['onBoard'][0] < 4 and self.round['onBoard'][0] + self.round['inHole'][0] < 4):\n self.round['onBoard'][0] +=1\n elif(team == 2 and self.round['onBoard'][1] < 4 and self.round['onBoard'][1] + self.round['inHole'][1] < 4):\n self.round['onBoard'][1] +=1\n \n def addInHole(self, team):\n if(team == 1 and self.round['inHole'][0] < 4 and self.round['onBoard'][0] + self.round['inHole'][0] < 4):\n self.round['inHole'][0] +=1\n elif(team == 2 and self.round['inHole'][1] < 4 and self.round['onBoard'][1] + self.round['inHole'][1] < 4):\n self.round['inHole'][1] +=1\n \n def removeOnBoard(self, team):\n if(team == 1 and self.round['onBoard'][0] > 0):\n self.round['onBoard'][0] -=1\n elif(team == 2 and self.round['onBoard'][1] > 0):\n self.round['onBoard'][1] -= 1\n\n def removeInHole(self, team):\n if(team == 1 and self.round['inHole'][0] > 0):\n self.round['inHole'][0] -=1\n elif(team == 2 and self.round['inHole'][1] > 0):\n self.round['inHole'][1] -= 1\n\n\nsampleGame = Game()\n#round1 \nsampleGame.addOnBoard(1)\nsampleGame.addOnBoard(2)\nsampleGame.addOnBoard(1)\nsampleGame.addInHole(1)\nsampleGame.scoreRound()\nprint('Round 1 Score:')\nprint('Team 1:', sampleGame.team1, 'Team 2:', sampleGame.team2)\n\nsampleGame.addInHole(2)\nsampleGame.addInHole(2)\nsampleGame.addInHole(2)\nsampleGame.addInHole(2)\nsampleGame.scoreRound()\nprint('Round 2 Score:')\nprint('Team 1:', sampleGame.team1, 'Team 2:', sampleGame.team2)\n\nsampleGame.addInHole(2)\nsampleGame.addInHole(1)\nsampleGame.addInHole(2)\nsampleGame.addOnBoard(2)\nsampleGame.addOnBoard(2)\nsampleGame.removeOnBoard(2)\nsampleGame.scoreRound()\nprint('Round 3 Score:')\nprint('Team 1:', sampleGame.team1, 'Team 2:', sampleGame.team2)\n","repo_name":"mag8224/cornhole-scoreboard","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"5706201191","text":"# pipeline.py\n#\n# Pipeline helper for setting up data transfer\n#\n# Manifest Specifications:\n#\tA manifest is a file that includes a series of space ' ' seperated absolute filepaths\n#\n# Functions Implemented Here:\n#\tload_im - Depreciated, do not use\n#\tload_manifest - Loads all images from a manifest\n#\tload_manifest_count - Loads a set number of images in a deterministic way from a manifest\n#\tload_manifest_rand - Loads a set number of images randomly from a manifest\n#\n\n\n#Necessary Imports\nfrom PIL import Image\nimport numpy as np\n\nimport random\n\n\n#Hardcoded Directory Path\n#NOTE: This is utilzed in depreciated functions only\ndirectory = \"/home/ubuntu/fmow-rgb-dataset/\"\n\n\n\n#load_im(): Loads a number of images based on a manifest\n# NOTE: This function is depreciated. It is not recommended to use it\n# \tIt implements on the fly image normalization which is not efficient\n#manifest - List of all possible filepaths\n#num_imgs - How many images to return\n#dim - The dimensions of the image to load, should be in size (X,Y)\n## DEPRECIATED ##\ndef load_im(manifest, num_imgs, dim):\n\n\treturn_data = np.empty((0,) + dim + (3,))\n\treshape_size = (-1,) + dim + (3,)\n\n\tmax_rand = len(manifest) - 1\n\tfor i in range(num_imgs):\n\n\t\tchoice = random.randint(0, max_rand)\n\t\t#Open chosen file from hardcoded file path\n\t\tim = Image.open(directory + manifest[choice])\n\n\t\t#Resize Image\n\t\tim = im.resize(dim)\n\n\t\t#Convert to np array\n\t\tim_np = np.asarray(im)\n\n\t\t#Convert to correct shape\n\t\tim_np = im_np.reshape(reshape_size)\n\n\t\tim_np = im_np /255.\n\n\t\t#Add to return data\n\t\treturn_data = np.concatenate((return_data, im_np))\n\n\treturn return_data\n\n\n\n#Loads all images from a specified Manifest\n#manifest - List of all possible filepaths\n#dim - Size of the images to load (VARIABLE NOT IN USE/DEPRECIATED)\ndef load_manifest(manifest, dim):\n\t#return_data = np.empty((0,) + dim + (3,))\n\t#reshape_size = dim + (3,)\n\n\t# Create an empty list for concatenate work around\n\timage_list = []\n\n\t# Load each image individually\n\tfor obj in manifest:\n\t\t# Sanity Check\n\t\t# FIXME: Manifest likely shouldn't include this in the first place?\n\t\tif obj == \"\":\n\t\t\tcontinue\n\t\t#Debug Print\n\t\t#print(\"Loading: \" + obj)\n\t\tim = Image.open(obj)\n\t\tim_np = np.asarray(im)\n\n\t\t#im_np = im_np.reshape(reshape_size)\n\n\t\tim_np = im_np /255.\n\n\t\t#NOTE: Concatenate is slow and BAD, do not use!!!\n\t\t#return_data = np.concatenate((return_data, im_np))\n\n\t\timage_list.append(im_np)\n\n\treturn_data = np.array(image_list)\n\treturn return_data\n\n# Loads a specified number of images from a manifest in a deterministic order\n#manifest - List of all possible filepaths\n#dim - Size of the images to load (VARIABLE NOT IN USE/DEPRECIATED)\n#count - Number of images to return\ndef load_manifest_count(manifest, dim, count):\n\t#return_data = np.empty((0,) + dim + (3,))\n\t#reshape_size = dim + (3,)\n\n\t# Create an empty list for concatenate work around\n\timage_list = []\n\t\n\t# Load each image individually\n\tfor i in range(count):\n\t\tobj = manifest[i]\n\t\t# Sanity Check\n\t\t# FIXME: Manifest likely shouldn't include this in the first place?\n\t\tif obj == \"\":\n\t\t\tcontinue\n\t\t#Debug Print\n\t\t#print(\"Loading: \" + obj)\n\t\tim = Image.open(obj)\n\t\tim_np = np.asarray(im)\n\n\t\t#im_np = im_np.reshape(reshape_size)\n\n\t\tim_np = im_np /255.\n\n\t\t#NOTE: Concatenate is slow and BAD, do not use!!!\n\t\t#return_data = np.concatenate((return_data, im_np))\n\n\t\timage_list.append(im_np)\n\n\treturn_data = np.array(image_list)\n\treturn return_data\n\n# Loads random images from a manifest\n# The best function implemented here for training\n#manifest - List of all possible filepaths\n#dim - Size of the images to load (VARIABLE NOT IN USE/DEPRECIATED)\n#count - Number of images to return\ndef load_manifest_rand(manifest, dim, count):\n\t\n\tmanifest = manifest[:-1]\n\timage_list = []\n\tmax_rand = len(manifest) - 1\n\tfor i in range(count):\n\t\tchoice = random.randint(0, max_rand)\n\t\tobj = manifest[random.randint(0, max_rand)]\n\t\t#print(\"Loading: \" + obj)\n\t\tim = Image.open(obj)\n\t\tim_np = np.asarray(im)\n\n\t\t#im_np = im_np.reshape(reshape_size)\n\n\t\tim_np = im_np /255.\n\n\t\t#NOTE: Concatenate is slow and BAD, do not use!!!\n\t\t#return_data = np.concatenate((return_data, im_np))\n\n\t\timage_list.append(im_np)\n\n\treturn_data = np.array(image_list)\n\treturn return_data\n","repo_name":"ljansen2140/AlienHunters_VAE_V2","sub_path":"pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"43"} +{"seq_id":"11017576602","text":"from azul import config\nfrom azul.deployment import (\n aws,\n emit_tf,\n)\n\nif config.terraform_component:\n suffix = \"-\" + config.terraform_component\nelse:\n suffix = ''\n\nemit_tf(\n {\n \"terraform\": {\n \"backend\": {\n \"s3\": {\n \"bucket\": config.terraform_backend_bucket,\n \"key\": f\"cellxgene-fargate{suffix}.tfstate\",\n \"region\": aws.region_name,\n **(\n {\n \"profile\": aws.profile['source_profile'],\n \"role_arn\": aws.profile['role_arn']\n } if 'role_arn' in aws.profile else {\n }\n )\n }\n }\n }\n }\n)\n","repo_name":"DataBiosphere/cellxgene-fargate","sub_path":"terraform/backend.tf.json.template.py","file_name":"backend.tf.json.template.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"28218684669","text":"# coding: utf-8\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 使用numpy生成200个随机点,值在-0.5~0.5中,产生了200行一列的矩阵\nx_data = np.linspace(-0.5, 0.5, 200)[:, np.newaxis]\n# 产生随机噪声\nnoise = np.random.normal(0, 0.02, x_data.shape)\n# 给y_data加入噪声 y = x^2 + noise\ny_data = np.square(x_data) + noise\n\n# 定义两个placeholder\nx = tf.placeholder(tf.float32, [None, 1])\ny = tf.placeholder(tf.float32, [None, 1])\n\n# 定义神经网络中间层,中间层权值为一行十列的矩阵\nWeights_L1 = tf.Variable(tf.random_normal([1, 10]))\n# 产生偏置值\nbiases_L1 = tf.Variable(tf.zeros([1, 10]))\n# 预测结果:y = x * w + b\nWx_plus_b_L1 = tf.matmul(x, Weights_L1) + biases_L1\n# 使用tanh作为激活函数\nL1 = tf.nn.tanh(Wx_plus_b_L1)\n\n# 定义神经网络输出层,权值为十行一列的矩阵\nWeights_L2 = tf.Variable(tf.random_normal([10, 1]))\nbiases_L2 = tf.Variable(tf.zeros([1, 1]))\nWx_plus_b_L2 = tf.matmul(L1, Weights_L2) + biases_L2\nprediction = tf.nn.tanh(Wx_plus_b_L2)\n\n# 二次代价函数\nloss = tf.reduce_mean(tf.square(y - prediction))\n# 使用梯度下降法训练\ntrain_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\n\nwith tf.Session() as sess:\n # 变量初始化\n sess.run(tf.global_variables_initializer())\n for _ in range(2000):\n sess.run(train_step, feed_dict={x: x_data, y: y_data})\n\n # 获得预测值\n prediction_value = sess.run(prediction, feed_dict={x: x_data})\n # 画图\n plt.figure()\n plt.scatter(x_data, y_data)\n plt.plot(x_data, prediction_value, 'r-', lw=5)\n plt.show()\n","repo_name":"hujiese/Tensorflow-Tourial","sub_path":"02.Tensorflow线性回归以及分类的简单使用,softmax介绍/src/01_no_linear_regression.py","file_name":"01_no_linear_regression.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"74583853570","text":"import os\nfrom flask import Flask, jsonify\nfrom flask_cors import CORS\nfrom flask import request\nfrom dotenv import load_dotenv\nfrom controllers.services import Services\nfrom controllers.incidents import Incidents\nfrom utils.status import calculate_status\n\nload_dotenv()\n\nPORT = int(os.environ.get('PORT', 5000))\n\napp = Flask(__name__)\n\nCORS(app)\n\n@app.route(\"/\")\ndef health():\n return jsonify(\"healthy\")\n\n# Get all services \n@app.route(\"/services\")\ndef services():\n controller = Services()\n return controller.get_all_services()\n\n@app.route(\"/services/\")\ndef service_by_id(id):\n controller = Services()\n return controller.get_service_by_id(id)\n\n# get all incidents per Service\n@app.route(\"/incidents/service/\")\ndef incidents_by_service_id(id):\n controller = Incidents()\n return controller.get_incidents_by_service(id)\n\n\n# get all status per incident\n@app.route(\"/incident/\")\ndef incident_by_id(id):\n controller = Incidents()\n return controller.get_incident_by_id(id)\n \n\n# Create and Change incidents\n@app.route(\"/incident\", methods= ['PUT', 'POST'])\ndef indicent():\n body = request.get_json()\n controller = Incidents()\n if request.method == 'POST':\n return controller.create_incident_by_id(body)\n else: \n return controller.put_incident_by_id(body)\n\n# get status of all incidents associated with a service\n@app.route(\"/services/status/\")\ndef service_status(id):\n controller = Incidents()\n incidents = controller.get_incidents_by_service(id)\n total, perc = calculate_status(incidents )\n res = {'total': total, 'percentage': perc}\n return res\n \n@app.route(\"/incidents\")\ndef incidents():\n incident = Incidents.get_all_incidents()\n return incident\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=PORT, debug=True)","repo_name":"icanipa/pd-csg","sub_path":"pd_back/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"43"} +{"seq_id":"37711232124","text":"import logging\nimport math\nimport os\nimport random\nimport sys\n\nimport numpy as np\nimport torch\n\nfrom fairseq import checkpoint_utils, distributed_utils, options, tasks, utils\nfrom fairseq.data import iterators\nfrom fairseq.logging import meters, metrics, progress_bar\nfrom fairseq.trainer import Trainer\n\n\nlogging.basicConfig(\n format='%(asctime)s | %(levelname)s | %(name)s | %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n level=logging.INFO,\n stream=sys.stdout,\n)\nlogger = logging.getLogger('fairseq_cli.train')\n\n\ndef main(args, init_distributed=False):\n utils.import_user_module(args) # 由\"--user_dir\"import可选用户模块(非参数),默认--user_dir为None\n\n assert args.max_tokens is not None or args.max_sentences is not None, \\\n 'Must specify batch size either with --max-tokens or --max-sentences' # 必须设置bacth size,无论是token-level还是sent-level\n\n # Initialize CUDA and distributed training\n if torch.cuda.is_available() and not args.cpu: # 进行cuda计算(单GPU),设置cuda设备号\n torch.cuda.set_device(args.device_id)\n np.random.seed(args.seed) # 针对numpy参数,设置固定的随机数生成,仅该次有效\n torch.manual_seed(args.seed) # 针对torch参数,设置固定的随机数生成\n if init_distributed: # 若进行分布式训练:\n args.distributed_rank = distributed_utils.distributed_init(args)\n\n if distributed_utils.is_master(args): # 检查save_dir是否存在,由一个dummy文件做写入操作进行确认,正常则删除\n checkpoint_utils.verify_checkpoint_directory(args.save_dir)\n\n # Print args 打印全部args\n logger.info(args)\n\n # Setup task, e.g., translation, language modeling, etc. 设置task,如translation等\n task = tasks.setup_task(args) # 返回初始化且加载源/目标字典后的TranslationTask类\n\n # Load valid dataset (we load training data below, based on the latest checkpoint) 加载验证集(我们根据最新的检查点在下面加载训练数据)\n for valid_sub_split in args.valid_subset.split(','):\n task.load_dataset(valid_sub_split, combine=False, epoch=1) # 返回源和目标验证集的句子对数据集\n\n # Build model and criterion 根据全部参数args来建立模型和criterion(损失)\n model = task.build_model(args) # 返回一个TransformerModel类,由与原始论文一致的Transfromer Encoder和Decoder组成\n criterion = task.build_criterion(args) # 通过args参数(-arch)选择所设定的criterions,由criterion对应类(LabelSmoothedCrossEntropyCriterion)的init_args完成对criterion对应类的初始化\n logger.info(model) # 打印模型结构\n logger.info('model {}, criterion {}'.format(args.arch, criterion.__class__.__name__)) # 打印所建立的模型和criterion(损失)\n logger.info('num. model params: {} (num. trained: {})'.format(\n sum(p.numel() for p in model.parameters()),\n sum(p.numel() for p in model.parameters() if p.requires_grad),\n )) # 打印所建立的模型的参数大小和训练参数大小\n\n # Build trainer # 由args,task,所建立的模型和criterion(损失)来建立训练器\n trainer = Trainer(args, task, model, criterion)\n logger.info('training on {} GPUs'.format(args.distributed_world_size)) # 打印在几台gpu上训练\n logger.info('max tokens per GPU = {} and max sentences per GPU = {}'.format(\n args.max_tokens,\n args.max_sentences,\n )) # 打印在每台gpu上的训练批次(token-level and sents-level)\n\n # Load the latest checkpoint if one is available and restore the\n # corresponding train iterator 加载最新的检查点(如果有)并恢复对应的训练迭代器\n # 在该函数下还建立: 训练数据集的epoch数据迭代器,优化器optimizer,以及学习率调度器lr_scheduler\n extra_state, epoch_itr = checkpoint_utils.load_checkpoint(args, trainer)\n\n # Train until the learning rate gets too small 训练直到学习率变得太小,到达args.min-lr(1e-09)\n max_epoch = args.max_epoch or math.inf\n max_update = args.max_update or math.inf # 设置训练的最大更新批次数\n lr = trainer.get_lr() # 返回当前的学习率\n train_meter = meters.StopwatchMeter() # 初始化一个计算事件的持续时间的计时器\n train_meter.start() # 开始记录代码所持续时间\n valid_subsets = args.valid_subset.split(',') # 获取验证集split名称['vaild']\n while (\n lr > args.min_lr\n and epoch_itr.next_epoch_idx <= max_epoch\n and trainer.get_num_updates() < max_update # 若学习率未达到最低学习率min_lr, 当前epoch编号未超过最大轮数,当前更新批次步骤未超过最大更新批次步骤:\n ):\n # train for one epoch 由args,初始化且加载源/目标字典后的TranslationTask类,\n # 由args,task,所建立的模型和criterion(损失)来建立训练器,训练数据集的epoch数据迭代器来训练一轮\n train(args, trainer, task, epoch_itr)\n\n if not args.disable_validation and epoch_itr.epoch % args.validate_interval == 0: # 若不禁止验证,且默认每一轮验证一次\n valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets) # 故每训练完一轮要进行一次验证,与在一轮内的验证一样\n # 返回验证集平均目标词对应的-lable_smoothing loss/log(2)列表\n else:\n valid_losses = [None]\n\n # only use first validation loss to update the learning rate \n lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) # 每训练完一轮后,根据验证集损失计算当前更新批次步下���学习率,并给优化器更新学习率以及更新MetersDict中lr值\n\n # save checkpoint\n if epoch_itr.epoch % args.save_interval == 0: # 若当前轮数满足每多少轮存储一个检查点文件,默认为每轮\n checkpoint_utils.save_checkpoint(args, trainer, epoch_itr, valid_losses[0])\n # 将当前轮数,更新批次下的所有训练状态和vaild_loss等存到检查点目录中如下检查点文件中: (其中save_checkpoint.best默认为最小val_loss)\n # checkpoint_epoch_updates.pt,checkpoint_best.pt,checkpoint_last.pt文件下(已设好目录)\n # 同时仅保留最后keep_interval_updates个检查点(间隔为--save-interval-updates),且检查点以降序排列\n\n # early stop 提早停止,非默认设置\n if should_stop_early(args, valid_losses[0]):\n logger.info('early stop since valid performance hasn\\'t improved for last {} runs'.format(args.patience))\n break\n\n epoch_itr = trainer.get_train_iterator(\n epoch_itr.next_epoch_idx,\n # sharded data: get train iterator for next epoch\n load_dataset=(os.pathsep in getattr(args, 'data', '')),\n ) # 由下一轮轮数来更新epoch_itr,返回一个基于torch.utils.data.Dataset上的多epoch数据迭代器\n train_meter.stop() # 记录代码从开始到全部训练结束总共所持续的时间,并打印出来\n logger.info('done training in {:.1f} seconds'.format(train_meter.sum))\n\n\ndef should_stop_early(args, valid_loss):\n # skip check if no validation was done in the current epoch\n if valid_loss is None:\n return False\n if args.patience <= 0:\n return False\n\n def is_better(a, b):\n return a > b if args.maximize_best_checkpoint_metric else a < b\n\n prev_best = getattr(should_stop_early, 'best', None)\n if prev_best is None or is_better(valid_loss, prev_best):\n should_stop_early.best = valid_loss\n should_stop_early.num_runs = 0\n return False\n else:\n should_stop_early.num_runs += 1\n return should_stop_early.num_runs >= args.patience\n\n\n@metrics.aggregate('train')\ndef train(args, trainer, task, epoch_itr):\n \"\"\"Train the model for one epoch.\"\"\"\n # 由args,初始化且加载源/目标字典后的TranslationTask类, 由args,task,所建立的模型和criterion(损失)来建立训练器,训练数据集的epoch数据迭代器来训练一轮\n # Initialize data iterator 初始化数据迭代器\n itr = epoch_itr.next_epoch_itr(\n fix_batches_to_gpus=args.fix_batches_to_gpus,\n shuffle=(epoch_itr.next_epoch_idx > args.curriculum), # 若当前epoch编号>args.curriculum,则设置打乱标记为True;默认为True\n ) # 返回self._cur_epoch_itr,可记录迭代数的迭代器,基于torch.data.DataLoader在给定的数据集类上创建的数据加载器\n update_freq = (\n args.update_freq[epoch_itr.epoch - 1]\n if epoch_itr.epoch <= len(args.update_freq) # 若当前轮数大于所设置的每N个批次更新一次参数(梯度累积更新),则返回args.update_freq[-1]\n else args.update_freq[-1]\n )\n itr = iterators.GroupedIterator(itr, update_freq) # 返回分好块的迭代器GroupedIterator类,基于self._cur_epoch_itr\n progress = progress_bar.progress_bar(\n itr,\n log_format=args.log_format, # 记录所用格式,json\n log_interval=args.log_interval, # 每多少个batches打印进度,等价于disp_freq\n epoch=epoch_itr.epoch, # 当前epoch编号\n tensorboard_logdir=(\n args.tensorboard_logdir if distributed_utils.is_master(args) else None\n ), # 用tensorboard保存日志的路径\n default_log_format=('tqdm' if not args.no_progress_bar else 'simple'), # 若设置不报告进度信息,则默认log格式为tadm\n ) # 返回以JSON格式记录输出JsonProgressBar类,加载分好块的迭代器GroupedIterator类,log_interval,当前epoch编号,offset等\n\n # task specific setup per epoch 每epoch的任务特定设置\n task.begin_epoch(epoch_itr.epoch, trainer.get_model()) # trainer.get_model()获取非warpped模型\n\n valid_subsets = args.valid_subset.split(',') # 存储全部验证集spilt名称的列表\n max_update = args.max_update or math.inf # 获得最大更新批次步骤数\n for samples in progress: # 遍历JsonProgressBar类中的分好块的迭代器GroupedIterator类,其中通过了多个类的__iter__(),得到一个批次的示例\n with metrics.aggregate('train_inner'): # 通过aggregate()创建一个给定名称下用于整合指标的上下文管理器(meterdicts)\n log_output = trainer.train_step(samples) # 通过一个批次的示例进行训练,\n # 返回有序字典logging_output,其中键值对有,{loss\":当前批次平均目标词对应的-lable_smoothing loss/log(2);\n # \"nll_loss\":当前批次平均目标词对应的-nll_loss(y_hot损失)/log(2);'sample_size':当前批次目标tokens数}\n if log_output is None: # OOM, overflow, ...\n continue\n\n # log mid-epoch stats 记录一轮训练中的统计\n num_updates = trainer.get_num_updates()\n if num_updates % args.log_interval == 0: # 若当前更新批次步骤可以整除进度打印频率:\n stats = get_training_stats(metrics.get_smoothed_values('train_inner')) # 获取在'train_inner'下所汇聚的平滑值,即MetersDict中非\"_\"开头的key,以及其smoothed_value所组成的有序字典\n # OrderedDict([('loss', 13.988), ('nll_loss', 13.982), ('ppl', 16175.65), ('wps', 0.0), ('ups', 0.0), ('wpb', 2931.0),\n # ('bsz', 192.0), ('num_updates', 1), ('lr', 1.874875e-07), ('gnorm', 8.824), ('train_wall', 22.0), ('wall', 99.0)])\n progress.log(stats, tag='train_inner', step=num_updates)\n # 'epoch':当前epoch和'update':所完成第几轮的百分之几批次添加进上述'train_inner'下所汇聚的平滑值,并打印出来:\n # OrderedDict([(\"epoch\": 1), (\"update\": 0.001),('loss', 13.988), ('nll_loss', 13.982), ('ppl', 16175.65), ('wps', 0.0), ('ups', 0.0),\n # ('wpb', 2931.0), ('bsz', 192.0), ('num_updates', 1), ('lr', 1.874875e-07), ('gnorm', 8.824), ('train_wall', 22.0), ('wall', 99.0)])\n\n # reset mid-epoch stats after each log interval 在每个进度打印间隔后重置一轮训练中的统计信息, 仍将保留一轮训练完的统计\n # the end-of-epoch stats will still be preserved\n metrics.reset_meters('train_inner')\n\n if (\n not args.disable_validation # 若不禁止验证,\n and args.save_interval_updates > 0 # 若每多少updates存储一个检查点文件大于0(存储频率),注:validate-interval为验证频率,默认为1\n and num_updates % args.save_interval_updates == 0 # 若当前更新批次步骤可以整除存储频率:\n and num_updates > 0 # 若当前更新批次步骤>0:\n ):\n valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets) # 返回验证集平均目标词对应的-lable_smoothing loss/log(2)列表\n checkpoint_utils.save_checkpoint(args, trainer, epoch_itr, valid_losses[0])\n # 将当前轮数,更新批次下的所有训练状态和vaild_loss等存到检查点目录中如下检查点文件中: (其中save_checkpoint.best默认为最小val_loss)\n # checkpoint_epoch_updates.pt,checkpoint_best.pt,checkpoint_last.pt文件下(已设好目录)\n # 同时仅保留最后keep_interval_updates个检查点(间隔为--save-interval-updates),且检查点以降序排列\n if num_updates >= max_update: # 若超过最大更新批次步骤数,则停止训练\n break\n\n # log end-of-epoch stats 记录一轮训练完的统计\n stats = get_training_stats(metrics.get_smoothed_values('train')) # 获取在'train'下所汇聚的平滑值,即MetersDict中非\"_\"开头的key,以及其smoothed_value所组成的有序字典\n # OrderedDict([('loss', 13.215), ('nll_loss', 13.204), ('ppl', 9438.41), ('wps', 0.9), ('ups', 0.0), ('wpb', 2804.0),\n # ('bsz', 132.0), ('num_updates', 2), ('lr', 2.74975e-07), ('gnorm', 8.076), ('train_wall', 48.0), ('wall', 0.0)])\n progress.print(stats, tag='train', step=num_updates)\n # 将'train(训练完)/root(验证完)'下所汇聚的平滑值,以及'epoch':当前epoch, (训练完特有)'update':所完成第几轮的百分之几批次添加进一个OrderDict()\n # {\"epoch\": 1, \"train_loss\": \"13.215\", \"train_nll_loss\": \"13.204\", \"train_ppl\": \"9438.41\", \"train_wps\": \"0.9\", \"train_ups\": \"0\",\n # \"train_wpb\": \"2804\", \"train_bsz\": \"132\", \"train_num_updates\": \"2\", \"train_lr\": \"2.74975e-07\",\n # \"train_gnorm\": \"8.076\", \"train_train_wall\": \"48\", \"train_wall\": \"0\"}\n\n # reset epoch-level meters 重置轮数级别(训练完一轮)的指标器\n metrics.reset_meters('train')\n\n\ndef get_training_stats(stats): # stats为在'train_inner'下所汇聚的平滑值,即MetersDict中非\"_\"开头的key,以及其smoothed_value所组成的有序字典\n if 'nll_loss' in stats and 'ppl' not in stats: # 若stats不存在'ppl',则由所存在'nll_loss'计算'ppl'\n stats['ppl'] = utils.get_perplexity(stats['nll_loss'])\n stats['wall'] = round(metrics.get_meter('default', 'wall').elapsed_time, 0) # 将\"wall\":总运行时间,以及优先级,由log_scalar添加到MetersDict中实时记录并更新\n return stats\n\n\ndef validate(args, trainer, task, epoch_itr, subsets):\n \"\"\"Evaluate the model on the validation set(s) and return the losses.\"\"\"\n\n if args.fixed_validation_seed is not None: # 为每一次验证过程设置固定的随机数生成器种子,非默认情况\n # set fixed seed for every validation\n utils.set_torch_seed(args.fixed_validation_seed)\n\n valid_losses = [] # 用于存储验证集平均目标词��应的-lable_smoothing loss/log(2)的列表\n for subset in subsets: # 遍历存储全部验证集spilt名称的列表\n # Initialize data iterator\n # 初始化验证集的数据迭代器,与训练集基本一致,区别:ignore_invalid_inputs=False(仅当max_positions小于验证集中句子长度时生效),shuffle=False(验证集不打乱)\n itr = task.get_batch_iterator(\n dataset=task.dataset(subset), # 根据subset返回加载的数据集split类,\n max_tokens=args.max_tokens_valid, # 批次大小(token-level,默认与max_tokens一致)\n max_sentences=args.max_sentences_valid,\n max_positions=utils.resolve_max_positions(\n task.max_positions(), # 返回task允许的最大句子长度,即(self.args.max_source_positions, self.args.max_target_positions)\n trainer.get_model().max_positions(), # 返回model允许的最大句子长度,即(self.args.max_source_positions, self.args.max_target_positions)\n ), # 通过resolve_max_positions解决来自多个来源的排名限制,返回(self.args.max_source_positions, self.args.max_target_positions)\n ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test, # 为False,为太长的句子引发异常\n required_batch_size_multiple=args.required_batch_size_multiple, # 需要一个批次是这个数的整数\n seed=args.seed, # 给定随机数种子\n num_shards=args.distributed_world_size, # 将数据集分成distributed_world_size片\n shard_id=args.distributed_rank, # 将数据集的所有分片带上序号\n num_workers=args.num_workers, # 多少个子进程用于数据加载,0表示将在主进程中加载数据\n ).next_epoch_itr(shuffle=False) # next_epoch_itr前,返回一个基于torch.utils.data.Dataset上的多epoch数据迭代器(验证集)\n # next_epoch_itr后, 返回self._cur_epoch_itr可记录迭代数的迭代器,基于torch.data.DataLoader在给定的数据集类上创建的数据加载器(验证集)\n progress = progress_bar.progress_bar(\n itr,\n log_format=args.log_format, # 记录所用格式,json\n log_interval=args.log_interval, # 每多少个batches打印进度,等价于disp_freq\n epoch=epoch_itr.epoch, # 当前epoch编号,由多epoch数据迭代器(训练集)给定\n prefix=f\"valid on '{subset}' subset\", #\n tensorboard_logdir=(\n args.tensorboard_logdir if distributed_utils.is_master(args) else None\n ), # 用tensorboard保存日志的路径\n default_log_format=('tqdm' if not args.no_progress_bar else 'simple'), # 若设置不报告进度信息,则默认log格式为tadm\n ) # 返回以JSON格式记录输出JsonProgressBar类(验证集),加载self._cur_epoch_itr可记录迭代数的迭代器,log_interval,当前epoch编号,offset等\n\n # create a new root metrics aggregator so validation metrics\n # don't pollute other aggregators (e.g., train meters) \n with metrics.aggregate(new_root=True) as agg: # 创建一个新的root指标汇聚器(上下文管理器),以便验证指标不影响其他汇聚器(如训练指标)\n for sample in progress: # 遍历JsonProgressBar类中的self._cur_epoch_itr可记录迭代数的迭代器,其中通过了多个类的__iter__(),得到一个批次的示例\n # id': 当前遍历的batch中全部句子对的ID的Tensor,按照源句子降序的order重新排列每行;'nsentences':句子对数;'ntokens':该批次所有目标句子的tokens总数;\n # 'net_input':\n # 'src_tokens':当前遍历的batch中全部源句子的tensor所转换的二维填充向量,按照源句子降序的order重新排列每行;\n # 'src_lengths':将当前遍历的batch中全部源句子的长度的Tensor;\n # 'prev_output_tokens':创建目标的移位版本(即全部目标句子的eos移到开头)\n # 'target': 当前遍历的batch中全部目标句子的tensor所转换的二维填充向量,按照源句子降序的order重新排列每行;\n trainer.valid_step(sample)\n # 返回有序字典logging_output,其中键值对有,{loss\":当前验证批次平均目标词对应的-lable_smoothing loss/log(2);\n # \"nll_loss\":当前验证批次平均目标词对应的-nll_loss(y_hot损失)/log(2);'sample_size':当前验证批次目标tokens数}\n\n # log validation stats 记录一轮验证完的统计\n stats = get_valid_stats(args, trainer, agg.get_smoothed_values()) # 获取在root指标下所汇聚的平滑值,即MetersDict中非\"_\"开头的key,以及其smoothed_value所组成的有序字典\n # OrderedDict([('loss', 13.211), ('nll_loss', 13.2), ('ppl', 9412.54), ('wps', 1.3), ('wpb', 648.0), ('bsz', 25.0), ('num_updates', 1)])\n progress.print(stats, tag=subset, step=trainer.get_num_updates())# 将'root(验证完)'下所汇聚的平滑值(带上tag='vaild'),以及'epoch':当前epoch, 添加进一个OrderDict()\n # {\"epoch\": 1, \"valid_loss\": \"13.211\", \"valid_nll_loss\": \"13.2\", \"valid_ppl\": \"9412.54\", \"valid_wps\": \"3.5\", \"valid_wpb\": \"648\",\n # \"valid_bsz\": \"25\", \"valid_num_updates\": \"1\"}\n valid_losses.append(stats[args.best_checkpoint_metric]) # 默认best_checkpoint_metric为loss,即将stats中vaild_loss存储进验证集平均目标词对应的-lable_smoothing loss/log(2)的列表\n return valid_losses # 返回验证集平均目标词对应的-lable_smoothing loss/log(2)列表\n\n\ndef get_valid_stats(args, trainer, stats): # stats为在root指标下下所汇聚的平滑值,即MetersDict中非\"_\"开头的key,以及其smoothed_value所组成的有序字典\n if 'nll_loss' in stats and 'ppl' not in stats: # 若stats不存在'ppl',则由所存在'nll_loss'计算'ppl'\n stats['ppl'] = utils.get_perplexity(stats['nll_loss'])\n stats['num_updates'] = trainer.get_num_updates() # 将\"num_updates\":当前批次更新步骤添加到MetersDict中实时记录并更新\n if hasattr(checkpoint_utils.save_checkpoint, 'best'): # 若checkpoint_utils.save_checkpoint存在'best';非默认情况\n key = 'best_{0}'.format(args.best_checkpoint_metric) # 默认最佳检查点指标为loss\n best_function = max if args.maximize_best_checkpoint_metric else min # 默认最佳检查点指标越小越好\n stats[key] = best_function(\n checkpoint_utils.save_checkpoint.best,\n stats[args.best_checkpoint_metric],\n ) # 将到目前为止的最佳检查点指标添加进stats中\n return stats\n\n\ndef distributed_main(i, args, start_rank=0):\n args.device_id = i\n if args.distributed_rank is None: # torch.multiprocessing.spawn\n args.distributed_rank = start_rank + i\n main(args, init_distributed=True)\n\n\ndef cli_main(modify_parser=None):\n parser = options.get_training_parser() # 根据特定的任务得到训练设置\n args = options.parse_args_and_arch(parser, modify_parser=modify_parser) # 返回全部的arguments设置\n\n if args.distributed_init_method is None: # 若不采用分布式训练,infer_init_method()不执行任何操作\n distributed_utils.infer_init_method(args)\n\n if args.distributed_init_method is not None: # 若分布式训练存在建立初始连接:\n # distributed training\n if torch.cuda.device_count() > 1 and not args.distributed_no_spawn:\n start_rank = args.distributed_rank\n args.distributed_rank = None # assign automatically\n torch.multiprocessing.spawn(\n fn=distributed_main,\n args=(args, start_rank),\n nprocs=torch.cuda.device_count(),\n )\n else:\n distributed_main(args.device_id, args)\n elif args.distributed_world_size > 1: # 若分布式训练设置了多个GPU\n # fallback for single node with multiple GPUs\n assert args.distributed_world_size <= torch.cuda.device_count()\n port = random.randint(10000, 20000)\n args.distributed_init_method = 'tcp://localhost:{port}'.format(port=port)\n args.distributed_rank = None # set based on device id\n torch.multiprocessing.spawn(\n fn=distributed_main,\n args=(args, ),\n nprocs=args.distributed_world_size,\n )\n else:\n # single GPU training\n main(args)\n\n\nif __name__ == '__main__':\n cli_main()\n","repo_name":"pengr/Deps-SAN","sub_path":"fairseq_cli/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":24371,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"32456508181","text":"from django.urls import path\nfrom rest_framework.routers import DefaultRouter\nfrom rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView\n\nfrom authentication import views\n\n\napp_name = 'authentication'\nrouter = DefaultRouter()\nrouter.include_root_view = False\nrouter.register('users', views.UserView, basename='user')\n\nurlpatterns = [\n path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),\n path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),\n path('token/verify/', TokenVerifyView.as_view(), name='token_verify'),\n *router.urls,\n]\n","repo_name":"BorisPlaton/shopping_cart_api","sub_path":"shopping_cart_api/authentication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"5749590940","text":"import requests\nimport names\nbase_url = \"https://reqres.in\"\n\n\ndef test_get_user_page2():\n get_url = f\"{base_url}/api/users?page=2\"\n response = requests.get(get_url)\n status = response.status_code\n assert status is 200, f\"Actual status is {status}\"\n text = response.json()\n assert text[\"page\"] is 2\n assert text[\"total\"] is 12\n assert text[\"data\"][0][\"id\"] is 7\n assert text[\"data\"][1][\"id\"] is 8\n assert text[\"data\"][2][\"id\"] is 9\n assert text[\"data\"][3][\"id\"] is 10\n assert text[\"data\"][4][\"id\"] is 11\n assert text[\"data\"][5][\"id\"] is 12\n\n\ndef test_create_user():\n post_url = f\"{base_url}/api/users\"\n name = names.get_first_name()\n body = {\"name\": name , \"job\": \"leader\"}\n response = requests.post(post_url, json = body)\n status = response.status_code\n assert status is 201\n text = response.json()\n assert text['name'] == name\n assert text['job'] == \"leader\"\n\ndef test_update_user():\n put_url = f\"{base_url}/api/users/\"\n name = names.get_last_name()\n body = {\"name\": name , \"job\": \"zion resident\"}\n response = requests.put(put_url, json = body)\n status = response.status_code\n assert status is 200\n text = response.json()\n assert text['name'] == name\n assert text['job'] == \"zion resident\"\n\ndef test_delete_user():\n delete_url = f\"{base_url}/api/users/2\"\n response = requests.delete(delete_url)\n status = response.status_code\n assert status is 204\n ","repo_name":"abiman20/pytest_rest_api","sub_path":"src/test_reqres.py","file_name":"test_reqres.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"12070708958","text":"\"\"\"\n- \"ticket/\" post Создание задач\n- \"ticket/\" get Получение всех задач\n\n- \"ticket/{ticket_id}\" get Получение задачи по id\n- \"ticket/{ticket_id}\" put Изменение задачи по id\n- \"ticket/{ticket_id}\" delete Удаление задачи по id\n- \"ticket/{ticket_id}/review\" post добавление duration к задаче\n- \"ticket/{ticket_id}/review\" put изменение duration к задаче\n\n\"\"\"\n\nimport csv\nfrom typing import Annotated, Optional\n\nfrom app import models, schemas, service, utils\nfrom app.dependencies import current_user, get_db\nfrom fastapi import (\n APIRouter,\n Body,\n Depends,\n FastAPI,\n File,\n HTTPException,\n Path,\n Query,\n Request,\n Response,\n UploadFile,\n status,\n)\nfrom sqlalchemy.orm import Session\n\nrouter = APIRouter(prefix=\"/ticket\", tags=[\"ticket\"])\n\n# get ticket/import\n\n@router.post(\n \"/create\",\n response_model=schemas.TicketDto,\n status_code=status.HTTP_201_CREATED,\n)\nasync def create_ticket(\n ticket: models.TicketCreate = Body(...),\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n \"\"\"\n Create a new ticket.\n \"\"\"\n return service.ticket.create(db, ticket, user)\n\n\n@router.get(\n \"/all\",\n response_model=list[schemas.TicketDto],\n status_code=status.HTTP_200_OK,\n)\nasync def get_ticket(\n request: Request,\n response: Response,\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n \"\"\"\n Get all tickets.\n \"\"\"\n return service.ticket.get_all(db, user)\n\n\n@router.get(\"/role/{role_id}\")\nasync def get_ticket_by_role(\n role_id: int,\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n \"\"\"\n Get all tickets by role.\n \"\"\"\n return service.ticket.get_all_by_role(db, role_id)\n\n\n@router.get(\n \"/{ticket_id}\",\n response_model=schemas.TicketDto,\n status_code=status.HTTP_200_OK,\n)\nasync def get_ticket_by_id(\n ticket_id: int,\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n \"\"\"\n Get ticket by id.\n \"\"\"\n try:\n return service.ticket.get(db, ticket_id)\n except Exception as e:\n raise HTTPException(status_code=404, detail=\"Ticket not found\")\n\n\n@router.put(\n \"/{ticket_id}\",\n response_model=schemas.TicketDto,\n status_code=status.HTTP_200_OK,\n)\nasync def update_ticket(\n ticket_id: int,\n ticket: models.TicketCreate = Body(...),\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n \"\"\"\n Update ticket by id.\n \"\"\"\n try:\n return service.ticket.update(db, ticket)\n except Exception as e:\n raise HTTPException(status_code=404, detail=\"Ticket not found\")\n\n\n@router.post(\"/{ticket_id}/review\")\nasync def review(\n ticket_id: int = Path(..., ge=1, description=\"Ticket id\"),\n payload: models.TicketReviewCreate = Body(...),\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n payload.ticket_id = ticket_id\n return service.ticket.review(db, payload, user)\n\n\n@router.post(\"/upload\")\nasync def upload_csv(\n file: UploadFile,\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n\n contents = await file.read() # Read the contents of the file as bytes\n decoded = contents.decode(\"utf-8\") # Decode the bytes to a string\n reader = csv.DictReader(decoded.splitlines(), delimiter=\";\", quotechar='\"')\n\n tickets = service.ticket.upload_csv(db, reader)\n return utils.ticket.assemble_ticket_dtos(tickets)\n\n\n@router.post(\"/teamflame\")\nasync def load_from_teamflame(\n db: Session = Depends(get_db),\n user: models.User = Depends(current_user),\n):\n tickets = service.ticket.get_from_teamflame(db, user)\n \n return utils.ticket.assemble_ticket_dtos(tickets)\n","repo_name":"EgorTarasov/innohack","sub_path":"backend/app/routers/ticket.py","file_name":"ticket.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"14318290187","text":"from setuptools import setup, find_packages\n\nversion = '0.4dev'\n\nsetup(name='collective.rope',\n version=version,\n description=(\"Zope2, CMF and Archetypes base classes to store content \"\n \"in relational databases through SQLAlchemy.\"),\n long_description=open(\"README.txt\").read() + \"\\n\" +\n open(\"HISTORY.txt\").read(),\n classifiers=[\n \"Framework :: Zope2\",\n \"Programming Language :: Python\",\n ],\n keywords='',\n author='Plone Community',\n author_email='plone@plone.org',\n url='http://svn.plone.org/svn/collective/collective.rope',\n license='GPL',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'Zope2',\n 'z3c.saconfig',\n ],\n extras_require=dict(\n plone=[\n 'Plone',\n ],\n test=[\n 'mock',\n 'plone.bbb_testing',\n 'plone.app.bbb_testing',\n ],\n ))\n","repo_name":"affinitic/collective.rope","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"14518926441","text":"from PyQt6.QtCore import QObject, QThreadPool, pyqtSignal\nimport importlib\nfrom task_management.task_worker import TaskWorker\nfrom shared.shared_data import tasks_data\nfrom automated_tasks.browser_session_manager import BrowserSessionManager # Import the session manager\n\nclass TaskManager(QObject):\n taskStarted = pyqtSignal(str)\n taskStopped = pyqtSignal(str)\n tasksDataChanged = pyqtSignal()\n\n def __init__(self):\n super().__init__()\n self.thread_pool = QThreadPool()\n self.workers = {}\n self.orchestrators = {}\n self.session_manager = BrowserSessionManager() # Instantiate the session manager\n\n def start_task(self, task_id, task_name, task_config):\n # Import the module containing the task orchestrator\n module_name = f\"automated_tasks.tasks.{task_name}.task_orchestrator\"\n task_orchestrator_module = importlib.import_module(module_name)\n\n # Get the class name of the orchestrator\n class_name = f\"{task_name}Orchestrator\"\n task_orchestrator_class = getattr(task_orchestrator_module, class_name)\n\n # Add the task ID to the task configuration\n task_config['task_id'] = task_id\n\n # Create a new browser session for the task\n # You might want to modify this part to reuse existing sessions or based on specific conditions\n session_id, _ = self.session_manager.create_browser_session() # For simplicity, creating a new session\n\n # Instantiate the task orchestrator with the task configuration, session manager, and session ID\n task_orchestrator = task_orchestrator_class(task_config, self.session_manager, session_id)\n\n # Store the orchestrator reference\n self.orchestrators[task_id] = task_orchestrator\n\n # Create a worker for the task and start it in a new thread\n worker = TaskWorker(task_orchestrator, task_config)\n self.workers[task_id] = worker\n self.thread_pool.start(worker)\n\n # Emit the signal indicating the task has started\n self.taskStarted.emit(task_id)\n \n # Update the shared task data with the new task's information\n tasks_data[task_id] = {\n \"name\": task_name,\n \"status\": \"Running\",\n \"config\": task_config\n }\n\n # Emit a signal to indicate the tasks data has changed\n print(\"Task started, emitting tasksDataChanged signal.\")\n self.tasksDataChanged.emit()\n\n\n def stop_task(self, task_id):\n print(f\"Stopping task with ID: {task_id}\")\n if task_id in self.workers:\n worker = self.workers[task_id]\n worker.stop()\n\n # Remove the task from tasks_data if it exists\n if task_id in tasks_data:\n del tasks_data[task_id]\n print(f\"Task {task_id} removed from tasks_data.\")\n\n # Emit the signal to indicate tasks data has changed\n self.tasksDataChanged.emit()\n else:\n print(f\"No worker found for task ID: {task_id}\")\n\n def stop_all_tasks(self):\n \"\"\"\n Stop all running tasks.\n \"\"\"\n print(\"Stopping all running tasks.\")\n for task_id in list(self.workers.keys()): # Iterate over a copy of the keys\n self.stop_task(task_id)\n\n # Optionally, wait for all tasks to finish if needed\n self.thread_pool.waitForDone()\n \n def get_orchestrator(self, task_id):\n orchestrator = self.orchestrators.get(task_id, None)\n print(f\"Retrieving orchestrator for task {task_id}: {orchestrator}\")\n return orchestrator\n \n def on_task_finished(self, task_id):\n if task_id in self.workers:\n del self.workers[task_id]\n if task_id in tasks_data:\n del tasks_data[task_id]\n print(f\"Task {task_id} removed from tasks_data after completion.\")\n\n self.taskStopped.emit(task_id)\n self.tasksDataChanged.emit()\n\n def on_task_error(self, task_id, error):\n print(f\"Error in task {task_id}: {error}\")\n if task_id in self.workers and task_id in tasks_data:\n # Optionally, you can update tasks_data with error details\n # tasks_data[task_id][\"status\"] = \"Error\"\n del tasks_data[task_id]\n print(f\"Task {task_id} removed from tasks_data due to error.\")\n\n self.on_task_finished(task_id)","repo_name":"genekyle/wsai","sub_path":"task_management/task_manager.py","file_name":"task_manager.py","file_ext":"py","file_size_in_byte":4416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"29533809673","text":"# -*- coding:utf-8 -*-\n\ndef solve():\n N = int(input())\n As = list(map(int, input().split()))\n MAX = 10**18\n\n if 0 in As:\n print(0)\n return\n\n ans = 1\n for a in As:\n ans *= a\n if ans > MAX:\n print(-1)\n return\n print(ans)\n\n\nif __name__ == \"__main__\":\n solve()\n","repo_name":"taketakeyyy/atcoder","sub_path":"abc/169/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"9194765463","text":"from shapely.geometry import Polygon, Point\nfrom shapely.geometry.base import BaseGeometry\n\nfrom geospark.utils.decorators import require\n\n\nclass Envelope(Polygon):\n\n def __init__(self, minx=0, maxx=1, miny=0, maxy=1):\n self.minx = minx\n self.maxx = maxx\n self.miny = miny\n self.maxy = maxy\n super().__init__([\n [self.minx, self.miny],\n [self.minx, self.maxy],\n [self.maxx, self.maxy],\n [self.maxx, self.miny]\n ])\n\n @require([\"Envelope\"])\n def create_jvm_instance(self, jvm):\n return jvm.Envelope(\n self.minx, self.maxx, self.miny, self.maxy\n )\n\n @classmethod\n def from_jvm_instance(cls, java_obj):\n return cls(\n minx=java_obj.getMinX(),\n maxx=java_obj.getMaxX(),\n miny=java_obj.getMinY(),\n maxy=java_obj.getMaxY(),\n )\n\n def to_bytes(self):\n from geospark.utils.binary_parser import BinaryBuffer\n bin_buffer = BinaryBuffer()\n bin_buffer.put_double(self.minx)\n bin_buffer.put_double(self.maxx)\n bin_buffer.put_double(self.miny)\n bin_buffer.put_double(self.maxy)\n return bin_buffer.byte_array\n\n @classmethod\n def from_shapely_geom(cls, geometry: BaseGeometry):\n if isinstance(geometry, Point):\n return cls(geometry.x, geometry.x, geometry.y, geometry.y)\n else:\n envelope = geometry.envelope\n exteriors = envelope.exterior\n coordinates = list(exteriors.coords)\n x_coord = [coord[0] for coord in coordinates]\n y_coord = [coord[1] for coord in coordinates]\n\n return cls(min(x_coord), max(x_coord), min(y_coord), max(y_coord))\n\n def __reduce__(self):\n return (self.__class__, (), dict(\n minx=self.minx,\n maxx=self.maxx,\n miny=self.miny,\n maxy=self.maxy,\n\n ))\n\n def __getstate__(self):\n return dict(\n minx=self.minx,\n maxx=self.maxx,\n miny=self.miny,\n maxy=self.maxy,\n\n )\n\n def __setstate__(self, state):\n self.minx = state.get(\"minx\", 0)\n self.minx = state.get(\"maxx\", 1)\n self.minx = state.get(\"miny\", 0)\n self.minx = state.get(\"maxy\", 1)\n\n @property\n def __array_interface__(self):\n raise NotImplementedError()\n\n def _get_coords(self):\n raise NotImplementedError()\n\n def _set_coords(self, ob):\n raise NotImplementedError()\n\n @property\n def coords(self):\n raise NotImplementedError()","repo_name":"Debadarsini/geospark-st-covers","sub_path":"python/geospark/core/geom/envelope.py","file_name":"envelope.py","file_ext":"py","file_size_in_byte":2606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"9329066403","text":"##########################################################################\n# File Name: 1471.py\n# Creat Time: 2022年03月23日 星期三 18时11分05秒\n# Author :Charliegean\n# Mail :wht905@gmail.com\n##########################################################################\n#!/usr/bin/env python3\n# coding=utf-8\n\ndef main():\n print(\"hello world\")\n\nif __name__==\"__main__\":\n main()\nclass Solution:\n def getStrongest(self, arr: List[int], k: int) -> List[int]:\n arr.sort()\n m=arr[int((len(arr)-1)/2)]\n bInd=0\n eInd=len(arr)-1\n res=[]\n while len(res)=m-arr[bInd]:\n res.append(arr[eInd])\n eInd-=1\n else:\n res.append(arr[bInd])\n bInd+=1\n return res\n","repo_name":"charliegeannew/codeSpaceGit","sub_path":"leetcode/finish/1471.py","file_name":"1471.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"39288091444","text":"print('Медалисты золото/серебро/бронза')\r\nwhile True:\r\n a = input()\r\n if a == ('золото'):\r\n print('никого нету;(')\r\n elif a == ('серебро'):\r\n print('Aйсулу Тыныбекова\\n''Акжол Махмудов\\n')\r\n elif a == ('бронза'):\r\n print('Мээрим Жуманазарова\\n')\r\n else:\r\n ptiny('пиши правильно')\r\n","repo_name":"islam1221/islam1221","sub_path":"homework2.py","file_name":"homework2.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"32220845349","text":"import json\nimport os\nimport time\n\nfrom logger import get_logger\nimport gc\n\nlogger = get_logger(__name__)\n\n\nclass Store(object):\n def __init__(self, dir=\"data\", prefix=\"repos\"):\n self._buf = []\n self._max_buf_count = 1000\n # if than this,will store\n self._dir = dir\n self._prefix = prefix\n self.path = self.new_file()\n self._now = 0\n \n async def put(self, data: list):\n if len(data) == 0:\n logger.info(f\"no data put to store\")\n return\n \n logger.info(f\"put {len(data)} to store\")\n self._buf.extend(data)\n self._now += len(data)\n if self._now > self._max_buf_count:\n self._now = 0\n self.path = self.new_file()\n self.store()\n \n def new_file(self) -> str:\n file_name = self._prefix + str(round(time.time() * 1000))\n logger.info(f\"will store {len(self._buf)} to {file_name}\")\n if os.path.isdir(self._dir):\n # join path\n path = os.path.join(self._dir, file_name)\n else:\n # path does not exist , store the current dir\n path = os.path.join(file_name)\n return path\n \n def store(self):\n with open(self.path, \"a\") as fp:\n json.dump(self._buf, fp)\n \n self._buf.clear()\n # clear buffer\n","repo_name":"china-shang/project2","sub_path":"datastore.py","file_name":"datastore.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"71281782539","text":"#initialization\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\n\n# importing Qiskit\nfrom qiskit import IBMQ, Aer, assemble, transpile\nfrom qiskit import QuantumCircuit\nfrom qiskit.providers.ibmq import least_busy\nfrom qiskit.circuit.library import RYGate\n\n# import basic plot tools\nfrom qiskit.visualization import plot_histogram\nimport qiskit.quantum_info as qi\nfrom qiskit.circuit.library import CSwapGate\nfrom qiskit.circuit.library import RYGate\n\nfrom trained import trained_vector\n\n\ndef gate_from_state(a, b):\n norm = math.sqrt(a ** 2 + b ** 2)\n x, y = a / norm, b / norm\n if y >= 0:\n theta = np.arccos(x)\n elif x <= 0 and y <= 0:\n theta = 2 * np.pi - np.arccos(x)\n elif x >= 0 and y <= 0:\n theta = 2 * np.pi - np.arccos(x)\n U = RYGate(theta * 2) \n U = RYGate(theta * 2)\n return U\n\ndef create_gate_from_4(x, y, z, t, verbose = False):\n norm = math.sqrt(x ** 2 + y ** 2 + z ** 2 + t ** 2)\n a, c, b, d = x / norm, y / norm, z / norm, t / norm\n if verbose:\n print(a, b, c, d)\n ab_norm = math.sqrt(a ** 2 + b ** 2)\n cd_norm = math.sqrt(c ** 2 + d ** 2)\n U_first = gate_from_state(ab_norm, cd_norm)\n U_ab = gate_from_state(a, b)\n U_ab_inverse = U_ab.inverse()\n \n U_cd = gate_from_state(c, d)\n \n qr = QuantumCircuit(1)\n qr.append(U_ab_inverse,[0])\n qr.append(U_cd,[0])\n U_ab_cd = qr.to_gate(label =\"ab->cd\")\n cU_ab_cd = U_ab_cd.control(1)\n \n main = QuantumCircuit(2)\n main.append(U_first, [0])\n main.append(U_ab, [1])\n main.append(cU_ab_cd, [0, 1])\n \n return main.to_gate(label = f\"U\")\n\n\ndef create_curcuit(testing_gate, trained_gates):\n qc = QuantumCircuit(3 + 2 + 2 + 8 + 4, 2 + 1)\n # h of the control qubit for the swap test\n qc.h([0])\n # h for the indecies\n qc.h([5,6])\n \n # append test gate \n qc.append(testing_gate, [1, 2])\n \n qc.barrier()\n # case 11, controls 18\n qc.ccx(5, 6, 18)\n qc.barrier()\n # case 01, controls 16\n qc.ccx(5, 6, 16)\n qc.cx(5, 16)\n qc.barrier()\n # case 10, controls 17\n qc.ccx(5, 6, 17)\n qc.cx(6, 17)\n qc.barrier()\n # case 00, controls 15 \n qc.x([5,6])\n qc.ccx(5, 6, 15)\n qc.x([5,6])\n qc.barrier()\n \n # adding the trained gates\n for i in range(4):\n qc.append(trained_gates[i], [2 * i + 7, 2 * i + 8])\n \n qc.barrier()\n # reading indecies and swapping the states\n qc.append(CSwapGate(), [15, 3, 7])\n qc.append(CSwapGate(), [15, 4, 8])\n\n qc.append(CSwapGate(), [16, 3, 9])\n qc.append(CSwapGate(), [16, 4, 10])\n \n qc.append(CSwapGate(), [17, 3, 11])\n qc.append(CSwapGate(), [17, 4, 12])\n \n qc.append(CSwapGate(), [18, 3, 13])\n qc.append(CSwapGate(), [18, 4, 14])\n \n qc.barrier()\n \n qc.barrier()\n qc.append(CSwapGate(), [0, 1, 3])\n qc.append(CSwapGate(), [0, 2, 4])\n qc.h(0)\n \n qc.barrier()\n qc.measure(0, 0)\n qc.measure(6, 1)\n qc.measure(5, 2)\n \n return qc\n\ndef run_experiment_with_shots(circuit, shots, verbose = True):\n aer_sim = Aer.get_backend('aer_simulator')\n transpiled_circuit = transpile(circuit, aer_sim)\n qobj = assemble(transpiled_circuit)\n results = aer_sim.run(qobj, shots=shots).result()\n counts = results.get_counts()\n if verbose:\n display(plot_histogram(counts))\n return counts\n\ndef process_counts(counts, state_to_key, verbose = True):\n res = {}\n for k in counts.keys():\n gate_index, v, value = state_to_key[k[:2]], k[2], counts[k]\n if gate_index in res:\n d = res[gate_index]\n if v in d:\n d[v] += value\n else:\n d[v] = value\n else:\n res[gate_index] = {v: value}\n\n experiment_results = {}\n for k in sorted(res.keys()):\n d = res[k]\n if '1' in d:\n p = d['1']/(d['1'] + d['0'])\n else:\n p = 0\n experiment_results[k] = p\n if verbose:\n print(f\"Probability of 1 in gate {k} is {p}\")\n \n return experiment_results\n\ndef get_sim_4_vectors(test, four_vectors_with_index, shots=1024, verbose = True):\n assert(len(four_vectors_with_index) == 4)\n id0, vec0 = four_vectors_with_index[0]\n id1, vec1 = four_vectors_with_index[1]\n id2, vec2 = four_vectors_with_index[2]\n id3, vec3 = four_vectors_with_index[3]\n \n gates = list(map(lambda x: create_gate_from_4(*x), [vec0, vec1, vec2, vec3]))\n \n test_gate = create_gate_from_4(*test)\n \n state_to_key = {'00': id0, '01': id1, '10': id2, '11': id3}\n\n qc = create_curcuit(test_gate, gates)\n \n counts = run_experiment_with_shots(qc, shots, verbose)\n counts_processed = process_counts(counts, state_to_key, verbose)\n \n res = {}\n for k, p in counts_processed.items():\n squared = 1 - 2 * p\n res[k] = squared\n return res\n\ndef get_sim_new(test_vector, trained_vectors = trained_vector, shots=4096):\n n = (len(trained_vectors) // 4) * 4\n # all_res = []\n max_score = 0\n max_id = None\n for i in range(0, n, 4):\n sample_trained_vectors = list(map(lambda j: (j, trained_vectors[j]), [i, i+1, i+2, i+3]))\n sims = get_sim_4_vectors(test_vector, sample_trained_vectors, shots=shots, verbose=False)\n # all_res.append(sims)\n res = []\n for k, v in sims.items():\n res.append((v, k))\n if v > max_score:\n max_id = k\n max_score = v\n # print(all_res)\n return max_id, max_score","repo_name":"Inverseit/quantum-estimator","sub_path":"new_quantum_core.py","file_name":"new_quantum_core.py","file_ext":"py","file_size_in_byte":5526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"73365376778","text":"from csv import reader\r\nfrom math import sqrt\r\nfrom random import seed\r\nfrom random import randrange\r\n\r\n# Load a CSV file\r\ndef load_csv(filename):\r\n dataset = list()\r\n with open(filename, 'r') as file:\r\n csv_reader = reader(file)\r\n for row in csv_reader:\r\n #print(row)\r\n if not row:\r\n continue\r\n dataset.append(row)\r\n return dataset\r\n\r\n# Convert string column to float\r\ndef str_column_to_float(dataset, column):\r\n for row in dataset:\r\n row[column] = float(row[column].strip())\r\n\r\n# Find the min and max values for each column\r\ndef dataset_minmax(dataset):\r\n minmax = list()\r\n for i in range(len(dataset[0])):\r\n col_values = [row[i] for row in dataset]\r\n value_min = min(col_values)\r\n value_max = max(col_values)\r\n minmax.append([value_min, value_max])\r\n return minmax\r\n\r\n# Rescale dataset columns to the range 0-1\r\ndef normalize_dataset(dataset, minmax):\r\n for row in dataset:\r\n for i in range(len(row)):\r\n row[i] = (row[i] - minmax[i][0]) / (minmax[i][1] - minmax[i][0])\r\n\r\n# calculate column means\r\ndef column_means(dataset):\r\n means = [0 for i in range(len(dataset[0]))]\r\n for i in range(len(dataset[0])):\r\n col_values = [row[i] for row in dataset]\r\n means[i] = sum(col_values) / float(len(dataset))\r\n return means\r\n\r\n# calculate column standard deviations\r\ndef column_stdevs(dataset, means):\r\n stdevs = [0 for i in range(len(dataset[0]))]\r\n for i in range(len(dataset[0])):\r\n variance = [pow(row[i]-means[i], 2) for row in dataset]\r\n stdevs[i] = sum(variance)\r\n stdevs = [sqrt(x/(float(len(dataset)-1))) for x in stdevs]\r\n return stdevs\r\n\r\n# standardize dataset\r\ndef standardize_dataset(dataset, means, stdevs):\r\n for row in dataset:\r\n for i in range(len(row)):\r\n row[i] = (row[i] - means[i]) / stdevs[i]\r\n\r\n# Split a dataset into a train and test set\r\ndef train_test_split(dataset, split=0.60):\r\n train = list()\r\n train_size = split * len(dataset)\r\n dataset_copy = list(dataset)\r\n while len(train) < train_size:\r\n index = randrange(len(dataset_copy))\r\n train.append(dataset_copy.pop(index))\r\n return train, dataset_copy\r\n\r\n##Ejercicios\r\ndef print_cols_first_ten_rows(dataset):\r\n i = 0\r\n while i < 10:\r\n print(dataset[i])\r\n i += 1\r\n\r\ndef main():\r\n dataset = load_csv(\"./wine.csv\")\r\n #Ej 3\r\n for i in range(0, 14):\r\n str_column_to_float(dataset, i)\r\n\r\n #Ej 2\r\n print(\"10 priemras filas\")\r\n print_cols_first_ten_rows(dataset)\r\n\r\n #Ej 4\r\n res_min_max = dataset_minmax(dataset)\r\n print(\"\\nValores minimos y maximos de cada columna\")\r\n print(res_min_max)\r\n\r\n #Ej 5\r\n means = column_means(dataset)\r\n print(\"\\n Las medias de cada columna\")\r\n print(means)\r\n\r\n #Ej 6\r\n stdevs = column_stdevs(dataset, means)\r\n print(\"\\n Desviación estándar\")\r\n print(stdevs)\r\n\r\n #Ej 7\r\n normalize_dataset(dataset, res_min_max)\r\n \r\n #Ej 8\r\n standardize_dataset(dataset, means, stdevs)\r\n\r\n #Ej 9\r\n train, test = train_test_split(dataset)\r\n print(\"\\nLa data de entrenamiento\\n\")\r\n print(train)\r\n print(\"\\nLa data de test\\n\")\r\n print(test)\r\nmain() ","repo_name":"tomasrama12/IA_01","sub_path":"pd3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"29841174593","text":"#! /usr/bin/env python3.6\n\nfrom optparse import OptionParser\nimport requests\nimport json\nimport xml.etree.cElementTree as ET\n\n\nclass CurrencyConverter:\n URL = \"https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml\"\n\n def __init__(self):\n self.codes = self.get_codes()\n self.rates = self.get_data_rates()\n\n def convert_to_code(self, currency):\n \"\"\"\n If currency symbol was given on input then the symbol is converted to currency code.\n :param currency: Symbol or code of given currency.\n :return: Code of given currency.\n \"\"\"\n\n if currency in ['EUR', '\\u20ac']:\n return 'EUR'\n\n code = self.codes.get(currency)\n\n if code is None:\n code = currency\n\n if code not in self.rates:\n self.handle_error('Bad input/output symbol/code')\n\n return code\n\n def parse_arguments(self, arg_parser):\n \"\"\"\n Parse arguments and prepares basic output object in json format.\n :param arg_parser: Object for parsing arguments.\n :return: Basic output object in json format.\n \"\"\"\n (options, args) = arg_parser.parse_args()\n\n if options.amount is None:\n self.handle_error('Argument amount is missing!')\n\n if options.input_currency is None:\n self.handle_error('Argument input_currency is missing!')\n\n if options.output_currency is not None:\n output_symb = self.convert_to_code(options.output_currency)\n if output_symb not in self.rates:\n self.handle_error(\"Bad output currency symbol / code\")\n else:\n output_symb = None\n\n input_symb = self.convert_to_code(options.input_currency)\n\n if input_symb not in self.rates:\n self.handle_error(\"Bad input currency symbol / code\")\n\n cli_output = {\n 'input': {\n 'amount': options.amount,\n 'currency': input_symb\n },\n 'output': output_symb\n }\n\n return cli_output\n\n def get_data_rates(self):\n \"\"\"\n Retrieves data about currency rates from hard coded url in xml format\n and converts it to json.\n :return: Currency rates json object.\n \"\"\"\n response = requests.get(self.URL)\n\n if response.status_code != 200:\n self.handle_error('Failed to get currency rates')\n\n root = ET.fromstring(response.text)\n\n result_json_rates = {}\n\n try:\n for child in root[2][0]:\n result_json_rates[child.attrib.get('currency')] = float(child.attrib.get('rate'))\n except IndexError:\n raise Exception(\"Index out of bound exception\")\n except ValueError:\n raise Exception(\"Bad currency value format\")\n\n # Need to explicitly add EUR to EUR\n result_json_rates['EUR'] = float(1)\n return json.loads(json.dumps(result_json_rates, indent=4))\n\n def get_codes(self):\n \"\"\"\n Reads currency symbols and their codes from file 'symbols_codes'.\n :return: Currency symbols and their codes json object.\n \"\"\"\n try:\n with open('symbols_codes', 'r') as file:\n result = json.loads(file.read())\n file.close()\n except IOError:\n self.handle_error(\"Symbols_codes file missing in directory.\")\n\n return result\n\n def compute(self, cli_output):\n \"\"\"\n Compute converted value in given output currency. If output currency was not given, function converts\n to all supported currencies.\n :param cli_output: Basic output object in json format.\n \"\"\"\n output_symb = cli_output['output']\n result_json = {}\n\n if output_symb is not None:\n result = cli_output['input']['amount'] / self.rates[cli_output['input']['currency']] * self.rates[\n output_symb]\n result_json[output_symb] = result\n else:\n for rate in self.rates:\n if rate == cli_output['input']['currency']:\n continue\n result = cli_output['input']['amount'] / self.rates[cli_output['input']['currency']] * self.rates[\n rate]\n result_json[rate] = result\n\n cli_output['output'] = result_json\n\n return cli_output\n\n @staticmethod\n def print_result(result):\n print(json.dumps(result, indent=4))\n\n @staticmethod\n def handle_error(error_message):\n print(error_message)\n exit(-1)\n\n\nif __name__ == '__main__':\n parser = OptionParser()\n parser.add_option('--amount', type=\"float\")\n parser.add_option('--input_currency')\n parser.add_option('--output_currency')\n\n converter = CurrencyConverter()\n\n output = converter.parse_arguments(parser)\n output = converter.compute(output)\n converter.print_result(output)\n","repo_name":"xcalad01/Kiwi-currency_converter","sub_path":"currency_converter.py","file_name":"currency_converter.py","file_ext":"py","file_size_in_byte":4916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"34722106964","text":"import hashlib\nimport random\nimport time\nimport uuid\n\nfrom django.http import JsonResponse\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom pet.models import User, Goods, Cart, Order, OrderGoods\n\n\ndef index(request):\n return render(request,'index.html')\n\n\ndef homepage(request):\n token=request.session.get('token')\n user=None\n if token:\n user=User.objects.get(token=token)\n goods=Goods.objects.all()\n\n\n return render(request,'homepage.html' ,context={'user':user,\n 'goods':goods})\n\n\ndef genrate_token():\n token = str(time.time()) + str(random.random())\n md5 = hashlib.md5()\n md5.update(token.encode('utf-8'))\n\n return md5.hexdigest()\n\n\ndef genrate_password(password):\n md5 = hashlib.md5()\n md5.update(password.encode('utf-8'))\n return md5.hexdigest()\n\n\ndef register(request):\n if request.method=='GET':\n\n return render(request,'register.html')\n elif request.method=='POST':\n tel=request.POST.get('tel')\n name=request.POST.get('name')\n password=request.POST.get('password')\n try:\n user=User()\n user.u_tel=tel\n user.u_name=name\n user.u_password=genrate_password(password)\n user.token=genrate_token()\n user.save()\n response=redirect(\"pet:homepage\")\n request.session['token']=user.token\n return response\n except:\n return render(request,'register.html')\n\n\ndef login(request):\n if request.method=='GET':\n return render(request,'login.html')\n elif request.method=='POST':\n\n name=request.POST.get('name')\n password=request.POST.get('password')\n users=User.objects.filter(u_name=name).filter(u_password=genrate_password(password))\n if users.exists():\n user=users.first()\n user.token=genrate_token()\n user.save()\n response=redirect('pet:homepage')\n request.session['token']=user.token\n return response\n else:\n return render(request,'login.html')\n\n\ndef goods(request,index=1):\n\n token=request.session.get('token')\n users=User.objects.filter(token=token)\n good=Goods.objects.get(id=index)\n if users.exists():\n user=users.first()\n return render(request,'goods.html',context={'good':good,\n 'user':user})\n else:\n\n return render(request,'login.html')\n\n\ndef logout(request):\n request.session.flush()\n response=redirect('pet:homepage')\n\n\n return response\n\n\n\n\ndef addcart(request):\n response_data={}\n\n token=request.session.get('token','')\n\n if token:\n users=User.objects.filter(token=token)\n\n if users.exists():\n user=users.first()\n goodsid = request.GET.get('goodid')\n num=request.GET.get('num')\n good = Goods.objects.get(pk=goodsid)\n carts=Cart.objects.filter(user=user).filter(goods=good)\n if carts.exists():\n cart=carts.first()\n cart.number=cart.number+int(num)\n cart.save()\n else:\n cart=Cart()\n cart.goods=good\n cart.user=user\n cart.number=1\n cart.save()\n response_data['status']=1\n response_data['number']=cart.number\n response_data['msg']='添加{}购物车成功:{}'.format(cart.goods.g_name,cart.number)\n\n\n return JsonResponse(response_data)\n response_data['status'] = -1\n response_data['msg'] = '请登录后操作'\n return JsonResponse(response_data)\n\n\ndef shopcar(request):\n token=request.session.get('token')\n user=User.objects.get(token=token)\n carts=Cart.objects.filter(user=user)\n price=0\n\n for cart in carts:\n price+=float(cart.goods.g_price)*float(cart.number)\n\n\n return render(request,'shopcar.html',context={'carts':carts,'price':price, })\n\n\ndef subcart(request):\n return None\n\n\ndef changecart(request):\n return None\n\n\ndef changeselect(request):\n return None\n\n\ndef generateorder(request):\n token=request.session.get('token')\n if token :\n user=User.objects.get(token=token)\n order=Order()\n order.user=user\n order.number=str(uuid.uuid5(uuid.uuid4(), 'order'))\n order.save()\n\n\n carts=Cart.objects.filter(user=user).filter(isselect=True)\n for cart in carts:\n orderGoods=OrderGoods()\n orderGoods.order=order\n orderGoods.goods=cart.goods\n orderGoods.number=cart.number\n orderGoods.save()\n cart.delete()\n\n orders=Order.objects.filter(user=user)\n\n return render(request,'orderinfo.html',context={'orders':orders})\n\n\ndef orderinfo(request):\n orderGoods = OrderGoods.objects.all()\n\n return render(request,'ordertext.html',context={'orderGoods':orderGoods})\n\n\ndef changeorder(request):\n return None","repo_name":"liuxinfeng312/epet","sub_path":"pet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5047,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"40755330277","text":"from models import Review, UpdateReviewModel\nimport motor.motor_asyncio # MongoDB Driver\nfrom bson.objectid import ObjectId\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\napi_key = os.environ.get('CLUSTER_PASSWORD')\n\n\n# MongoDB driver\nimport motor.motor_asyncio\n\nclient = motor.motor_asyncio.AsyncIOMotorClient(api_key)\ndatabase = client.ReviewList\ncollection = database.review\n\n\nasync def fetch_one_review(id):\n review = await collection.find_one({\"_id\": id})\n if review is not None:\n return review\n\nasync def fetch_all_reviews():\n reviews = []\n cursor = collection.find({})\n async for document in cursor:\n reviews.append(Review(**document))\n return reviews\n\nasync def create_review(review):\n document = review\n result = await collection.insert_one(document)\n return document\n\nasync def update_review(id, review):\n update_result = await collection.update_one({\"_id\": id}, {\"$set\": review})\n if update_result.modified_count == 1:\n updated_review = await collection.find_one({\"_id\": id})\n if updated_review is not None:\n return updated_review\n existing_review = await collection.find_one({\"_id\": id})\n if existing_review is not None:\n return existing_review\n\nasync def remove_review(id):\n await collection.delete_one({\"_id\": id})\n return True","repo_name":"CCKJon/cookbook","sub_path":"backend-reviews/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"21873948651","text":"from src.models.tournament import Tournament \nfrom src.models.player import Player \nfrom src.constants import *\nimport pytest\nimport datetime\nfrom tinydb import TinyDB, Query \n\n@pytest.fixture\ndef player_json():\n return {\n \"first_name\": \"Bill\",\n \"last_name\": \"Sorenson\",\n \"sex\": \"Male\",\n \"rating\": 20,\n \"dob\": \"24 September, 1992\",\n \"doc_id\": -1\n } \n \ndef test_player_creation():\n json = {\n \"first_name\": \"Alex\",\n \"last_name\": \"Mack\",\n \"rating\": 10,\n \"sex\": \"Male\",\n \"dob\": \"20 March, 1989\",\n \"doc_id\": -1\n }\n new_player = Player(**json)\n new_player.save()\n \n assert new_player.first_name == \"Alex\"\n assert new_player.last_name == \"Mack\"\n assert new_player.dob == datetime.datetime.strptime(\"20 March, 1989\",DEFAULT_DATE_FORMAT_STRING)\n assert new_player.sex == \"Male\"\n assert new_player.rating == 10 \n assert new_player.doc_id != -1\n \n \ndef test_player_creation2():\n json = {\n \"first_name\": \"Alex\",\n \"last_name\": \"Mack\",\n \"rating\": 10,\n \"sex\": \"Male\",\n \"dob\": \"20 March, 1989\",\n \"doc_id\": -1\n }\n new_player = Player(**json)\n new_player.save()\n \n db = TinyDB('db.json')\n players_table = db.table('players')\n q = Query()\n \n result1 = players_table.search(q.first_name==\"Alex\")\n target_player = result1[0]\n \n assert target_player[\"first_name\"] == new_player.first_name\n \n result1 = players_table.search(q.last_name==\"Mack\")\n target_player = result1[0]\n \n assert target_player[\"last_name\"] == new_player.last_name\n \n \ndef test_player_creation3(player_json):\n new_player = Player(**player_json)\n new_player.save()\n \n assert new_player.first_name == \"Bill\"\n assert new_player.last_name == \"Sorenson\"\n assert new_player.doc_id != -1\n \n\ndef test_tournament_creation():\n pass","repo_name":"mack-book-review/ChessTournament","sub_path":"tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"30522893080","text":"'''\nComplete the code in the main() function which adds 1 to\neach list element in the list which has an odd value.\n'''\n\nimport random\ndef main():\n a_list = []\n for index in range(10):\n a_list = a_list + [random.randrange(1, 100)]\n print(\"1.\", a_list)\n\n for index in range(len(a_list)):\n if a_list[index] % 2 == 1:\n a_list[index]= a_list[index] + 1\n print(\"2.\", a_list)\n\nmain()\n","repo_name":"TanyaMozoleva/python_practice","sub_path":"Lectures/Lec15/p8.py","file_name":"p8.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"26898067115","text":"'''\n-Medium-\n\n*Topological Sort*\n\nThere are N courses, labelled from 1 to N.\n\nWe are given relations[i] = [X, Y], representing a prerequisite relationship between \ncourse X and course Y: course X has to be studied before course Y.\n\nIn one semester you can study any number of courses as long as you have studied all the \nprerequisites for the course you are studying.\n\nReturn the minimum number of semesters needed to study all courses. If there is no way \nto study all the courses, return -1.\n\nExample 1:\n\nInput: N = 3, relations = [[1,3],[2,3]]\nOutput: 2\nExplanation: \nIn the first semester, courses 1 and 2 are studied. In the second semester, course 3 is studied.\nExample 2:\n\nInput: N = 3, relations = [[1,2],[2,3],[3,1]]\nOutput: -1\nExplanation: \nNo course can be studied because they depend on each other.\nNote:\n\n1 <= N <= 5000\n1 <= relations.length <= 5000\nrelations[i][0] != relations[i][1]\nThere are no repeated relations in the input.\n\n'''\nfrom collections import deque, defaultdict\n\nclass Solution(object):\n\n def minNumberOfSemesters(self, n, dependencies):\n indeg = [0] * (n+1)\n m = defaultdict(list)\n q = deque()\n for x,y in dependencies:\n indeg[y] += 1\n m[x].append(y)\n for i in range(1, n+1):\n if indeg[i] == 0:\n q.append(i)\n ans = 0\n while q:\n nxt = deque()\n while q:\n course = q.popleft()\n n -= 1\n for i in m[course]:\n indeg[i] -= 1\n if indeg[i] == 0:\n nxt.append(i)\n q = nxt\n ans += 1\n return ans if n == 0 else -1\n\nif __name__ == \"__main__\":\n print(Solution().minNumberOfSemesters(3, [[1,3],[2,3]]))\n print(Solution().minNumberOfSemesters(3, [[1,2],[2,3],[3,1]]))\n\n\n","repo_name":"bssrdf/pyleet","sub_path":"P/ParallelCourses.py","file_name":"ParallelCourses.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"38952121054","text":"# -*- coding: utf-8 -*-\nfrom nbautoeval.exercise_function import ExerciseFunction\nfrom nbautoeval.args import Args\n\ndef add(x,y):\n z = x+y\n return z\n\ninputs_add = [\n Args(1,1), Args(2,2), Args(3,3), Args(4,4), Args(5,5), Args(6,6) \n]\n\nexo_add = ExerciseFunction(\n add,\n inputs_add,\n layout='pprint',\n layout_args=(40, 40, 40),\n)\n","repo_name":"Fifi31-1964/NSI-ESSAI","sub_path":"exos/corrections.py","file_name":"corrections.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"41245841088","text":"\ndef insertionSort(arr):\n for i in range(1, len(arr)):\n preIndex = i-1\n for j in range(preIndex, -1, -1):\n if arr[j+1] < arr[j]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\n\n\ndef bubbleSort(arr):\n for i in range(len(arr)-1):\n for j in range(len(arr)-i-1):\n if arr[j+1] < arr[j]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr\n\n\ndef main():\n arr = [10, 7, 8, 9, 1, 5, 101, 77, 99, 56]\n n = len(arr)\n # arr = insertionSort(arr)\n arr = bubbleSort(arr)\n for i in range(n):\n print(\"%d\" % arr[i])\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chihta-chou/Base_Algorithm","sub_path":"Sort_Collection/insert_sort.py","file_name":"insert_sort.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"6755083501","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nInterface to project settings from dr2xml\n\"\"\"\nfrom __future__ import print_function, division, absolute_import, unicode_literals\n\nimport os\nfrom importlib.machinery import SourceFileLoader\n\nfrom .py_settings_interface import get_variable_from_lset_with_default_in_lset, get_variable_from_lset_with_default\nfrom dr2xml.projects.projects_interface_definitions import ParameterSettings\n\n\ndef initialize_project_settings():\n # Read content from json file\n project_filename = get_variable_from_lset_with_default_in_lset(key=\"project_settings\", key_default=\"project\",\n default=\"CMIP6\")\n # Merge with parent if needed\n project_filename, internal_values, common_values, project_settings = merge_project_settings(project_filename)\n # If asked, save the settings into a dedicated file\n save_project_settings = get_variable_from_lset_with_default(\"save_project_settings\", None)\n if save_project_settings is not None:\n write_project_content(save_project_settings, internal_values, common_values, project_settings)\n return internal_values, common_values, project_settings\n\n\ndef write_project_content(target, internal_values, common_values, project_settings):\n print(\"Writing project content is not yet implemented\")\n pass\n\n\ndef merge_project_settings(project_filename):\n # Initialize settings from current filename\n project_filename, parent_project_filename, internal_values, common_values, project_settings = \\\n read_project_settings(filename=project_filename)\n if parent_project_filename is not None:\n # Merge parent settings\n parent_project_filename, parent_internal_values, parent_common_values, parent_project_settings = \\\n merge_project_settings(project_filename=parent_project_filename)\n if project_filename != parent_project_filename:\n internal_values = update_settings(internal_values, parent_internal_values)\n common_values = update_settings(common_values, parent_common_values)\n project_settings = update_settings(project_settings, parent_project_settings)\n else:\n raise ValueError(\"The settings %s reference itself as parent settings. Stop\" % project_filename)\n return project_filename, internal_values, common_values, project_settings\n\n\ndef update_settings(current_settings, parent_settings):\n for value in current_settings:\n if value in parent_settings:\n parent_settings[value].update(current_settings[value])\n else:\n parent_settings[value] = current_settings[value]\n return parent_settings\n\n\ndef read_project_settings(filename):\n if not os.path.isfile(filename):\n filename = os.sep.join([os.path.dirname(os.path.abspath(__file__)), \"..\", \"projects\",\n \"{}.py\".format(filename)])\n file_module = SourceFileLoader(os.path.basename(filename), filename).load_module(os.path.basename(filename))\n if \"parent_project_settings\" in file_module.__dict__:\n parent_project_filename = file_module.__getattribute__(\"parent_project_settings\")\n else:\n parent_project_filename = None\n if \"internal_values\" in file_module.__dict__:\n internal_values = file_module.__getattribute__(\"internal_values\")\n else:\n internal_values = dict()\n if \"common_values\" in file_module.__dict__:\n common_values = file_module.__getattribute__(\"common_values\")\n else:\n common_values = dict()\n if \"project_settings\" in file_module.__dict__:\n project_settings = file_module.__getattribute__(\"project_settings\")\n else:\n project_settings = dict()\n return filename, parent_project_filename, internal_values, common_values, project_settings\n\n\ndef solve_values(values, internal_dict=dict(), common_dict=dict(), additional_dict=dict(),\n allow_additional_keytypes=True):\n if values in [\"internal\", ]:\n args_dict = dict(common_dict=common_dict, additional_dict=additional_dict, raise_on_error=False,\n allow_additional_keytypes=allow_additional_keytypes)\n dict_name = \"internal_dict\"\n current_dict = internal_dict\n elif values in [\"common\", ]:\n args_dict = dict(internal_dict=internal_dict, additional_dict=additional_dict, raise_on_error=False,\n allow_additional_keytypes=allow_additional_keytypes)\n dict_name = \"common_dict\"\n current_dict = common_dict\n else:\n raise ValueError(\"Could not solve values for setting %s\" % values)\n rep = dict()\n items_to_treat = sorted(list(current_dict))\n test = True\n while len(items_to_treat) > 0 and test:\n for item in items_to_treat:\n val = current_dict[item]\n if isinstance(val, ParameterSettings):\n found, value = val.find_value(**{dict_name: rep}, **args_dict)\n if found:\n rep[item] = value\n del current_dict[item]\n else:\n raise TypeError(\"Can only treat ParameterSettings type objects, not %s.\" % type(val))\n test = len(current_dict) < len(items_to_treat)\n items_to_treat = sorted(list(current_dict))\n if not test:\n for item in items_to_treat:\n if not current_dict[item].fatal:\n del current_dict[item]\n items_to_treat = sorted(list(current_dict))\n test = len(items_to_treat) == 0\n if not test:\n raise ValueError(\"Could not evaluate all %s values: the following are missing %s\" % (values, items_to_treat))\n return rep\n\n\ndef solve_settings(settings, internal_dict=dict(), common_dict=dict(), additional_dict=dict(),\n allow_additional_keytypes=True):\n for tag in settings:\n settings[tag].complete_and_clean()\n return settings\n","repo_name":"rigoudyg/dr2xml","sub_path":"dr2xml/settings_interface/py_project_interface.py","file_name":"py_project_interface.py","file_ext":"py","file_size_in_byte":5905,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"1705396587","text":"# Programa BUGADO. Só funciona com a gambiarra do 9999999999\r\n\r\nprint('Cálculo de compra\\n')\r\n\r\nmais_de_mil = 0\r\ntotal = 0\r\npreco_prod = 0\r\nmenor = 999999999\r\n\"\"\"cont = 0\"\"\"\r\nmais_bar = ''\r\n\r\nwhile True:\r\n nome_prod = str(input('Digite o nome do produto: '))\r\n preco_prod = float(input('Digite o preço do produto: R$'))\r\n \"\"\"cont = cont + 1\"\"\"\r\n total = total + preco_prod\r\n\r\n \"\"\"if cont == 1 or preco_prod < menor:\r\n menor = preco_prod\r\n mais_bar = nome_prod\"\"\"\r\n if preco_prod < menor:\r\n menor = preco_prod\r\n mais_bar = nome_prod\r\n if preco_prod > 1000:\r\n mais_de_mil = mais_de_mil + 1\r\n cont = str(input('Queres continuar? (S/N) ')).strip().upper()[0]\r\n while cont not in 'SN ':\r\n cont = str(input('Queres continuar? (S/N)')).strip().upper()[0]\r\n if cont == 'N':\r\n print(f'O total foi R${total:.2f}')\r\n print(f'{mais_de_mil} produtos custaram mais de 1000 reias')\r\n print(f'O produto mais barato foi o {mais_bar}')\r\n break\r\n else:\r\n continue\r\nprint('{:-^40}'.format(' FIM DO PROGRAMA '))","repo_name":"IsmaelBortoluzzi/Curso-Python-Do-Guanabara","sub_path":"cursoemvideo/desaf070.py","file_name":"desaf070.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"12885090382","text":"from torch import nn\nfrom torchvision.models.video.resnet import (BasicBlock,R2Plus1dStem,Conv2Plus1D,Bottleneck)\n\nclass VideoResNet(nn.Module):\n\n def __init__(self,pool_type,\n zero_init_residual=False):\n \"\"\"Generic resnet video generator.\n\n Args:\n block (nn.Module): resnet building block\n conv_makers (list(functions)): generator function for each layer\n layers (List[int]): number of blocks per layer\n stem (nn.Module, optional): Resnet stem, if None, defaults to conv-bn-relu. Defaults to None.\n num_classes (int, optional): Dimension of the final FC layer. Defaults to 400.\n zero_init_residual (bool, optional): Zero init bottleneck residual BN. Defaults to False.\n \"\"\"\n super(VideoResNet, self).__init__()\n block = BasicBlock\n conv_makers = [Conv2Plus1D] * 5\n layers = [2, 2, 2, 2, 2]\n stem = R2Plus1dStem\n self.inplanes = 64\n\n self.stem = stem()\n\n self.layer1 = self._make_layer(block, conv_makers[0], 64, layers[0], stride=1)\n self.layer2 = self._make_layer(block, conv_makers[1], 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, conv_makers[2], 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, conv_makers[3], 512, layers[3], stride=2)\n self.adp_pool=pool_type\n\n # init weights\n\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n\n def forward(self, inp):\n x = self.stem(inp)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n x = self.adp_pool(x)\n x = x.flatten(1)\n return x\n\n def _make_layer(self, block, conv_builder, planes, blocks, stride=1):\n downsample = None\n\n if stride != 1 or self.inplanes != planes * block.expansion:\n ds_stride = conv_builder.get_downsample_stride(stride)\n downsample = nn.Sequential(\n nn.Conv3d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=ds_stride, bias=False),\n nn.BatchNorm3d(planes * block.expansion)\n )\n layers = []\n layers.append(block(self.inplanes, planes, conv_builder, stride, downsample))\n\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes, conv_builder))\n\n return nn.Sequential(*layers)\n\n\n\n","repo_name":"Seleucia/goca","sub_path":"my_models/my_r2plus1d_18.py","file_name":"my_r2plus1d_18.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"46"} +{"seq_id":"12638008586","text":"import statsmodels\nimport survivalstan\nimport random\nrandom.seed(9001)\n\ndef load_test_dataset(n=50):\n ''' Load test dataset from R survival package\n '''\n dataset = statsmodels.datasets.get_rdataset(package='survival', dataname='flchain' )\n d = dataset.data.query('futime > 7').sample(n=n)\n d.reset_index(level=0, inplace=True)\n d.rename(columns={'futime': 't', 'death': 'event'}, inplace=True)\n return(d)\n\n\ndef sim_test_dataset(n=50):\n dataset = survivalstan.sim.sim_data_exp_correlated(N=n, censor_time=10)\n return(dataset)\n\n\ndef load_test_dataset_long(n=20):\n ''' Load test dataset from R survival package\n '''\n d = load_test_dataset(n=n)\n dlong = survivalstan.prep_data_long_surv(d, time_col='t', event_col='event')\n return dlong\n\ndef sim_test_dataset_long(n=20):\n d = sim_test_dataset(n=n)\n dlong = survivalstan.prep_data_long_surv(d, time_col='t', event_col='event')\n return dlong\n","repo_name":"hammerlab/survivalstan","sub_path":"test/test_datasets.py","file_name":"test_datasets.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"46"} +{"seq_id":"74816235338","text":"import json\nimport os\n\nimport torch\nimport torch.nn\nimport torch.optim\n\nimport src.utils as utils\nfrom common_constants import EXPERIMENTS_ROOT\nfrom metrics import create_all_metrics\nfrom predict import create_predictions\nfrom src.trainable import Trainable\nfrom src.utils import build_attr, build_model_from_args\n\n\ndef build_and_train_model(model_starter_file=False):\n \"\"\" This is the main training function that constructs the model and trains\n it on the chosen dataset.\n \"\"\"\n # Instantiate the trainable object\n try:\n trainable = build_trainable_from_args(\n args.data_dir,\n args.model,\n args.optimizer,\n args.criterion,\n args.lr_scheduler,\n args.batch_size,\n outdir,\n )\n # load in existing weights if requested\n if model_starter_file:\n trainable.load_model_weights(model_starter_file)\n except TypeError as e:\n print(\n \"Caught TypeError when instantiating trainable. Make sure \"\n + \"all required arguments are passed.\\n\"\n )\n raise e\n\n # Make results dir path. Check if it already exists.\n try:\n os.makedirs(outdir, exist_ok=args.overwrite)\n except OSError:\n can_continue = input(\n f'The directory \"{outdir}\" already exists. '\n + \"Do you wish to continue anyway? (y/N): \"\n )\n if can_continue and can_continue.lower()[0] == \"y\":\n os.makedirs(outdir, exist_ok=True)\n else:\n exit()\n print(f'Writing results to \"{outdir}\"')\n\n # Train\n trainable.train(args.num_epochs)\n trainable.save(extra_meta=vars(args))\n return trainable\n\n\ndef build_trainable_from_args(\n datadir,\n model_args,\n optim_args,\n criterion_args,\n lr_scheduler_args,\n batch_size,\n outdir,\n):\n \"\"\"Builds a Trainable from command line args\n\n Arguments:\n datadir {[type]} -- [description]\n model_args {[type]} -- [description]\n optim_args {[type]} -- [description]\n criterion_args {[type]} -- [description]\n lr_scheduler_args {[type]} -- [description]\n\n Returns:\n [type] -- [description]\n \"\"\"\n\n # set the num_classes arg\n # model_args.append(f'num_classes={num_classes}')\n model_name, _ = utils.args_to_name_and_kwargs(model_args)\n image_size = utils.determine_image_size(model_name)\n dataloaders = utils.get_train_val_dataloaders(\n datadir, 0.15, image_size, args.batch_size\n )\n\n model = build_model_from_args(args.model)\n model = utils.fit_model_last_to_dataset(model, dataloaders[\"train\"].dataset)\n\n optimizer = build_attr(torch.optim, optim_args, first_arg=model.parameters())\n criterion = build_attr(torch.nn, criterion_args)\n lr_scheduler = build_attr(\n torch.optim.lr_scheduler, lr_scheduler_args, first_arg=optimizer\n )\n\n trainable = Trainable(\n dataloaders, model, criterion, optimizer, lr_scheduler, outdir\n )\n return trainable\n\n\ndef load_args(args):\n # if the user passed in a directory, assume they meant \"meta.json\"\n if os.path.isdir(args.load_args):\n load_args_file = os.path.join(args.load_args, \"meta.json\")\n elif os.path.isfile(args.load_args):\n load_args_file = args.load_args\n\n with open(load_args_file, \"r\") as f:\n loaded = json.load(f)\n # only load intersecting arguments, in case the load file has extraneous\n # information\n intersected_keys = set(vars(args).keys()) & set(loaded.keys())\n load_args_dict = {k: loaded[k] for k in intersected_keys}\n print(\"Loaded args:\")\n # for each arg in argparse, check if any were not set by the user\n for common_arg, load_value in load_args_dict.items():\n # if the user did not set the argument, load it\n if not getattr(args, common_arg):\n setattr(args, common_arg, load_value)\n print(f\" {common_arg}: {load_value}\")\n print()\n\n\nif __name__ == \"__main__\":\n from train_args import train_args\n\n global args\n args = train_args\n print()\n print(f'*** BEGINNING EXPERIMENT: \"{args.experiment_name}\" ***', end=\"\\n\\n\")\n\n # load args from a previous train session if requested\n if args.load_args:\n load_args(args)\n\n # get rid of the extra slash if the user put one\n if args.data_dir[-1] == \"/\" or args.data_dir[-1] == \"\\\\\":\n args.data_dir = args.data_dir[:-1]\n dataset_name = os.path.basename(args.data_dir)\n # Make the output directory for the experiment\n global outdir\n outdir = os.path.join(\n EXPERIMENTS_ROOT, args.experiment_name, dataset_name, args.model[0]\n )\n\n if args.use_previous_model:\n prev_model_file = os.path.join(args.load_args, \"model.pth\")\n print(\"Loading previous model from \", prev_model_file)\n else:\n prev_model_file = False\n\n # run the main training script\n trainable = build_and_train_model(prev_model_file)\n\n # calculate performance metrics with the saved model\n # print('skip_metrics: ', args.skip_metrics)\n if not args.skip_metrics:\n print()\n print(\"Creating predictions file...\")\n predictions_file = create_predictions(\n outdir, subset=\"test\", data_dir=args.data_dir, model=trainable.model\n )\n print(\"Calculating performance metrics...\")\n create_all_metrics(predictions_file, outdir, prefix=\"test\")\n else:\n print(\"Skipping metrics.\")\n\n print()\n print(\"Done.\")\n","repo_name":"andrewjong/Estrous-AI","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"26945109833","text":"from moviebot.nlu.text_processing import Tokenizer\n\nimport pytest\n\n\n@pytest.mark.parametrize('utterance, expected', [\n ('Hello WoRld', ['hello', 'world']),\n ('document.with, punctuation: with?spaces\\ttabs\\nwith newlines\\n\\n\\n',\n ['document', 'punctuation', 'space', 'tab', 'newlines']),\n])\ndef test_process_text(utterance, expected):\n # Setup\n tp = Tokenizer()\n\n # Exercise\n result = tp.process_text(utterance)\n\n # Results\n assert result == expected\n\n # Cleanup - none","repo_name":"fseimb/moviebot-1","sub_path":"tests/nlu/test_text_processing.py","file_name":"test_text_processing.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"46"} +{"seq_id":"73175177740","text":"'''\n Run from LABFNS1 with: python3 -m Python.src.Comparisons\n'''\n\nimport pandas as pd\nimport numpy as np\nimport sys \n\nfrom ROOT import TH1D, TH2D, gStyle, gPad, TFile, TCanvas, TLegend, TLatex, TF1, TLine, TText\nfrom ROOT import kOrange, kGray, kAzure, kRed, kGreen, kBlue, kBlack\nimport uproot\n\nfrom Python.utils.StyleFormatter import SetGlobalStyle, SetObjectStyle\n#SetGlobalStyle(padleftmargin=5., padbottommargin=0.12, padrightmargin=0.5, padtopmargin=0.1, titleoffsety=1.1, titleoffsetx=0.9, titleoffset= 0.7, opttitle=1)\ngStyle.SetOptStat(0)\n\n# Data visualization\n\ndef PatternUnitSelection(df, dfPU, outputFile):\n '''\n Create histograms to compare data with and without selections with Pattern Unit\n '''\n\n # CHANNEL 10 (i.e. S1)\n canvas10 = TCanvas('adc_PU_comp_ch10', '', 1500, 1500)\n\n ADChist10 = TH1D('ADChist10', '', 235, 0, 2048)\n ADChist10.SetLineColor(kGray+2)\n ADChist10.SetFillColorAlpha(kGray+2, 0.5)\n ADChist10.SetTitle('ADC data with pattern unit selections (S1); Energy (chn); Counts (a.u.)')\n for x in df['2249W_-_adc__ch10']: ADChist10.Fill(x)\n\n ADChistPU10 = TH1D('ADChistPU10', '', 235, 0, 2048)\n ADChistPU10.SetLineColor(kOrange-3)\n ADChistPU10.SetFillColorAlpha(kOrange-3, 0.5)\n ADChistPU10.SetTitle('ADC data with pattern unit selections (S1); Energy (chn); Counts (a.u.)')\n for x in dfPU['2249W_-_adc__ch10']: ADChistPU10.Fill(x)\n\n leg1 = TLegend(0.55, 0.4, 0.75, 0.7)\n leg1.SetTextFont(42)\n leg1.SetTextSize(gStyle.GetTextSize()*0.7)\n leg1.SetFillStyle(0)\n leg1.SetBorderSize(0)\n leg1.AddEntry(ADChist10, 'All events', 'lf')\n leg1.AddEntry(ADChistPU10, 'Events selected by the pattern unit', 'lf')\n\n canvas10.cd()\n ADChist10.Draw('hist')\n ADChistPU10.Draw('hist same')\n leg1.Draw('same')\n #canvas.DrawFrame(0, 0, 2048, 1000, 'ADC data with pattern unit selections (S1); Energy (chn); Counts (a.u.)')\n\n outputFile.cd()\n ADChist10.Write()\n ADChistPU10.Write()\n canvas10.Write()\n canvas10.SaveAs('data/output/ComparisonADCpuS1.pdf')\n\n # CHANNEL 11 (i.e. SG)\n canvas11 = TCanvas('adc_PU_comp_ch11', '', 1500, 1500)\n\n ADChist11 = TH1D('ADChist11', '', 235, 0, 2048)\n ADChist11.SetLineColor(kGray+2)\n ADChist11.SetFillColorAlpha(kGray+2, 0.5)\n ADChist11.SetTitle('ADC data with pattern unit selections (SG); Energy (chn); Counts (a.u.)')\n for x in df['2249W_-_adc__ch11']: ADChist11.Fill(x)\n\n ADChistPU11 = TH1D('ADChistPU11', '', 235, 0, 2048)\n ADChistPU11.SetLineColor(kOrange-3)\n ADChistPU11.SetFillColorAlpha(kOrange-3, 0.5)\n ADChistPU11.SetTitle('ADC data with pattern unit selections (SG); Energy (chn); Counts (a.u.)')\n for x in dfPU['2249W_-_adc__ch11']: ADChistPU11.Fill(x)\n\n leg1 = TLegend(0.55, 0.4, 0.75, 0.7)\n leg1.SetTextFont(42)\n leg1.SetTextSize(gStyle.GetTextSize()*0.7)\n leg1.SetFillStyle(0)\n leg1.SetBorderSize(0)\n leg1.AddEntry(ADChist11, 'All events', 'lf')\n leg1.AddEntry(ADChistPU11, 'Events selected by the pattern unit', 'lf')\n\n canvas11.cd()\n ADChist11.Draw('hist')\n ADChistPU11.Draw('hist same')\n leg1.Draw('same')\n #canvas.DrawFrame(0, 0, 2048, 1100, 'ADC data with pattern unit selections (S1); Energy (chn); Counts (a.u.)')\n\n outputFile.cd()\n ADChist11.Write()\n ADChistPU11.Write()\n canvas11.Write()\n canvas11.SaveAs('data/output/ComparisonADCpuSG.pdf')\n\ndef secondPeakSelection(df, outputFile):\n\n # CHANNEL 10 (i.e. S1)\n dfSel = df.query('`2249W_-_adc__ch10` > 340', inplace=False)\n canvas10 = TCanvas('adc_PeakSel_ch10', '', 1500, 1500)\n\n ADChist10 = TH1D('ADChist10', '', 256, 0, 2048)\n ADChist10.SetLineColor(kGray+2)\n ADChist10.SetFillColorAlpha(kGray+2, 0.5)\n ADChist10.SetTitle('ADC data with peak selections (S1); Energy (chn); Counts (a.u.)')\n for x in df['2249W_-_adc__ch10']: ADChist10.Fill(x)\n\n ADChistSel10 = TH1D('ADChistSel10', '', 256, 0, 2048)\n ADChistSel10.SetLineColor(kGreen-3)\n ADChistSel10.SetFillColorAlpha(kGreen-3, 0.3)\n ADChistSel10.SetTitle('ADC data with peak selections (S1); Energy (chn); Counts (a.u.)')\n for x in dfSel['2249W_-_adc__ch10']: ADChistSel10.Fill(x)\n\n leg1 = TLegend(0.55, 0.4, 0.75, 0.7)\n leg1.SetTextFont(42)\n leg1.SetTextSize(gStyle.GetTextSize()*0.7)\n leg1.SetFillStyle(0)\n leg1.SetBorderSize(0)\n leg1.AddEntry(ADChist10, 'All events', 'lf')\n leg1.AddEntry(ADChistSel10, 'Events with energy > 340 chn', 'lf')\n\n lineAtPedestal = TLine(320, gPad.GetUymax(), 320, gPad.GetUymin())\n lineAtPedestal.SetLineColor(kBlack)\n lineAtPedestal.SetLineWidth(2)\n lineAtPedestal.SetLineStyle(7)\n\n pedestal= TText(0.24,0.7,\"Pedestal\")\n pedestal.SetNDC()\n pedestal.SetTextSize(gStyle.GetTextSize()*0.7)\n pedestal.SetTextAngle(90)\n pedestal.SetTextFont(42)\n\n canvas10.cd()\n ADChist10.Draw('hist')\n ADChistSel10.Draw('hist same')\n leg1.Draw('same')\n lineAtPedestal.Draw('same')\n pedestal.Draw('same')\n\n outputFile.cd()\n canvas10.Write()\n canvas10.SaveAs('data/output/ComparisonADCpeakS1.pdf')\n\n # TH2\n\n canvas20 = TCanvas('th2_PeakSel_ch10', '', 1500, 1500)\n\n hist10 = TH2D('hist10', '', 125, 0, 5000, 256, 0, 2048)\n for x, y in zip(df['tdc_ns'], df['2249W_-_adc__ch10']): hist10.Fill(x, y)\n hist10.SetTitle('ADC and TDC data with peak selections (S1); Time (ns); Energy (chn)')\n hist10.SetMarkerStyle(3)\n hist10.SetMarkerColor(kGray+2)\n\n hist10Sel = TH2D('hist10Sel', '', 125, 0, 5000, 256, 0, 2048)\n for x, y in zip(dfSel['tdc_ns'], dfSel['2249W_-_adc__ch10']): hist10Sel.Fill(x, y)\n hist10Sel.SetTitle('ADC and TDC data with peak selections (S1); Time (ns); Energy (chn)')\n hist10Sel.SetMarkerStyle(3)\n hist10Sel.SetMarkerColor(kGreen-3)\n\n leg1 = TLegend(0.55, 0.7, 0.75, 0.8)\n leg1.SetTextFont(42)\n leg1.SetTextSize(gStyle.GetTextSize()*0.7)\n leg1.SetFillStyle(0)\n leg1.SetBorderSize(0)\n leg1.AddEntry(hist10, 'All events', 'pf')\n leg1.AddEntry(hist10Sel, 'Events with energy > 340 chn', 'pf')\n\n lineAtPedestal = TLine(canvas20.GetUxmax(), 320, canvas20.GetUxmin(), 320)\n lineAtPedestal.SetLineColor(kBlack)\n lineAtPedestal.SetLineWidth(1)\n lineAtPedestal.SetLineStyle(7)\n\n pedestal= TText(0.7,0.21,\"Pedestal\")\n pedestal.SetNDC()\n pedestal.SetTextSize(gStyle.GetTextSize()*0.7)\n pedestal.SetTextFont(42)\n\n canvas20.cd()\n hist10.Draw('scat')\n hist10Sel.Draw('scat same')\n leg1.Draw('same')\n\n outputFile.cd()\n canvas20.Write()\n canvas20.SaveAs('data/output/ComparisonTH2peakS1.pdf')\n\n\n\n\n # CHANNEL 11 (i.e. S1)\n dfSel = df.query('`2249W_-_adc__ch11` > 584', inplace=False)\n canvas11 = TCanvas('adc_PeakSel_ch11', '', 1500, 1500)\n\n ADChist11 = TH1D('ADChist11', '', 256, 0, 2048)\n ADChist11.SetLineColor(kGray+2)\n ADChist11.SetFillColorAlpha(kGray+2, 0.5)\n ADChist11.SetTitle('ADC data with peak selections (SG); Energy (chn); Counts (a.u.)')\n for x in df['2249W_-_adc__ch11']: ADChist11.Fill(x)\n\n ADChistSel11 = TH1D('ADChistSel11', '', 256, 0, 2048)\n ADChistSel11.SetLineColor(kGreen-3)\n ADChistSel11.SetFillColorAlpha(kGreen-3, 0.3)\n ADChistSel11.SetTitle('ADC data with peak selections (SG); Energy (chn); Counts (a.u.)')\n for x in dfSel['2249W_-_adc__ch11']: ADChistSel11.Fill(x)\n\n leg1 = TLegend(0.55, 0.4, 0.75, 0.7)\n leg1.SetTextFont(42)\n leg1.SetTextSize(gStyle.GetTextSize()*0.7)\n leg1.SetFillStyle(0)\n leg1.SetBorderSize(0)\n leg1.AddEntry(ADChist11, 'All events', 'lf')\n leg1.AddEntry(ADChistSel11, 'Events with energy > 584 chn', 'lf')\n\n lineAtPedestal = TLine(320, gPad.GetUymax(), 320, gPad.GetUymin())\n lineAtPedestal.SetLineColor(kBlack)\n lineAtPedestal.SetLineWidth(1)\n lineAtPedestal.SetLineStyle(7)\n\n pedestal= TText(0.24,0.7,\"Pedestal\")\n pedestal.SetNDC()\n pedestal.SetTextSize(gStyle.GetTextSize()*0.7)\n pedestal.SetTextAngle(90)\n pedestal.SetTextFont(42)\n\n canvas11.cd()\n ADChist11.Draw('hist')\n ADChistSel11.Draw('hist same')\n leg1.Draw('same')\n lineAtPedestal.Draw()\n pedestal.Draw('same')\n\n outputFile.cd()\n canvas11.Write()\n canvas11.SaveAs('data/output/ComparisonADCpeakSG.pdf')\n\n # TH2\n\n canvas21 = TCanvas('th2_PeakSel_ch11', '', 1500, 1500)\n\n hist11 = TH2D('hist11', '', 125, 0, 5000, 256, 0, 2048)\n for x, y in zip(df['tdc_ns'], df['2249W_-_adc__ch11']): hist11.Fill(x, y)\n hist11.SetTitle('ADC and TDC data with peak selections (SG); Time (ns); Energy (chn)')\n hist11.SetMarkerStyle(3)\n hist11.SetMarkerColor(kGray+2)\n\n hist11Sel = TH2D('hist11Sel', '', 125, 0, 5000, 256, 0, 2048)\n for x, y in zip(dfSel['tdc_ns'], dfSel['2249W_-_adc__ch11']): hist11Sel.Fill(x, y)\n hist11Sel.SetTitle('ADC and TDC data with peak selections (SG); Time (ns); Energy (chn)')\n hist11Sel.SetMarkerStyle(3)\n hist11Sel.SetMarkerColor(kGreen-3)\n\n leg1 = TLegend(0.55, 0.7, 0.75, 0.8)\n leg1.SetTextFont(42)\n leg1.SetTextSize(gStyle.GetTextSize()*0.7)\n leg1.SetFillStyle(0)\n leg1.SetBorderSize(0)\n leg1.AddEntry(hist11, 'All events', 'pf')\n leg1.AddEntry(hist11Sel, 'Events with energy > 584 chn', 'pf')\n\n lineAtPedestal = TLine(gPad.GetUxmax(), 320, gPad.GetUxmin(), 320)\n lineAtPedestal.SetLineColor(kBlack)\n lineAtPedestal.SetLineWidth(1)\n lineAtPedestal.SetLineStyle(7)\n\n pedestal = TText(0.7,0.21,\"Pedestal\")\n pedestal.SetNDC()\n pedestal.SetTextSize(gStyle.GetTextSize()*0.7)\n pedestal.SetTextFont(42)\n\n canvas21.cd()\n hist11.Draw('scat')\n hist11Sel.Draw('scat same')\n leg1.Draw('same')\n lineAtPedestal.Draw()\n pedestal.Draw('same')\n\n outputFile.cd()\n canvas21.Write()\n canvas21.SaveAs('data/output/ComparisonTH2peakSG.pdf')\n\ndef TDCwithSelection(df, outputFile):\n \n dfSel = df.query('`2249W_-_adc__ch10` > 340 and `2249W_-_adc__ch11` > 584', inplace=False)\n dfDisc = df.query('`2249W_-_adc__ch10` < 340 or `2249W_-_adc__ch11` < 584', inplace=False)\n\n # Discarded events\n canvas = TCanvas('adc_PeakSel_ch11', '', 1500, 1500)\n canvas.SetLogy()\n\n TDChist = TH1D('TDChist', '', 125, 0, 5000)\n TDChist.SetLineColor(kGray+2)\n TDChist.SetFillColorAlpha(kGray+2, 0.5)\n TDChist.SetTitle('TDC data with discarded events; Time (ns); Counts (a.u.)')\n for x in df['tdc_ns']: TDChist.Fill(x)\n\n TDChistDisc = TH1D('TDChistDisc', '', 125, 0, 5000)\n TDChistDisc.SetLineColor(kRed-3)\n TDChistDisc.SetFillColorAlpha(kRed-3, 0.3)\n TDChistDisc.SetTitle('TDC data with discarded events; Time (ns); Counts (a.u.)')\n for x in dfDisc['tdc_ns']: TDChistDisc.Fill(x)\n\n leg1 = TLegend(0.55, 0.4, 0.75, 0.7)\n leg1.SetTextFont(42)\n leg1.SetTextSize(gStyle.GetTextSize()*0.7)\n leg1.SetFillStyle(0)\n leg1.SetBorderSize(0)\n leg1.AddEntry(TDChist, 'All events', 'lf')\n leg1.AddEntry(TDChistDisc, 'Discarded events', 'lf')\n\n canvas.cd()\n TDChist.Draw('hist')\n TDChistDisc.Draw('hist same')\n leg1.Draw('same')\n\n outputFile.cd()\n canvas.Write()\n canvas.SaveAs('data/output/ComparisonTDCdiscards.pdf')\n\n\n # FIT\n\n cS1 = TCanvas(\"cS1\",\"cS1\",1500,1500)\n cS1.cd()\n cS1.SetLogy()\n\n hTDC = TH1D(\"hTDC\",\"hTDC\",125,0,5000)\n for x in dfSel[\"tdc_ns\"]: hTDC.Fill(x)\n hTDC.SetFillColorAlpha(kOrange-3, 0.5)\n\n funz = TF1(\"funz\",\"[0]+[1]*exp(x*[2])\",20,800)\n funz1 = TF1(\"funz1\",\"[0]+[1]*exp(x*[2])\",2000,5000)\n funz2 = TF1(\"funz2\",\"[0]+[1]*exp(x*[2])+[3]*exp(x*[4])\",300, 800)\n\n funz1.SetParameter(0,0)\n funz1.SetParLimits(0, 0, 1e6)\n funz1.SetParameter(1, 68)\n funz1.SetParameter(2, -0.00045)\n hTDC.Fit(funz1,\"RM+\")\n print('Chi square fit 1 / DoF = ', funz1.GetChisquare(), '/', funz1.GetNDF())\n\n funz2.SetParameter(0, funz1.GetParameter(0))\n funz2.SetParLimits(0, 0, 1e6)\n funz2.SetParameter(1, funz1.GetParameter(1))\n funz2.SetParLimits(1, 0, 1e6)\n funz2.SetParameter(2, funz1.GetParameter(2))\n funz2.SetParLimits(2, -0.0007, -0.0003)\n funz2.SetParameter(3, 1.7e4)\n funz2.SetParLimits(3, 0, 1e6)\n funz2.SetParameter(4, -0.009)\n funz2.SetParLimits(4, -0.011, -0.007)\n hTDC.Fit(funz2,\"RM+\")\n print('Chi square fit 2 / DoF = ', funz2.GetChisquare(), '/', funz2.GetNDF())\n\n funz.SetLineColor(kBlue)\n funz1.SetLineColor(kRed)\n funz2.SetLineColor(kGreen)\n\n hTDC.Draw(\"hist e0\")\n funz1.Draw('same')\n funz2.Draw('same')\n\n hTDC.SetTitle(\"TDC intervals with ADC selections; Time (ns); Counts (a.u)\")\n\n text =TLatex(0.30, 0.7,\"TDC LeCroy 2228A\")\n text.SetNDC()\n text.SetTextSize(gStyle.GetTextSize())\n text.SetTextFont(42)\n text.Draw()\n text2 =TLatex(0.30, 0.62,\"ADC selections\")\n text2.SetNDC()\n text2.SetTextSize(gStyle.GetTextSize()*0.7)\n text2.SetTextFont(42)\n text2.Draw()\n text3 =TLatex(0.30, 0.56,\"Acquisition time: 236985 s\")\n text3.SetNDC()\n text3.SetTextSize(gStyle.GetTextSize()*0.7)\n text3.SetTextFont(42)\n text3.Draw()\n text4 =TLatex(0.30, 0.48,\"Fake stop time: 6 #mus\")\n text4.SetNDC()\n text4.SetTextSize(gStyle.GetTextSize()*0.7)\n text4.SetTextFont(42)\n text4.Draw()\n\n leg = TLegend(0.55, 0.51, 0.85, 0.72)\n leg.SetTextFont(42)\n leg.SetBorderSize(0)\n leg.SetTextSize(gStyle.GetTextSize()*0.7)\n leg.SetFillStyle(0)\n\n leg.AddEntry(hTDC, 'TDC_data', 'lf')\n leg.AddEntry(funz1, 'N_{0} + c_{1} e^{-#lambda_{dec} t}', 'lf')\n leg.AddEntry(funz2, 'N_{0} + c_{1} e^{-#lambda_{dec} t} + c_{2} e^{-#lambda_{cat} t}', 'lf')\n leg.Draw('same')\n\n outputFile.cd()\n cS1.Write()\n cS1.SaveAs('data/output/ComparisonsTDC.pdf')\n\n\n\n\n\nif __name__ == '__main__':\n \n tree = uproot.open(\"data/processed/data_tree.root\")[\"fTreeData\"]\n df = tree.arrays(library='pd')\n df['tdc_ns'] = df['2228A_-_tdc__ch6'] * 2.5\n dfPU = df.query('`V259N_-_multi-hit_patter_unit__ch0` == 0', inplace=False)\n\n rootFilePath = 'data/output/Comparison.root'\n rootFile = TFile(rootFilePath, 'recreate')\n\n PatternUnitSelection(df, dfPU, rootFile)\n secondPeakSelection(df, rootFile)\n TDCwithSelection(df, rootFile)\n\n ## Produce TH2 and projections along axis\n #hist10 = AdcTdc2dimHistCompare(df, rootFile, 10)\n #print('Pearson correlation (ch10): ', df['2249W_-_adc__ch10'].corr(df['2228A_-_tdc__ch6'], method='pearson'))\n #print('Spearman correlation (ch10): ', df['2249W_-_adc__ch10'].corr(df['2228A_-_tdc__ch6'], method='spearman'))\n #hist11 = AdcTdc2dimHistCompare(df, rootFile, 11)\n #print('Pearson correlation (ch11): ', df['2249W_-_adc__ch11'].corr(df['2228A_-_tdc__ch6'], method='pearson'))\n #print('Spearman correlation (ch11): ', df['2249W_-_adc__ch11'].corr(df['2228A_-_tdc__ch6'], method='spearman'))\n #AdcTdc2dimHistCompare(dfPU, rootFile, 10, True)\n #AdcTdc2dimHistCompare(dfPU, rootFile, 11, True)\n\n #TDCprojBinList = [[320, 340], [520, 540], [720, 740], [920, 940], [1120, 1140], \n # [1320, 1340], [1520, 1540], [1720, 1740], [1920, 1940], [2120, 2140],\n # [2320, 2340]]\n #for bin_edges in TDCprojBinList: \n # TDCprojection(hist10, bin_edges[0]+1, bin_edges[1], rootFile, ADCchannel=10)\n # TDCprojection(hist11, bin_edges[0]+1, bin_edges[1], rootFile, ADCchannel=11)\n # \n\n #ADCprojBinList = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8]]\n #for bin_edges in ADCprojBinList: \n # ADCprojection(hist10, bin_edges[0]+1, bin_edges[1], rootFile, ADCchannel=10)\n # ADCprojection(hist11, bin_edges[0]+1, bin_edges[1], rootFile, ADCchannel=11) \n\n rootFile.Close()\n\n\n","repo_name":"GiorgioAlbertoLucia/LabFNS1","sub_path":"Python/src/Comparisons.py","file_name":"Comparisons.py","file_ext":"py","file_size_in_byte":15580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"33308705561","text":"from typing import List, Optional, Tuple\r\n\r\nfrom src.aoc2022 import utils\r\n\r\n\r\ndef parse_data_to_array(\r\n raw_data: str,\r\n) -> List[Tuple[int, int, int, int]]:\r\n \"\"\"\r\n Parse raw data into a list of sensor/closest beacon locations\r\n\r\n :param raw_data: Raw data to parse into sensor/beacon locations\r\n :type raw_data: str\r\n\r\n :return: the parsed sensor/beacon locations\r\n :rtype: List[Tuple[int, int]]\r\n \"\"\"\r\n\r\n coordinate_pairs = []\r\n\r\n for line in raw_data.split(\"\\n\"):\r\n sensor_str, beacon_str = line.split(\": \")\r\n\r\n sensor_prefix = \"Sensor at \"\r\n x_str, y_str = sensor_str.replace(sensor_prefix, \"\").split(\", \")\r\n sensor_location = int(x_str[2:]), int(y_str[2:])\r\n\r\n beacon_prefix = \"closest beacon is at \"\r\n x_str, y_str = beacon_str.replace(beacon_prefix, \"\").split(\", \")\r\n beacon_location = int(x_str[2:]), int(y_str[2:])\r\n\r\n coordinate_pairs.append((*sensor_location, *beacon_location))\r\n\r\n return coordinate_pairs\r\n\r\n\r\ndef count_scanned_location(\r\n beacon_sensor_locations: List[Tuple[int, int, int, int]],\r\n row_number: int,\r\n bounding_range: Optional[Tuple[int, int]] = None,\r\n) -> Tuple[List[Tuple[int, int]], int]:\r\n \"\"\"\r\n Count how many locations have been scanned given the beacon/sensor\r\n locations and the row number\r\n\r\n :param beacon_sensor_locations: List of sensor/beacon locations\r\n :type beacon_sensor_locations: List[Tuple[int, int, int, int]]\r\n\r\n :param row_number: The row for which to count the scan locations\r\n :type row_number: int\r\n\r\n :param bounding_range: an optional bounding range for scan range\r\n :type bounding_range: Optional[Tuple[int, int]]\r\n\r\n :return: the ranges scanned as well as the total number of scanned cells\r\n :rtype: Tuple[List[Tuple[int, int]], int]\r\n \"\"\"\r\n\r\n ranges = []\r\n\r\n # note this is not optimal, this is O(nm), where n = num beacons, m = size\r\n # could do an O(n^2) solution by checking each pair of beacons, would be\r\n # faster in the case that n << m\r\n for sensor_x, sensor_y, beacon_x, beacon_y in beacon_sensor_locations:\r\n\r\n L1_dist = abs(beacon_x - sensor_x) + abs(beacon_y - sensor_y)\r\n\r\n width = (2 * L1_dist + 1) - (2 * abs(sensor_y - row_number))\r\n\r\n if width > 0:\r\n left = sensor_x - width // 2\r\n right = sensor_x + width // 2\r\n if bounding_range is not None:\r\n left = max(bounding_range[0], min(bounding_range[1], left))\r\n right = max(bounding_range[0], min(bounding_range[1], right))\r\n\r\n range_ = (left, right)\r\n ranges.append(range_)\r\n\r\n potential_beacons = set(\r\n [t[2] for t in beacon_sensor_locations if t[3] == row_number]\r\n )\r\n\r\n sorted_ranges = sorted(ranges, key=lambda t: t[0])\r\n range_stack = [sorted_ranges[0]]\r\n\r\n for start, end in sorted_ranges[1:]:\r\n stack_start, stack_end = range_stack[-1]\r\n\r\n if stack_start <= start <= stack_end:\r\n range_stack[-1] = (stack_start, max(stack_end, end))\r\n else:\r\n range_stack.append((start, end))\r\n\r\n total_count = 0\r\n for start, end in range_stack:\r\n for x in potential_beacons:\r\n if start <= x <= end:\r\n total_count -= 1\r\n\r\n total_count += end - start + 1\r\n\r\n return range_stack, total_count\r\n\r\n\r\nif __name__ == \"__main__\": # pragma: no cover\r\n\r\n row_to_analyze = 2_000_000\r\n\r\n raw_data = utils.get_raw_data(\"./src/aoc2022/data/day15.txt\")\r\n sensor_beacon_coordinates = parse_data_to_array(raw_data)\r\n\r\n ranges, location_count = count_scanned_location(\r\n sensor_beacon_coordinates, row_to_analyze\r\n )\r\n print(f\"{location_count} locations are sure to not contain a beacon\")\r\n\r\n min_x, max_x = 0, 4_000_000\r\n\r\n for i in range(min_x, max_x):\r\n ranges, location_count = count_scanned_location(\r\n sensor_beacon_coordinates, i, bounding_range=(min_x, max_x)\r\n )\r\n\r\n if len(ranges) != 1:\r\n x_coord = ranges[0][1] + 1\r\n print(f\"The tuning frequence is {x_coord * 4_000_000 + i}\")\r\n break\r\n","repo_name":"Philliams/AdventOfCode","sub_path":"src/aoc2022/days/day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":4167,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"86712409067","text":"#!/usr/bin/env python3\n# Disable some of the pylint violations in this file\n# see https://pylint.pycqa.org/en/latest/user_guide/messages/message_control.html#block-disables\n# pylint: disable=line-too-long, missing-function-docstring, missing-module-docstring\n\nfrom __future__ import print_function\nfrom future.utils import iteritems\nfrom abc import ABCMeta, abstractmethod\nimport os\nimport logging\n\n\n# try:\n# from lxml import etree as ET\n# #print(\"running with lxml.etree\")\n# except ImportError:\ntry:\n import xml.etree.ElementTree as ET\n # print(\"running with ElementTree on Python 2.5+\")\nexcept ImportError:\n # print(\"Failed to import ElementTree from any known place\")\n pass\n\nimport xacro\nimport xml.dom.minidom\nimport codecs\nimport yaml\nimport json\nimport copy\nfrom collections import OrderedDict\n\nfrom modular.utils import ResourceFinder, ModularResourcesManager\nfrom modular.enums import ModuleType, ModuleClass\nfrom modular.ModelStats import ModelStats\nimport modular.ModuleNode as ModuleNode\nimport argparse\n\nimport rospy\nimport roslaunch\nimport rospkg\nimport tf\n\n# from anytree import NodeMixin, RenderTree, Node, AsciiStyle\nimport anytree\nfrom anytree import RenderTree\n\nimport subprocess\nfrom shutil import copyfile\nimport os\nimport errno\nimport sys\ncurrDir = os.path.dirname(os.path.realpath(__file__))\n# print(currDir)\nrootDir = os.path.abspath(os.path.join(currDir, '../..'))\n# print(rootDir)\nif rootDir not in sys.path: # add parent dir to paths\n sys.path.append(rootDir)\n\nNS_XACRO = \"http://www.ros.org/wiki/xacro\"\nET.register_namespace(\"xacro\", NS_XACRO)\nns = {\"xacro\": NS_XACRO}\n\nimport modular\npath_name = os.path.dirname(modular.__file__)\n# print(path_name)\npath_superbuild = os.path.abspath(os.path.join(path_name, '../..'))\n# print(path_superbuild)\n# #obtaining tree from base file\n# resource_path = '/'.join(('modular_data', 'urdf/ModularBot.library.urdf.xacro'))\n# basefile_name = pkg_resources.resource_string(resource_package, resource_path)\n# urdf_tree = ET.parse(basefile_name)\n\n# Use /tmp folder to store urdf, srdf, etc.\npath_name = \"/tmp\"\n\nfrom enum import Enum\nclass SlaveDescMode(str, Enum):\n \"\"\"Slave description mode\"\"\"\n USE_POSITIONS = 'use_pos'\n USE_IDS = 'use_ids'\n\n# noinspection PyPep8Naming\ndef ordered_load(stream, Loader=yaml.SafeLoader, object_pairs_hook=OrderedDict):\n class OrderedLoader(Loader):\n pass\n\n def construct_mapping(loader, node):\n loader.flatten_mapping(node)\n return object_pairs_hook(loader.construct_pairs(node))\n\n OrderedLoader.add_constructor(\n yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n construct_mapping)\n\n return yaml.load(stream, OrderedLoader)\n\n\nclass MyDumper(yaml.Dumper):\n\n def increase_indent(self, flow=False, indentless=False):\n return super(MyDumper, self).increase_indent(flow, False)\n\n\n# noinspection PyPep8Naming\ndef ordered_dump(data, stream=None, Dumper=MyDumper, **kwds):\n class OrderedDumper(Dumper):\n pass\n\n def _dict_representer(dumper, data):\n return dumper.represent_mapping(\n yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,\n data.items())\n\n OrderedDumper.add_representer(OrderedDict, _dict_representer)\n\n # to avoid printing tags. TODO: Find a better way to do this. This changes the global yaml emitter\n def noop(self, *args, **kw):\n pass\n\n yaml.emitter.Emitter.process_tag = noop\n\n return yaml.dump(data, stream, OrderedDumper, **kwds)\n\n\ndef repl_option():\n parser = argparse.ArgumentParser()\n # parser.add_argument(\"-f\", \"--file_yaml\", dest=\"esc_type_yaml\", action=\"store\", default=\"esc_type.yaml\")\n parser.add_argument(\"-f\", \"--file_yaml\", dest=\"robot_id_yaml\", action=\"store\", default=\"./robot_id.yaml\")\n parser.add_argument(\"-c\", dest=\"cmd_exec_cnt\", action=\"store\", type=int, default=1)\n args = parser.parse_args()\n dict_opt = vars(args)\n return dict_opt\n\n\nclass Plugin:\n __metaclass__ = ABCMeta\n\n @property\n def urdf_writer(self):\n return self._urdf_writer\n\n @urdf_writer.setter\n def urdf_writer(self, writer):\n self._urdf_writer = writer\n\n @abstractmethod\n def add_plugin(self):\n pass\n\n @abstractmethod\n def add_joint(self):\n pass\n\n @abstractmethod\n def remove_joint(self):\n pass\n\n # SRDF\n @abstractmethod\n def add_gripper_to_srdf(self):\n pass\n\n @abstractmethod\n def add_hand_group_to_srdf(self):\n pass\n\n @abstractmethod\n def add_wheel_to_srdf(self):\n pass\n\n @abstractmethod\n def add_wheel_group_to_srdf(self):\n pass\n\n\n # TODO: This should be fixed. Should not be here, probably a SRDFwriter class could be implemented\n def write_srdf(self, builder_joint_map=None):\n \"\"\"Generates a basic srdf so that the model can be used right away with XBotCore\"\"\"\n\n root = ET.Element('robot', name=\"ModularBot\")\n\n active_modules_chains = []\n\n groups = []\n chains = []\n joints = []\n wheels = []\n end_effectors = []\n groups_in_chains_group = []\n groups_in_arms_group = []\n\n active_modules_chains = self.urdf_writer.get_actuated_modules_chains()\n self.urdf_writer.print(active_modules_chains)\n\n for idx, joints_chain in enumerate(active_modules_chains):\n group_name = \"chain\" + self.urdf_writer.find_chain_tag(joints_chain)\n groups.append(ET.SubElement(root, 'group', name=group_name))\n base_link = self.urdf_writer.find_chain_base_link(joints_chain)\n tip_link = self.urdf_writer.find_chain_tip_link(joints_chain)\n chains.append(ET.SubElement(groups[idx], 'chain', base_link=base_link, tip_link=tip_link))\n \n # Create groups for chains, arms and wheels. Also 'group_state' for homing\n chains_group = ET.SubElement(root, 'group', name=\"chains\")\n arms_group = ET.SubElement(root, 'group', name=\"arms\")\n wheels_group = self.add_wheel_group_to_srdf(root, \"wheels\")\n group_state = ET.SubElement(root, 'group_state', name=\"home\", group=\"chains\")\n\n for joints_chain in active_modules_chains:\n group_name = \"chain\" + self.urdf_writer.find_chain_tag(joints_chain)\n groups_in_chains_group.append(ET.SubElement(chains_group, 'group', name=group_name))\n for joint_module in joints_chain:\n # add joints chain to srdf end-effectors group\n if joint_module.type in ModuleClass.end_effector_modules():\n groups_in_arms_group.append(ET.SubElement(arms_group, 'group', name=group_name))\n # TODO: add end-effector module to srdf end-effectors group. To be fixed for all end-effector types.\n # add wheel module to srdf wheels group\n if joint_module.type is ModuleType.WHEEL:\n wheels += filter(lambda item: item is not None, [self.add_wheel_to_srdf(wheels_group, joint_module.name)])\n # add homing state for each joint-like module. Also create custom groups for some end-effectors\n if joint_module.type in ModuleClass.joint_modules() | {ModuleType.DAGANA}:\n joint_name = self.urdf_writer.get_joint_name(joint_module)\n if builder_joint_map is not None:\n homing_value = float(builder_joint_map[joint_name])\n else:\n homing_value = 0.1\n joints.append(ET.SubElement(group_state, \n 'joint', \n name=joint_name, \n value=str(homing_value)))\n elif joint_module.type is ModuleType.TOOL_EXCHANGER:\n tool_exchanger_group = ET.SubElement(root, 'group', name=\"ToolExchanger\")\n end_effectors.append(ET.SubElement(tool_exchanger_group, \n 'joint',\n name=joint_module.name + '_fixed_joint'))\n elif joint_module.type is ModuleType.GRIPPER:\n hand_name = \"hand\" + self.urdf_writer.find_chain_tag(joints_chain)\n self.add_hand_group_to_srdf(root, joint_module.name, hand_name)\n end_effectors += filter(lambda item: item is not None, [self.add_gripper_to_srdf(root, joint_module.name, hand_name, group_name)])\n\n xmlstr = xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml(indent=\" \")\n\n return xmlstr\n\n # JOINT MAP\n def write_joint_map(self, use_robot_id=False):\n \"\"\"Creates the joint map needed by XBotCore \"\"\"\n\n # global path_name\n jointmap_filename = path_name + '/ModularBot/joint_map/ModularBot_joint_map.yaml'\n # jointmap_filename = path_superbuild + '/configs/ADVR_shared/ModularBot/joint_map/ModularBot_joint_map.yaml'\n ## jointmap_filename = self.urdf_writer.resource_finder.get_filename('joint_map/ModularBot_joint_map.yaml',\n ## 'modularbot_path')\n #jointmap_filename=\"/tmp/modular/joint_map/ModularBot_joint_map.yaml\"\n i = 0\n joint_map = {'joint_map': {}}\n for hub_module in self.urdf_writer.listofhubs:\n i += 1\n if use_robot_id:\n joint_map['joint_map'][int(hub_module.robot_id)] = \"HUB_\" + str(hub_module.robot_id)\n else:\n joint_map['joint_map'][i] = \"HUB_\" + str(i)\n for joints_chain in self.urdf_writer.listofchains:\n for joint_module in joints_chain:\n if joint_module.type in ModuleClass.nonactuated_modules():\n continue\n i += 1\n if joint_module.type is ModuleType.TOOL_EXCHANGER:\n name = joint_module.name + '_fixed_joint'\n elif joint_module.type is ModuleType.GRIPPER:\n name = joint_module.name + '_fixed_joint'\n else:\n name = joint_module.name\n\n if use_robot_id:\n joint_map['joint_map'][int(joint_module.robot_id)] = name\n else:\n joint_map['joint_map'][i] = name\n # self.urdf_writer.print(str(i), joint_module.name)\n # self.urdf_writer.print(joint_map)\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(jointmap_filename)):\n try:\n os.makedirs(os.path.dirname(jointmap_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(jointmap_filename, 'w+') as outfile:\n yaml.dump(joint_map, outfile, default_flow_style=False)\n return joint_map\n\n # CONFIG\n def write_lowlevel_config(self):\n pass\n\n\nclass RosControlPlugin(Plugin):\n def add_plugin(self):\n return ET.SubElement(self.urdf_writer.root, \"xacro:plugin_ros_control\")\n\n def add_joint(self, joint_name):\n ET.SubElement(self.urdf_writer.root, \"xacro:ros_control_transmission\",\n transmission=joint_name+'_tran',\n joint=joint_name,\n motor=joint_name+'_mot')\n\n def remove_joint(self, joint_name):\n for transmission in self.urdf_writer.root.findall('*[@transmission]', ns):\n if transmission.attrib['joint'] == joint_name:\n self.urdf_writer.root.remove(transmission)\n\n # SRDF\n def add_gripper_to_srdf(self, root, gripper_name, hand_name, parent_group_name):\n ET.SubElement(root, \"end-effector\", name=\"TCP\", parent_link=\"TCP_\"+gripper_name,\n group=hand_name, parent_group=parent_group_name)\n # add arm_hand group\n arm_hand_group = ET.SubElement(root, \"group\", name=\"arm_\" + hand_name)\n ET.SubElement(arm_hand_group, \"group\", name=parent_group_name)\n ET.SubElement(arm_hand_group, \"group\", name=hand_name)\n\n def add_hand_group_to_srdf(self, root, gripper_name, hand_name):\n hand_group = ET.SubElement(root, \"group\", name=hand_name)\n ET.SubElement(hand_group, \"link\", name=gripper_name)\n ET.SubElement(hand_group, \"link\", name=gripper_name+\"_leftfinger\")\n ET.SubElement(hand_group, \"link\", name=gripper_name+\"_rightfinger\")\n ET.SubElement(hand_group, \"joint\", name=gripper_name+\"_finger_joint1\")\n ET.SubElement(hand_group, \"passive_joint\", name=gripper_name+\"_finger_joint2\")\n open_state = ET.SubElement(root, \"group_state\", name=\"open\", group=hand_name)\n ET.SubElement(open_state, \"joint\", name=gripper_name+\"_finger_joint1\", value=\"0.05\")\n ET.SubElement(open_state, \"joint\", name=gripper_name+\"_finger_joint2\", value=\"0.05\")\n close_state = ET.SubElement(root, \"group_state\", name=\"close\", group=hand_name)\n ET.SubElement(close_state, \"joint\", name=gripper_name+\"_finger_joint1\", value=\"0.0\")\n ET.SubElement(close_state, \"joint\", name=gripper_name+\"_finger_joint2\", value=\"0.0\")\n # remove collisions\n ET.SubElement(root, \"disable_collisions\", link1=gripper_name, link2=\"TCP_\"+gripper_name, reason=\"Adjacent\")\n ET.SubElement(root, \"disable_collisions\", link1=gripper_name, link2=gripper_name+\"_leftfinger\", reason=\"Adjacent\")\n ET.SubElement(root, \"disable_collisions\", link1=gripper_name, link2=gripper_name+\"_rightfinger\", reason=\"Adjacent\")\n ET.SubElement(root, \"disable_collisions\", link1=\"TCP_\"+gripper_name, link2=gripper_name+\"_rightfinger\", reason=\"Default\")\n ET.SubElement(root, \"disable_collisions\", link1=\"TCP_\"+gripper_name, link2=gripper_name+\"_leftfinger\",reason=\"Default\")\n ET.SubElement(root, \"disable_collisions\", link1=gripper_name + \"_rightfinger\", link2=gripper_name+\"_leftfinger\", reason=\"Default\")\n\n return hand_group\n\n def add_wheel_to_srdf(self, wheel_group_name, wheel_name):\n return None\n\n def add_wheel_group_to_srdf(self, root, wheel_group_name):\n pass\n\n def write_srdf(self, builder_joint_map=None):\n \"\"\"Generates a basic srdf so that the model can be used right away with XBotCore\"\"\"\n \n root = ET.Element('robot', name=\"ModularBot\")\n\n groups = []\n chains = []\n joints = []\n end_effectors = []\n groups_in_chains_group = []\n groups_in_arms_group = []\n # groups_in_hands_group = []\n\n # MoveIt\n controller_list = []\n initial_poses = []\n hardware_interface_joints = []\n\n #kinematics.yaml\n template_kinematics_filename = self.urdf_writer.resource_finder.get_filename('moveit_config/kinematics.yaml', ['data_path'])\n kinematics_filename = path_name + \"/moveit_config/kinematics.yaml\"\n # kinematics_filename = \"/tmp/modular/moveit_config/kinematics.yaml\"\n tmp_kinematics = OrderedDict([])\n kinematics = OrderedDict([])\n with open(template_kinematics_filename, 'r') as stream:\n try:\n tmp_kinematics = ordered_load(stream, yaml.SafeLoader)\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n\n #ompl_planning.yaml\n template_ompl_filename = self.urdf_writer.get_filename('moveit_config/ompl_planning.yaml', ['data_path'])\n ompl_filename = path_name + \"/moveit_config/ompl_planning.yaml\"\n # ompl_filename = \"/tmp/modular/moveit_config/ompl_planning.yaml\"\n tmp_ompl = OrderedDict([])\n ompl = OrderedDict([])\n with open(template_ompl_filename, 'r') as stream:\n try:\n tmp_ompl = ordered_load(stream, yaml.SafeLoader)\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n ompl.update([('planner_configs', copy.deepcopy(tmp_ompl['planner_configs']))])\n\n self.urdf_writer.print(self.urdf_writer.listofchains)\n for idx, joints_chain in enumerate(self.urdf_writer.listofchains):\n group_name = \"arm\" + self.urdf_writer.find_chain_tag(joints_chain)\n groups.append(ET.SubElement(root, 'group', name=group_name))\n base_link = self.urdf_writer.find_chain_base_link(joints_chain)\n tip_link = self.urdf_writer.find_chain_tip_link(joints_chain)\n chains.append(ET.SubElement(groups[idx], 'chain', base_link=base_link, tip_link=tip_link))\n arms_group = ET.SubElement(root, 'group', name=\"arms\")\n #chains_group = ET.SubElement(root, 'group', name=\"chains\")\n group_state = ET.SubElement(root, 'group_state', name=\"home\", group=\"chains\")\n tool_exchanger_group = ET.SubElement(root, 'group', name=\"ToolExchanger\")\n hands_group = ET.SubElement(root, 'group', name=\"hands\")\n # MoveIt\n initial_poses.append(OrderedDict([('group', 'arms'), ('pose', 'home')]))\n for idx, joints_chain in enumerate(self.urdf_writer.listofchains):\n #group_name = \"chain\" + self.urdf_writer.find_chain_tag(joints_chain)\n #groups_in_chains_group.append(ET.SubElement(chains_group, 'group', name=group_name))\n group_name = \"arm\" + self.urdf_writer.find_chain_tag(joints_chain)\n hand_name = \"hand\" + self.urdf_writer.find_chain_tag(joints_chain)\n groups_in_arms_group.append(ET.SubElement(arms_group, 'group', name=group_name))\n # MoveIt: create controller list\n controller_list.append(OrderedDict([('name', 'fake_'+group_name+'_controller'), ('joints', [])]))\n kinematics.update([(group_name, copy.deepcopy(tmp_kinematics['group_name']))])\n ompl.update([(group_name, copy.deepcopy(tmp_ompl['group_name']))])\n for joint_module in joints_chain:\n if joint_module.type in ModuleClass.joint_modules() | {ModuleType.DAGANA}:\n # Homing state\n if builder_joint_map is not None:\n homing_value = float(builder_joint_map[joint_module.name])\n else:\n homing_value = 0.1\n #self.urdf_writer.print(homing_value)\n joints.append(ET.SubElement(group_state, 'joint', name=joint_module.name, value=str(homing_value)))\n # Disable collision\n # disable_collision = ET.SubElement(root, 'disable_collisions', link1=joint_module.stator_name, link2=joint_module.distal_link_name, reason='Adjacent')\n # MoveIt: add joints to controller\n controller_list[idx]['joints'].append(joint_module.name)\n hardware_interface_joints.append(joint_module.name)\n elif joint_module.type is ModuleType.TOOL_EXCHANGER:\n tool_exchanger_group = ET.SubElement(root, 'group', name=\"ToolExchanger\")\n end_effectors.append(ET.SubElement(tool_exchanger_group, 'joint',\n name=joint_module.name + '_fixed_joint'))\n elif joint_module.type is ModuleType.GRIPPER:\n self.add_hand_group_to_srdf(root, joint_module.name, hand_name)\n # groups_in_hands_group.append(ET.SubElement(hands_group, 'group', name=hand_name))\n end_effectors += filter(lambda item: item is not None, [self.add_gripper_to_srdf(root, joint_module.name, hand_name, group_name)])\n controller_list.append(OrderedDict([('name', 'fake_' + hand_name + '_controller'), ('joints', [])]))\n controller_list[idx+1]['joints'].append(joint_module.name+'_finger_joint1')\n controller_list[idx+1]['joints'].append(joint_module.name + '_finger_joint2')\n hardware_interface_joints.append(joint_module.name + '_finger_joint1')\n initial_poses.append(OrderedDict([('group', hand_name), ('pose', 'open')]))\n ompl.update([(hand_name, copy.deepcopy(tmp_ompl['group_name']))])\n ompl.update([('arm_'+hand_name, copy.deepcopy(tmp_ompl['group_name']))])\n\n # MoveIt: add virtual joint\n # ET.SubElement(root, \"virtual_joint\", name=\"virtual_joint\", type=\"floating\", parent_frame=\"world\", child_link=\"base_link\")\n\n # MoveIt disable collisions\n for coll_elem in self.urdf_writer.collision_elements:\n ET.SubElement(root, 'disable_collisions', link1=coll_elem[0], link2=coll_elem[1], reason='Adjacent')\n\n xmlstr = xml.dom.minidom.parseString(ET.tostring(root)).toprettyxml(indent=\" \")\n\n ###################################\n # Moveit configs: TO BE FIXED\n # ros_controllers_template_filename = self.urdf_writer.resource_finder.get_filename(\n # 'ModularBot/moveit_config/ros_controllers.yaml', 'data_path')\n # ros_controllers_filename = \"/tmp/modular/moveit_config/ros_controllers.yaml\"\n # ros_controllers = OrderedDict([])\n\n fake_controllers_filename = path_name + \"/moveit_config/fake_controllers.yaml\"\n # fake_controllers_filename = \"/tmp/modular/moveit_config/fake_controllers.yaml\"\n fake_controllers = OrderedDict([('controller_list', controller_list)])\n fake_controllers.update({'initial': initial_poses})\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(fake_controllers_filename)):\n try:\n os.makedirs(os.path.dirname(fake_controllers_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(fake_controllers_filename, 'w') as outfile:\n ordered_dump(fake_controllers, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n with open(kinematics_filename, 'w') as outfile:\n ordered_dump(kinematics, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n with open(ompl_filename, 'w') as outfile:\n ordered_dump(ompl, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n # ros_controllers.launch\n ros_controllers_launch = path_name + \"/launch/ros_controllers.launch\"\n # ros_controllers_launch = \"/tmp/modular/launch/ros_controllers.launch\"\n launch_root = ET.Element('launch')\n ET.SubElement(launch_root, \"rosparam\", file=\"$(find pino_moveit)/moveit_config/ros_controllers.yaml\",\n command=\"load\")\n controller_list_str = ' '.join((ctrl['name'].replace('fake_', '') for ctrl in controller_list))\n ET.SubElement(launch_root, \"node\", name=\"controller_spawner\", pkg=\"controller_manager\", type=\"spawner\",\n respawn=\"false\", output=\"screen\", args=\"joint_state_controller \"+controller_list_str)\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(ros_controllers_launch)):\n try:\n os.makedirs(os.path.dirname(ros_controllers_launch))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n xmlstr_launch = xml.dom.minidom.parseString(ET.tostring(launch_root)).toprettyxml(indent=\" \")\n with open(ros_controllers_launch, 'w+') as f:\n f.write(xmlstr_launch)\n\n #########################\n # Remove collisions from SRDF by using Moveit collisions_updater\n # THIS WILL BE DONE AFTER DEPLOY FOR NOW\n\n # rospy.init_node('collisions_node', anonymous=True)\n # uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)\n # roslaunch.configure_logging(uuid)\n # # find launch filename\n # update_collisions_launch = self.urdf_writer.resource_finder.get_filename('launch/update_collision.launch', 'data_path')\n # launch = roslaunch.parent.ROSLaunchParent(uuid, [update_collisions_launch])\n # launch.start()\n # rospy.loginfo(\"started\")\n # launch.spin()\n\n return xmlstr\n\n\nclass XBotCorePlugin(Plugin):\n def add_plugin(self):\n # return ET.SubElement(self.urdf_writer.root, \"xacro:plugin_xbotcore\")\n pass\n\n def add_joint(self, joint_name):\n pass\n\n def remove_joint(self, joint_name):\n pass\n\n # SRDF\n def add_gripper_to_srdf(self, root, gripper_name, hand_name, parent_group_name):\n return None\n\n def add_hand_group_to_srdf(self, root, gripper_name, hand_name):\n pass\n\n def add_wheel_to_srdf(self, wheel_group_name, wheel_name):\n return None\n\n def add_wheel_group_to_srdf(self, root, wheel_group_name):\n pass\n\n # CONFIG\n def write_lowlevel_config(self, use_robot_id=False):\n \"\"\"Creates the low level config file needed by XBotCore \"\"\"\n\n # basic_config_filename = path_name + '/configs/ModularBot.yaml'\n basic_config_filename = self.urdf_writer.resource_finder.get_filename('configs/ModularBot.yaml', ['data_path'])\n lowlevel_config_filename = path_name + '/ModularBot/configs/ModularBot.yaml'\n ## lowlevel_config_filename = self.urdf_writer.resource_finder.get_filename('configs/ModularBot.yaml', 'modularbot_path')\n # lowlevel_config_filename = \"/tmp/modular/configs/ModularBot.yaml\"\n lowlevel_config = OrderedDict([])\n\n with open(basic_config_filename, 'r') as stream:\n try:\n lowlevel_config = ordered_load(stream, yaml.SafeLoader)\n self.urdf_writer.print(list(lowlevel_config.items())[0])\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n\n self.urdf_writer.print(lowlevel_config.items())\n self.urdf_writer.print(lowlevel_config['GazeboXBotPlugin'])\n lowlevel_config['GazeboXBotPlugin']['gains'] = OrderedDict([])\n i = 0\n p = 0\n for joints_chain in self.urdf_writer.listofchains:\n # HACK\n p += 1\n for joint_module in joints_chain:\n if joint_module.type in ModuleClass.nonactuated_modules():\n continue\n if joint_module.type in ModuleClass.joint_modules():\n i += 1\n lowlevel_config['GazeboXBotPlugin']['gains'][joint_module.name] = OrderedDict(\n [('p', 300), ('d', 20)])\n if use_robot_id:\n key = 'CentAcESC_' + str(joint_module.robot_id)\n else:\n key = 'CentAcESC_' + str(i)\n value = joint_module.CentAcESC\n self.urdf_writer.print(yaml.dump(joint_module.CentAcESC))\n # HACK: Every joint on 2nd, 3rd, etc. chains have the torque loop damping set very low.\n # This is to handle chains with only one joint and low inertia after it.\n # If we build two big robots this could have catastrophic effects\n # TODO: fix this\n if p > 1:\n value.pid.impedance = [500.0, 20.0, 1.0, 0.003, 0.99]\n elif joint_module.type is ModuleType.TOOL_EXCHANGER:\n if use_robot_id:\n key = 'AinMsp432ESC_' + str(joint_module.robot_id)\n xbot_ecat_interface = [[int(joint_module.robot_id)], \"libXBotEcat_ToolExchanger\"]\n else:\n key = 'AinMsp432ESC_' + str(i)\n xbot_ecat_interface = [[int(i)], \"libXBotEcat_ToolExchanger\"]\n value = joint_module.AinMsp432ESC\n self.urdf_writer.print(yaml.dump(joint_module.AinMsp432ESC))\n lowlevel_config['HALInterface']['IEndEffectors'].append(xbot_ecat_interface)\n elif joint_module.type is ModuleType.GRIPPER:\n if use_robot_id:\n key = 'LpESC_' + str(joint_module.robot_id)\n xbot_ecat_interface = [[int(joint_module.robot_id)], \"libXBotEcat_Gripper\"]\n else:\n key = 'LpESC_' + str(i)\n xbot_ecat_interface = [[int(i)], \"libXBotEcat_Gripper\"]\n value = joint_module.LpESC\n self.urdf_writer.print(yaml.dump(joint_module.LpESC))\n lowlevel_config['HALInterface']['IEndEffectors'].append(xbot_ecat_interface)\n\n lowlevel_config[key] = value\n self.urdf_writer.print(joint_module.kinematics.__dict__.items())\n self.urdf_writer.print(lowlevel_config[key])\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(lowlevel_config_filename)):\n try:\n os.makedirs(os.path.dirname(lowlevel_config_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(lowlevel_config_filename, 'w') as outfile:\n # ordered_dump(lowlevel_config, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(lowlevel_config, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n return lowlevel_config\n\nclass XBot2Plugin(Plugin):\n def add_plugin(self):\n #self.urdf_writer.plugin_element = ET.SubElement(self.urdf_writer.root, \"xacro:plugin_xbot2\")\n self.gazebo_node = ET.SubElement(self.urdf_writer.root, \"gazebo\")\n self.plugin_node = ET.SubElement(self.gazebo_node, \"plugin\",\n name=\"xbot2_gz_joint_server\",\n filename=\"libxbot2_gz_joint_server.so\")\n self.pid_node = ET.SubElement(self.plugin_node, \"pid\")\n self.gain_node = ET.SubElement(self.pid_node, \"gain\", name='small_mot', p='100', d='10')\n self.gain_node = ET.SubElement(self.pid_node, \"gain\", name='medium_mot', p='500', d='50')\n self.gain_node = ET.SubElement(self.pid_node, \"gain\", name='big_mot', p='1000', d='100')\n return self.pid_node\n\n def add_joint(self, joint_name, control_params=None):\n #return ET.SubElement(self.pid_node, \"xacro:add_xbot2_pid\", name=joint_name, profile=\"small_mot\")\n if control_params is not None:\n if hasattr(control_params, 'pid'):\n pid_node = ET.SubElement(self.pid_node, \"gain\", name=joint_name, p=str(control_params.pid.p), d=str(control_params.pid.d))\n if hasattr(control_params, 'profile'):\n pid_node = ET.SubElement(self.pid_node, \"gain\", name=joint_name, profile=str(control_params.profile))\n else:\n pid_node = ET.SubElement(self.pid_node, \"gain\", name=joint_name, profile=\"medium_mot\")\n return pid_node\n\n def remove_joint(self, joint_name):\n for pid in self.pid_node.findall('./pid'):\n if pid.attrib['name'] == joint_name:\n self.pid_node.remove(pid)\n\n # SRDF\n def add_gripper_to_srdf(self, root, gripper_name, hand_name, parent_group_name):\n return None\n\n def add_hand_group_to_srdf(self, root, gripper_name, hand_name):\n pass\n\n def add_wheel_to_srdf(self, wheel_group, wheel_name):\n wheel = ET.SubElement(wheel_group, 'joint', name=wheel_name)\n return wheel\n\n def add_wheel_group_to_srdf(self, root, wheel_group_name):\n wheel_group = ET.SubElement(root, 'group', name=wheel_group_name)\n return wheel_group\n\n # JOINT MAP\n def write_joint_map(self, use_robot_id=False):\n \"\"\"Creates the joint map needed by XBotCore \"\"\"\n\n # global path_name\n jointmap_filename = path_name + '/ModularBot/joint_map/ModularBot_joint_map.yaml'\n # jointmap_filename = path_superbuild + '/configs/ADVR_shared/ModularBot/joint_map/ModularBot_joint_map.yaml'\n ## jointmap_filename = self.urdf_writer.resource_finder.get_filename('joint_map/ModularBot_joint_map.yaml',\n ## 'modularbot_path')\n #jointmap_filename=\"/tmp/modular/joint_map/ModularBot_joint_map.yaml\"\n i = 0\n joint_map = {'joint_map': {}, 'albero_gripper_map': {}}\n\n for hub_module in self.urdf_writer.listofhubs:\n i += 1\n if use_robot_id:\n joint_map['joint_map'][int(hub_module.robot_id)] = \"HUB_\" + str(hub_module.robot_id)\n else:\n joint_map['joint_map'][i] = \"HUB_\" + str(i)\n for joints_chain in self.urdf_writer.listofchains:\n for joint_module in joints_chain:\n if joint_module.type in ModuleClass.nonactuated_modules():\n continue\n i += 1\n if joint_module.type is ModuleType.TOOL_EXCHANGER:\n name = joint_module.name + '_fixed_joint'\n elif joint_module.type is ModuleType.GRIPPER:\n name = joint_module.name\n fingers = [name + '_rightfinger', name + '_leftfinger']\n if use_robot_id:\n joint_map['albero_gripper_map'][int(joint_module.robot_id)] = {'name': name, 'fingers': fingers}\n else:\n joint_map['albero_gripper_map'][i] = {'name': name, 'fingers': fingers}\n else:\n name = self.urdf_writer.get_joint_name(joint_module)\n \n if use_robot_id:\n joint_map['joint_map'][int(joint_module.robot_id)] = name\n else:\n joint_map['joint_map'][i] = name\n \n # self.urdf_writer.print(str(i), joint_module.name)\n # self.urdf_writer.print(joint_map)\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(jointmap_filename)):\n try:\n os.makedirs(os.path.dirname(jointmap_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(jointmap_filename, 'w+') as outfile:\n yaml.dump(joint_map, outfile, default_flow_style=False)\n return joint_map\n\n # CONFIG\n def write_lowlevel_config(self, use_robot_id=False):\n \"\"\"Creates the low level config file needed by XBotCore \"\"\"\n # HAL config ModularBot_ec_all\n hal_config_template = self.urdf_writer.resource_finder.get_filename('configs/low_level/hal/ModularBot_ec_all.yaml', ['data_path'])\n hal_config_filename = path_name + '/ModularBot/config/hal/ModularBot_ec_all.yaml'\n # hal_config_filename = self.urdf_writer.resource_finder.get_filename('config/hal/ModularBot_ec_all.yaml', 'modularbot_path')\n # hal_config_filename = \"/tmp/modular/config/hal/ModularBot_ec_all.yaml\"\n hal_config = OrderedDict([])\n\n with open(hal_config_template, 'r') as stream:\n try:\n hal_config = ordered_load(stream, yaml.SafeLoader)\n self.urdf_writer.print(list(hal_config.items())[0])\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n\n self.urdf_writer.print(hal_config['xbotcore_devices']['joint_ec']['params'].items())\n ids = []\n i = 0\n for joints_chain in self.urdf_writer.listofchains:\n for joint_module in joints_chain:\n if joint_module.type in ModuleClass.nonactuated_modules():\n continue\n i += 1\n if joint_module.type in {ModuleType.TOOL_EXCHANGER, ModuleType.GRIPPER}:\n if use_robot_id:\n mod_id = str(joint_module.robot_id)\n else:\n mod_id = str(i)\n ids.append(mod_id)\n ignore_id = OrderedDict({'ignore_id': {'type': 'vector', 'value': ids}})\n hal_config['xbotcore_devices']['joint_ec']['params'].update(ignore_id)\n\n #joint_gripper_adapter\n i = 0\n for joints_chain in self.urdf_writer.listofchains:\n for joint_module in joints_chain:\n if joint_module.type is ModuleType.DAGANA:\n \n attrs = [a for a in dir(joint_module.joint_gripper_adapter) if not a.startswith('__') and not callable(getattr(joint_module.joint_gripper_adapter, a))]\n attrs_with_prefix = [joint_module.name+\"/\" + x for x in attrs]\n params_dict = {i:getattr(joint_module.joint_gripper_adapter, j) for i, j in zip(attrs_with_prefix, attrs)}\n params_dict.update({joint_module.name+\"/joint_name\": {\"value\": joint_module.dagana_joint_name, \"type\": \"string\"}})\n # joint_gripper_adapter_params = OrderedDict({joint_module.name+\"/joint_name\": {\"value\": joint_module.dagana_joint_name, \"type\": \"string\"},\n # joint_module.name+\"/joint_type\": {\"value\": \"joint_ec\", \"type\": \"string\"},\n # joint_module.name+\"/qopen\": {\"value\": -0.4, \"type\": \"double\"},\n # joint_module.name+\"/qclosed\": {\"value\": 0.6, \"type\": \"double\"},\n # joint_module.name+\"/vmax\": {\"value\": 1.0, \"type\": \"double\"},\n # joint_module.name+\"/stiffness\": {\"value\": 50.0, \"type\": \"double\"}\n # })\n joint_gripper_adapter_params = OrderedDict(params_dict)\n hal_config['xbotcore_devices']['joint_gripper_adapter']['params'].update(joint_gripper_adapter_params)\n\n hal_config['xbotcore_devices']['joint_gripper_adapter']['names'].append(joint_module.name)\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(hal_config_filename)):\n try:\n os.makedirs(os.path.dirname(hal_config_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(hal_config_filename, 'w') as outfile:\n # ordered_dump(hal_config, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(hal_config, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n # HAL config ModularBot_idle\n idle_joint_config_template = self.urdf_writer.resource_finder.get_filename(\n 'configs/low_level/joint_config/ModularBot_idle.yaml', ['data_path'])\n idle_joint_config_filename = path_name + '/ModularBot/config/joint_config/ModularBot_idle.yaml'\n # HAL config ModularBot_impd4\n impd4_joint_config_template = self.urdf_writer.resource_finder.get_filename(\n 'configs/low_level/joint_config/ModularBot_impd4.yaml', ['data_path'])\n impd4_joint_config_filename = path_name + '/ModularBot/config/joint_config/ModularBot_impd4.yaml'\n # HAL config ModularBot_pos3b\n pos3b_joint_config_template = self.urdf_writer.resource_finder.get_filename(\n 'configs/low_level/joint_config/ModularBot_pos3b.yaml', ['data_path'])\n pos3b_joint_config_filename = path_name + '/ModularBot/config/joint_config/ModularBot_pos3b.yaml'\n # XBot2 config\n xbot2_config_template = self.urdf_writer.resource_finder.get_filename(\n 'configs/ModularBot_xbot2.yaml', ['data_path'])\n xbot2_config_filename = path_name + '/ModularBot/config/ModularBot.yaml'\n\n idle_joint_config = OrderedDict([])\n impd4_joint_config = OrderedDict([])\n pos3b_joint_config = OrderedDict([])\n xbot2_config = OrderedDict([])\n\n with open(idle_joint_config_template, 'r') as stream:\n try:\n idle_joint_config = ordered_load(stream, yaml.SafeLoader)\n self.urdf_writer.print(list(idle_joint_config.items())[0])\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n with open(impd4_joint_config_template, 'r') as stream:\n try:\n impd4_joint_config = ordered_load(stream, yaml.SafeLoader)\n self.urdf_writer.print(list(impd4_joint_config.items())[0])\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n with open(pos3b_joint_config_template, 'r') as stream:\n try:\n pos3b_joint_config = ordered_load(stream, yaml.SafeLoader)\n self.urdf_writer.print(list(pos3b_joint_config.items())[0])\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n\n i = 0\n p = 0\n for joints_chain in self.urdf_writer.listofchains:\n # HACK\n p += 1\n for joint_module in joints_chain:\n if joint_module.type in ModuleClass.nonactuated_modules():\n continue\n if joint_module.type in {ModuleType.JOINT, ModuleType.DAGANA}:\n key = self.urdf_writer.get_joint_name(joint_module)\n value = joint_module.CentAcESC\n # Remove parameters that are now not used by XBot2 (they are handled by the EtherCat master on a different config file)\n if hasattr(value, 'sign'):\n del value.sign\n if hasattr(value, 'pos_offset'):\n del value.pos_offset\n if hasattr(value, 'max_current_A'):\n del value.max_current_A\n\n impd4_joint_config[key] = copy.deepcopy(value)\n impd4_joint_config[key].control_mode = 'D4_impedance_ctrl'\n if hasattr(impd4_joint_config[key], 'pid'):\n if hasattr(impd4_joint_config[key].pid, 'position'):\n del impd4_joint_config[key].pid.position\n\n pos3b_joint_config[key] = copy.deepcopy(value)\n pos3b_joint_config[key].control_mode = '3B_motor_pos_ctrl'\n if hasattr(pos3b_joint_config[key], 'pid'):\n if hasattr(pos3b_joint_config[key].pid, 'impedance'):\n del pos3b_joint_config[key].pid.impedance\n\n idle_joint_config[key] = copy.deepcopy(value)\n idle_joint_config[key].control_mode = 'idle'\n if hasattr(idle_joint_config[key], 'pid'):\n if hasattr(idle_joint_config[key].pid, 'position'):\n del idle_joint_config[key].pid.position\n if hasattr(idle_joint_config[key], 'pid'):\n if hasattr(idle_joint_config[key].pid, 'impedance'):\n del idle_joint_config[key].pid.impedance\n if hasattr(idle_joint_config[key], 'pid'):\n if hasattr(idle_joint_config[key].pid, 'velocity'):\n del idle_joint_config[key].pid.velocity\n\n # # HACK: Every joint on 2nd, 3rd, etc. chains have the torque loop damping set very low.\n # # This is to handle chains with only one joint and low inertia after it.\n # # If we build two big robots this could have catastrophic effects\n # # TODO: fix this\n # if p > 1:\n # value.pid.impedance = [500.0, 20.0, 1.0, 0.003, 0.99]\n\n elif joint_module.type is ModuleType.WHEEL:\n key = self.urdf_writer.get_joint_name(joint_module)\n value = joint_module.CentAcESC\n # Remove parameters that are now not used by XBot2 (they are handled by the EtherCat master on a different config file)\n if hasattr(value, 'sign'):\n del value.sign\n if hasattr(value, 'pos_offset'):\n del value.pos_offset\n if hasattr(value, 'max_current_A'):\n del value.max_current_A\n\n impd4_joint_config[key] = copy.deepcopy(value)\n impd4_joint_config[key].control_mode = '71_motor_vel_ctrl'\n\n pos3b_joint_config[key] = copy.deepcopy(value)\n pos3b_joint_config[key].control_mode = '71_motor_vel_ctrl'\n\n idle_joint_config[key] = copy.deepcopy(value)\n idle_joint_config[key].control_mode = 'idle'\n if hasattr(idle_joint_config[key], 'pid'):\n if hasattr(idle_joint_config[key].pid, 'velocity'):\n del idle_joint_config[key].pid.velocity\n\n elif joint_module.type is ModuleType.TOOL_EXCHANGER:\n key = joint_module.name\n value = joint_module.AinMsp432ESC\n\n elif joint_module.type is ModuleType.GRIPPER:\n key = joint_module.name + '_motor'\n value = joint_module.LpESC\n # Remove parameters that are now not used by XBot2 (they are handled by the EtherCat master on a different config file)\n if hasattr(value, 'sign'):\n del value.sign\n if hasattr(value, 'pos_offset'):\n del value.pos_offset\n if hasattr(value, 'max_current_A'):\n del value.max_current_A\n\n impd4_joint_config[key] = copy.deepcopy(value)\n impd4_joint_config[key].control_mode = '3B_motor_pos_ctrl'\n\n idle_joint_config[key] = copy.deepcopy(value)\n idle_joint_config[key].control_mode = 'idle'\n\n # idle_joint_config[key] = copy.deepcopy(value)\n # idle_joint_config[key].control_mode = 'idle'\n # Remove parameters that are now not used by XBot2 (they are handled by the EtherCat master on a different config file)\n # del idle_joint_config[key].sign\n # del idle_joint_config[key].pos_offset\n # del idle_joint_config[key].max_current_A\n\n with open(xbot2_config_template, 'r') as stream:\n try:\n xbot2_config = ordered_load(stream, yaml.SafeLoader)\n self.urdf_writer.print(list(idle_joint_config.items())[0])\n except yaml.YAMLError as exc:\n self.urdf_writer.print(exc)\n\n if self.urdf_writer.floating_base:\n xbot2_config['ModelInterface']['is_model_floating_base'] = 'true'\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(idle_joint_config_filename)):\n try:\n os.makedirs(os.path.dirname(idle_joint_config_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n if not os.path.exists(os.path.dirname(impd4_joint_config_filename)):\n try:\n os.makedirs(os.path.dirname(impd4_joint_config_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n if not os.path.exists(os.path.dirname(pos3b_joint_config_filename)):\n try:\n os.makedirs(os.path.dirname(pos3b_joint_config_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n if not os.path.exists(os.path.dirname(xbot2_config_filename)):\n try:\n os.makedirs(os.path.dirname(xbot2_config_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(idle_joint_config_filename, 'w') as outfile:\n # ordered_dump(idle_joint_config, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(idle_joint_config, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n with open(impd4_joint_config_filename, 'w') as outfile:\n # ordered_dump(impd4_joint_config, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(impd4_joint_config, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n with open(pos3b_joint_config_filename, 'w') as outfile:\n # ordered_dump(impd4_joint_config, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(pos3b_joint_config, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n with open(xbot2_config_filename, 'w') as outfile:\n # ordered_dump(impd4_joint_config, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(xbot2_config, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n\n return hal_config\n\n\n# noinspection PyUnresolvedReferences\nclass UrdfWriter:\n def __init__(self,\n config_file='config_file.yaml',\n control_plugin='xbot2',\n elementree=None,\n speedup=False,\n parent=None,\n floating_base=False,\n verbose=False,\n logger=None,\n slave_desc_mode='use_pos'):\n self.config_file = config_file\n self.resource_finder = ResourceFinder(self.config_file)\n self.modular_resources_manager = ModularResourcesManager(self.resource_finder)\n self.reset(control_plugin,\n elementree,\n speedup,\n parent,\n floating_base,\n verbose,\n logger,\n slave_desc_mode)\n\n def reset(self,\n control_plugin='xbot2',\n elementree=None,\n speedup=False,\n parent=None,\n floating_base=False,\n verbose=False,\n logger=None,\n slave_desc_mode='use_pos'):\n\n # Setting this variable to True, speed up the robot building.\n # To be used when the urdf does not need to be shown at every iteration\n self.speedup = speedup\n\n self.parent = parent\n\n # xacro mappings to perform args substitution (see template.urdf.xacro)\n self.default_xacro_mappings = {'modular_path': os.path.dirname(os.path.realpath(__file__)),\n 'floating_base': 'false',\n 'gazebo_urdf': 'false',\n 'velodyne': 'false',\n 'realsense': 'false',\n 'ultrasound': 'false',\n 'use_gpu_ray': 'false'}\n\n self.set_floating_base(floating_base)\n\n if logger is None:\n self.logger = logging.getLogger('URDF_writer')\n else:\n self.logger = logger\n\n self.verbose = verbose\n if self.verbose and self.logger is not None:\n self.logger.setLevel(logging.DEBUG)\n else:\n pass\n\n self.collision_elements = []\n\n # Plugin class attribute. Can be XBot2Plugin, XBotCorePlugin or RosControlPlugin\n if control_plugin == 'ros_control':\n self.control_plugin = RosControlPlugin()\n elif control_plugin == 'xbotcore':\n self.control_plugin = XBotCorePlugin()\n elif control_plugin == 'xbot2':\n self.control_plugin = XBot2Plugin()\n self.control_plugin.urdf_writer = self\n\n if elementree is None:\n ## Open the template xacro file\n template = self.resource_finder.get_string('urdf/template.urdf.xacro', ['data_path'])\n # we load the template as a ET Element. Store the 'robot' element as root\n self.root = ET.fromstring(template)\n # Open the base xacro file\n # filename = path_name + '/modular_data/urdf/template.urdf.xacro'\n # self.print(filename)\n # with codecs.open(filename, 'r') as f:\n # string = f.read()\n # Instantiate an Element Tree\n #self.root = ET.fromstring(string)\n\n self.urdf_tree = ET.ElementTree(self.root)\n\n # change path to xacro library\n library_filename = self.resource_finder.get_filename('urdf/ModularBot.library.urdf.xacro', ['data_path'])\n control_filename = self.resource_finder.get_filename('urdf/ModularBot.control.urdf.xacro', ['data_path'])\n for include in self.root.findall('xacro:include', ns):\n if include.attrib['filename'] == 'ModularBot.library.urdf.xacro':\n include.attrib['filename'] = library_filename\n elif include.attrib['filename'] == 'ModularBot.control.urdf.xacro':\n include.attrib['filename'] = control_filename\n\n self.control_plugin.add_plugin()\n\n else:\n self.root = elementree\n self.urdf_tree = ET.ElementTree(self.root)\n\n self.tag_num = 0\n self.branch_switcher = {\n 0: '',\n 1: '_A',\n 2: '_B',\n 3: '_C',\n 4: '_D',\n 5: '_E',\n 6: '_F',\n 7: '_G',\n 8: '_H',\n 9: '_I',\n 10: '_L',\n 11: '_M',\n 12: '_N',\n 13: '_O',\n 14: '_P',\n 15: '_Q',\n 16: '_R'\n }\n\n self.inverse_branch_switcher = {y: x for x, y in iteritems(self.branch_switcher)}\n\n self.origin, self.xaxis, self.yaxis, self.zaxis = (0, 0, 0.4), (1, 0, 0), (0, 1, 0), (0, 0, 1)\n\n data = {'type': \"base_link\", 'name': \"base_link\", 'kinematics_convention': \"urdf\"}\n\n self.base_link = ModuleNode.ModuleNode(data, \"base_link\")\n setattr(self.base_link, 'name', \"base_link\")\n setattr(self.base_link, 'tag', self.branch_switcher.get(self.tag_num))\n setattr(self.base_link, 'flange_size', '3')\n setattr(self.base_link, 'i', 0)\n setattr(self.base_link, 'p', 0)\n setattr(self.base_link, 'Homogeneous_tf', tf.transformations.identity_matrix())\n setattr(self.base_link, 'robot_id', 0)\n setattr(self.base_link, 'current_port', 1)\n #HACK: base_link does not have ports.\n setattr(self.base_link, 'active_ports', \"0011\")\n setattr(self.base_link, 'occupied_ports', \"0001\")\n setattr(self.base_link, 'connectors', ['connector_0'])\n setattr(self.base_link, 'connector_idx', 1)\n setattr(self.base_link, 'is_structural', False)\n setattr(self.base_link, 'mesh_names', [])\n\n self.listofchains = [[self.base_link]]\n self.listofhubs = []\n\n self.parent_module = self.base_link\n\n # update generator expression\n self.update_generators()\n\n # map between name of the mesh and the module\n self.mesh_to_module_map = {}\n\n self.urdf_string = self.process_urdf()\n\n self.model_stats = ModelStats(self)\n\n # set the slave description mode\n try:\n self.slave_desc_mode = SlaveDescMode(slave_desc_mode)\n except ValueError:\n self.slave_desc_mode = SlaveDescMode.USE_POSITIONS\n self.info_print('Slave description mode not recognized! Defaulting to USE_POSITIONS')\n\n def set_floating_base(self, floating_base):\n \"\"\"Set the floating base flag\"\"\"\n self.floating_base = floating_base\n self.update_default_xacro_mappings()\n\n def update_default_xacro_mappings(self):\n \"\"\"Update the xacro mappings to perform args substitution (see template.urdf.xacro).\n To be called when the floating base status changes.\"\"\"\n if self.floating_base:\n self.default_xacro_mappings['floating_base'] = 'true'\n else:\n self.default_xacro_mappings['floating_base'] = 'false'\n\n def print(self, *args):\n if isinstance(self.logger, logging.Logger):\n self.logger.debug(' '.join(str(a) for a in args))\n else:\n print(args)\n\n def info_print(self, *args):\n if isinstance(self.logger, logging.Logger):\n self.logger.info(' '.join(str(a) for a in args))\n else:\n print(args)\n\n def error_print(self, *args):\n if isinstance(self.logger, logging.Logger):\n self.logger.error(' '.join(str(a) for a in args))\n else:\n print(args)\n\n @staticmethod\n def find_module_from_id(module_id, modules):\n \"\"\"Given the module id find the corresponding dictionary entry and return it\"\"\"\n found_module = None\n for module in modules:\n if module_id in module.keys():\n found_module = module\n break\n else:\n continue\n return found_module\n\n @staticmethod\n def find_next_module_in_chain(module_id, modules):\n \"\"\"Given the module id find the corresponding dictionary entry and return it\"\"\"\n found_module = None\n found_module_id = 0\n next_position = 2 # 1 #TODO: remove this hack for not cosidering pwrboard\n for module in modules:\n if module_id in module.keys():\n position = module[module_id]['position']\n next_position = int(position) + 1\n break\n # print('next position:', next_position)\n for next_module in modules:\n next_id = (next_module.keys())[0]\n if next_module[next_id]['position'] == next_position:\n found_module = next_module\n found_module_id = next_id\n break\n else:\n continue\n return found_module, found_module_id\n\n def sort_modules(self, modules_dict):\n\n ordered_chain = [None] * len(modules_dict)\n\n for key, item in modules_dict.items():\n\n module_position = int(item['position'])\n\n try:\n ordered_chain[module_position - 1] = item\n\n except IndexError:\n self.print('unexpected module position {}, modules number: {}'.format(module_position, len(modules_dict)))\n return list()\n\n return ordered_chain\n\n\n def sort_modules_by_pos(self, modules_dict):\n\n ordered_chain = [None] * len(modules_dict)\n\n for key, item in modules_dict.items():\n\n module_position = key\n\n try:\n ordered_chain[module_position - 1] = item\n \n except IndexError:\n self.print('unexpected module position {}, modules number: {}'.format(module_position, len(modules_dict)))\n return list()\n \n return ordered_chain\n\n\n # This method will be used when branches in the robot will be supported.\n def read_from_json(self, json_data):\n # HACK: we keep track of how many sockets we have to add to insert a default offset\n socket_counter = 0\n\n # If a tree representing the topology was already instantiated, re-initialize and start from scratch\n if self.root != 0:\n self.print(\"Re-initialization\")\n self.__init__(config_file=self.config_file,\n control_plugin=self.control_plugin,\n speedup=self.speedup,\n verbose=self.verbose,\n logger=self.logger,\n slave_desc_mode=self.slave_desc_mode)\n\n robot_id_yaml = self.resource_finder.get_filename('robot_id.yaml')\n robot_id_dict = yaml.safe_load(open(robot_id_yaml, 'r'))\n\n module_params_yaml = self.resource_finder.get_filename('module_params.yaml')\n module_params_dict = yaml.safe_load(open(module_params_yaml, 'r'))\n\n # Process the modules described in the json to create the tree\n modules_dict = yaml.safe_load(json_data)\n \n if self.slave_desc_mode is SlaveDescMode.USE_POSITIONS:\n # Sort the modules by position\n modules_list = self.sort_modules_by_pos(modules_dict)\n elif self.slave_desc_mode is SlaveDescMode.USE_IDS:\n # Sort the modules by id\n modules_list = self.sort_modules(modules_dict)\n else:\n raise ValueError('Slave description mode not recognized!')\n\n for module in modules_list:\n\n module_position = int(module['position'])\n module['robot_id'] = int(module['robot_id']) if module['robot_id'] != -1 else module_position*(-1)\n robot_id = module['robot_id']\n active_ports = int(module['active_ports'])\n\n mod_type = int(module['mod_type'])\n mod_id = int(module['mod_id'])\n mod_size = int(module['mod_size'])\n mod_rev = int(module['mod_rev'])\n\n module_filename = module_params_dict.get(mod_type, {}).get(mod_id,{}).get(mod_size,{}).get(mod_rev)\n if module_filename is None:\n module_filename = robot_id_dict.get(robot_id)\n if module_filename is None:\n self.info_print(\"Id not recognized! Skipping add_module() for id\", robot_id_dict.get(robot_id)) \n continue\n\n self.info_print('Discovered module with ID:', robot_id)\n\n parent_position = None\n\n # find parent (from OpenEtherCATsociety)\n if (module_position > 1):\n topo_counter = 0\n candidate_position = module_position - 1\n\n while candidate_position > 0:\n candidate_parent = modules_list[candidate_position - 1]\n topology = int(candidate_parent['topology'])\n\n if topology == 1:\n topo_counter -= 1\n elif topology == 3:\n topo_counter += 1\n elif topology == 4:\n topo_counter += 2\n\n if (topo_counter >= 0 and topology > 1) or candidate_position == 1:\n # parent found\n parent_position = candidate_position\n candidate_position = 1\n\n candidate_position -= 1\n\n self.print(\"module and parent:\", robot_id, parent_position)\n\n # select the correct parent module\n if parent_position :\n parent = modules_list[parent_position -1]\n self.print('parent:', parent)\n \n parent_id = int(parent['robot_id'])\n self.print('parent_id:', parent_id)\n\n parent_active_ports = int(parent['active_ports'])\n self.print('parent_active_ports:', parent_active_ports)\n\n parent_topology = int(parent['topology'])\n self.print('parent_topology:', parent_topology)\n\n # select the correct parent module from its id and sets the correct current port\n self.select_module_from_id(parent_id)\n\n # set the current_port as occupied\n mask = 1 << self.eth_to_physical_port_idx(self.parent_module.current_port)\n self.print(mask)\n self.print(self.parent_module.occupied_ports)\n self.parent_module.occupied_ports = \"{0:04b}\".format(int(self.parent_module.occupied_ports, 2) | mask)\n self.print(self.parent_module.occupied_ports)\n\n #HACK: If the parent is a cube to support non-structural box we add a socket\n if self.parent_module.type is ModuleType.CUBE:\n if not self.parent_module.is_structural:\n self.add_module('socket.yaml', {'x': float(socket_counter)}, reverse=False)\n socket_counter += 1\n\n # HACK: manually set name of mobile platform to be 'mobile_base', instead of auto-generated name\n module_name = None\n if module_filename=='concert/mobile_platform_concert.json':\n module_name = 'mobile_base'\n\n #add the module\n data = self.add_module(module_filename, {}, reverse=False, robot_id=robot_id, active_ports=active_ports, module_name=module_name)\n \n ## HACK: Manually add passive end effector for now!\n # self.add_simple_ee(0.0, 0.0, 0.135, mass=0.23)\n # data = self.add_module('concert/passive_end_effector_panel.json', {}, False)\n # data = self.add_module('experimental/passive_end_effector_pen.json', {}, False)\n\n self.urdf_string = self.process_urdf()\n\n self.info_print(\"Discovery completed\")\n\n data = {'string': self.urdf_string}\n return data\n\n def render_tree(self):\n for pre, _, node in RenderTree(self.base_link):\n self.print(pre, node, node.name, node.robot_id)\n\n return 0\n\n def read_file(self, file_str):\n \"\"\"Open the URDF chosen from the front-end and import it as a ElemenTree tree\"\"\"\n # global root, urdf_tree\n self.print(file_str)\n self.root = ET.fromstring(file_str.encode('utf-8'))\n self.urdf_tree = ET.ElementTree(self.root)\n self.print(ET.tostring(self.urdf_tree.getroot()))\n\n # include files necessary for Gazebo&XBot simulation\n # ET.SubElement(root, \"xacro:include\", filename=\"$(find modular)/urdf/config.xacro\")\n # ET.SubElement(root, \"xacro:include\", filename=\"$(find modular)/urdf/modular.gazebo\")\n\n doc = xacro.parse(file_str.encode('utf-8'))\n xacro.process_doc(doc, in_order=True)\n string = doc.toprettyxml(indent=' ')\n\n data = {'string': string}\n return data\n\n def process_urdf(self, xacro_mappings={}):\n \"\"\"Process the urdf to convert from xacro and perform macro substitutions. Returns urdf string\"\"\"\n\n # write the urdf tree to a string\n xmlstr = xml.dom.minidom.parseString(ET.tostring(self.urdf_tree.getroot())).toprettyxml(indent=\" \")\n # self.print(xmlstr)\n\n # parse the string to convert from xacro\n doc = xacro.parse(xmlstr)\n\n # mappings = self.default_xacro_mappings if xacro_mappings else xacro_mappings\n mappings = copy.deepcopy(self.default_xacro_mappings)\n mappings.update(xacro_mappings)\n\n # perform macro replacement\n xacro.process_doc(doc, mappings=mappings)\n\n # string = doc.toprettyxml(indent=' ')\n string = doc.toprettyxml(indent=' ', encoding='utf-8').decode('utf-8')\n\n return string\n\n def add_to_chain(self, new_joint):\n \"\"\"Add joint to one of the robot kinematic chains\n\n Parameters\n ----------\n new_joint: ModuleNode.ModuleNode\n New ModuleNode object representing a joint to be added to a kinematic chain\"\"\"\n\n # get tag_index, an integer representing on which branch of the robot the joint has been added\n tag_index = self.inverse_branch_switcher.get(new_joint.tag)\n parent_tag_index = self.inverse_branch_switcher.get(new_joint.parent.tag)\n chain = [new_joint]\n self.print(\"tag_index: \", tag_index, \"list of chains: \", len(self.listofchains))\n # if tag_index (offseted by one, since now we start from 0) is bigger than the length of the list of chains, it means this chain hasn't been added yet.\n # then we need to append a new list representing the new chain formed by the new joint only\n if tag_index > parent_tag_index:\n self.listofchains.append(chain)\n # if instead tag_index is not bigger it means the chain the new joint is part of has already beeen added.\n # then the new joint is appended to the list representing the chain it's part of.\n else:\n self.listofchains[tag_index].append(new_joint)\n\n def remove_from_chain(self, joint):\n \"\"\"Remove joint from the list of the robot kinematic chains\n\n Parameters\n ----------\n joint: ModuleNode.ModuleNode\n ModuleNode object representing a joint to be removed to a kinematic chain\"\"\"\n\n for chain in self.listofchains:\n if joint in chain:\n chain.remove(joint)\n self.listofchains = list(filter(None, self.listofchains))\n\n def get_actuated_modules_chains(self):\n active_modules_chains = []\n for modules_chain in self.listofchains:\n # check number of joints and active modules in the chain. \n joint_num = 0\n for joint_module in modules_chain:\n if joint_module.type in ModuleClass.actuated_modules():\n joint_num += 1\n # If 0, skip it. The chain doesn't need to be added to the srdf in this case.\n if joint_num == 0:\n continue\n else:\n active_modules_chains.append(modules_chain)\n return active_modules_chains\n\n def get_ET(self):\n return self.urdf_tree\n\n def get_parent_module(self):\n return self.parent_module\n \n @staticmethod\n def find_chain_tip_link(chain):\n if chain[-1].type in ModuleClass.joint_modules():\n tip_link = chain[-1].distal_link_name\n elif chain[-1].type in ModuleClass.link_modules() | ModuleClass.hub_modules():\n tip_link = chain[-1].name\n elif chain[-1].type in ModuleClass.end_effector_modules() - {ModuleType.DAGANA}:\n tip_link = chain[-1].tcp_name\n elif chain[-1].type is ModuleType.DAGANA:\n tip_link = chain[-1].dagana_link_name\n return tip_link\n \n @staticmethod\n def find_chain_base_link(chain):\n if not chain[0].parent:\n base_link = chain[0].name\n if \"con_\" in chain[0].parent.name:\n base_link = chain[0].parent.parent.name\n else:\n if not chain[0].parent.is_structural and chain[0].parent.type in ModuleClass.hub_modules():\n base_link = chain[0].parent.parent.name\n else:\n base_link = chain[0].parent.name\n return base_link\n\n @staticmethod\n def find_chain_tag(chain):\n return chain[-1].tag \n\n def update_generators(self):\n # Generator expression for list of urdf elements without the gazebo tag.\n # This is needed because of the change in the xacro file, as gazebo simulation tags\n # are now added from the start and this creates problems with the search\n nodes = set(self.root.findall(\"*\"))\n gazebo_nodes = set(self.root.findall(\"./gazebo\"))\n xacro_include_nodes = set(self.root.findall('./xacro:include', ns))\n xacro_if_nodes = set(self.root.findall('./xacro:if', ns))\n # xacro_macro_nodes = set(self.root.findall('./xacro:macro', ns))\n xacro_property_nodes = set(self.root.findall('./xacro:property', ns))\n xacro_arg_nodes = set(self.root.findall('./xacro:arg', ns))\n filtered_nodes = nodes.difference(gazebo_nodes).difference(xacro_include_nodes).difference(xacro_if_nodes).difference(xacro_property_nodes).difference(xacro_arg_nodes)\n self.urdf_nodes_generator = (node for node in filtered_nodes)\n self.gazebo_nodes_generator = (node for node in gazebo_nodes)\n\n # Adds a table for simulation purposes\n def add_table(self):\n data = {'type': \"link\", 'name': \"table\"}\n\n table = ModuleNode.ModuleNode(data, \"table\", parent=self.base_link)\n setattr(table, 'name', \"table\")\n setattr(table, 'tag', \"_A\")\n setattr(table, 'flange_size', 3)\n setattr(table, 'i', 0)\n setattr(table, 'p', 0)\n setattr(table, 'Homogeneous_tf', tf.transformations.identity_matrix())\n setattr(table, 'robot_id', 0)\n\n ET.SubElement(self.root,\n \"xacro:add_table\",\n type=\"link\",\n name=\"table\",\n father=self.parent_module.name)\n\n self.collision_elements.append((self.parent_module.name, \"table\"))\n\n self.parent_module = table\n\n # Select the current connector of the new module\n selected_connector = self.select_connector(table)\n # Select the meshes to highlight in the GUI\n selected_meshes = self.select_meshes(selected_connector, table)\n\n if self.speedup:\n self.urdf_string = \"\"\n else:\n # Process the urdf string by calling the process_urdf method. Parse, convert from xacro and write to string\n self.urdf_string = self.process_urdf()\n\n # Create the dictionary with the relevant info on the selected module, so that the GUI can dispaly it.\n data = {'name': table.name,\n 'type': table.type,\n 'flange_size': table.flange_size,\n 'selected_connector': selected_connector,\n 'selected_meshes': selected_meshes,\n 'urdf_string': self.urdf_string}\n\n return data\n \n def add_drillbit(self, length=0.27, radius=0.012, mass=0.1):\n drillbit_name = 'drillbit'+ self.parent_module.tag\n ET.SubElement(self.root,\n \"xacro:add_cylinder\",\n type=\"drillbit\",\n name=drillbit_name,\n size_z=str(length),\n mass=str(mass),\n radius=str(radius))\n self.parent_module.mesh_names.append(drillbit_name)\n\n trasl = tf.transformations.translation_matrix((0.0, 0.0, length))\n rot = tf.transformations.euler_matrix(0.0, 0.0, 0.0, 'sxyz')\n transform = ModuleNode.get_rototranslation(trasl, rot)\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(transform)\n\n father_name = self.parent_module.tcp_name\n\n ET.SubElement(self.root,\n \"xacro:add_fixed_joint\",\n type=\"fixed_joint\",\n name=\"fixed_\" + drillbit_name,\n father=father_name,\n child=drillbit_name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n \n self.collision_elements.append((father_name, drillbit_name))\n\n if self.speedup:\n self.urdf_string = \"\"\n else:\n # Process the urdf string by calling the process_urdf method. Parse, convert from xacro and write to string\n self.urdf_string = self.process_urdf()\n\n return [drillbit_name, \"fixed_\" + drillbit_name]\n\n def add_handle(self, x_offset=0.0, y_offset=0.25, z_offset=-0.18, mass=0.330, radius=0.025):\n handle_name = 'handle'+ self.parent_module.tag\n ET.SubElement(self.root,\n \"xacro:add_cylinder\",\n type=\"drillbit\",\n name=handle_name,\n size_z=str(abs(y_offset)),\n mass=str(mass),\n radius=str(radius))\n self.parent_module.mesh_names.append(handle_name)\n\n trasl = tf.transformations.translation_matrix((x_offset, y_offset, z_offset))\n if y_offset >= 0.0:\n rot = tf.transformations.euler_matrix(-1.57, 0.0, 0.0, 'sxyz')\n else:\n rot = tf.transformations.euler_matrix(1.57, 0.0, 0.0, 'sxyz')\n transform = ModuleNode.get_rototranslation(trasl, rot)\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(transform)\n\n father_name = self.parent_module.tcp_name\n\n ET.SubElement(self.root,\n \"xacro:add_fixed_joint\",\n type=\"fixed_joint\",\n name=\"fixed_\" + handle_name,\n father=father_name,\n child=handle_name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n \n self.collision_elements.append((father_name, handle_name))\n\n # Add also a frame on the handle gripping point\n trasl = tf.transformations.translation_matrix((0.0, y_offset/2, z_offset))\n rot = tf.transformations.euler_matrix(0.0, 0.0, 0.0, 'sxyz')\n transform = ModuleNode.get_rototranslation(trasl, rot)\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(transform)\n\n handle_gripping_point_name = 'handle_gripping_point'+ self.parent_module.tag\n ET.SubElement(self.root,\n \"xacro:add_fixed_joint\",\n type=\"fixed_joint\",\n name=\"fixed_\" + handle_gripping_point_name,\n father=father_name,\n child=handle_gripping_point_name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n \n ET.SubElement(self.root,\n \"link\",\n name=handle_gripping_point_name)\n\n if self.speedup:\n self.urdf_string = \"\"\n else:\n # Process the urdf string by calling the process_urdf method. Parse, convert from xacro and write to string\n self.urdf_string = self.process_urdf()\n\n return [handle_name, \"fixed_\" + handle_name, handle_gripping_point_name, \"fixed_\" + handle_gripping_point_name]\n\n # Add a cylinder as a fake end-effector\n def add_simple_ee(self, x_offset=0.0, y_offset=0.0, z_offset=0.0, angle_offset=0.0, mass=1.0, radius=0.02):\n # TODO: treat this as a link in the link_after_* methods!\n data = {'type': \"simple_ee\", 'name': \"simple_ee\", 'kinematics_convention': \"urdf\"}\n\n simple_ee = ModuleNode.ModuleNode(data, \"simple_ee\", parent=self.parent_module)\n setattr(simple_ee, 'tag', self.parent_module.tag)\n setattr(simple_ee, 'flange_size', self.parent_module.flange_size)\n setattr(simple_ee, 'i', self.parent_module.i)\n setattr(simple_ee, 'p', self.parent_module.p+1)\n setattr(simple_ee, 'robot_id', 0)\n setattr(simple_ee, 'name', 'ee' + self.parent_module.tag)\n\n ET.SubElement(self.root,\n \"xacro:add_cylinder\",\n type=\"simple_ee\",\n name=simple_ee.name,\n size_z=str(z_offset),\n mass=str(mass),\n radius=str(radius))\n\n try:\n self.add_gazebo_element(simple_ee, simple_ee.gazebo.body_1, simple_ee.name)\n except AttributeError:\n pass\n\n trasl = tf.transformations.translation_matrix((x_offset, y_offset, z_offset))\n rot = tf.transformations.euler_matrix(0.0, 0.0, angle_offset, 'sxyz')\n rototrasl = ModuleNode.get_rototranslation(trasl, rot)\n setattr(simple_ee, 'Homogeneous_tf', rototrasl)\n\n if self.parent_module.type is ModuleType.JOINT:\n transform = ModuleNode.get_rototranslation(self.parent_module.Distal_tf, rototrasl)\n else:\n transform = ModuleNode.get_rototranslation(self.parent_module.Homogeneous_tf, rototrasl)\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(transform)\n\n fixed_joint_name = 'L_' + str(simple_ee.i) + '_fixed_joint_' + str(simple_ee.p) + simple_ee.tag\n\n if self.parent_module.type is ModuleType.JOINT:\n father_name = 'L_' + str(self.parent_module.i) + self.parent_module.tag\n else:\n father_name = self.parent_module.name\n\n ET.SubElement(self.root,\n \"xacro:add_fixed_joint\",\n type=\"fixed_joint\",\n name=fixed_joint_name,\n father=father_name,\n child=simple_ee.name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n\n self.collision_elements.append((father_name, simple_ee.name))\n\n self.add_to_chain(simple_ee)\n \n self.parent_module = simple_ee\n\n # Select the current connector of the new module\n selected_connector = self.select_connector(simple_ee)\n # Select the meshes to highlight in the GUI\n selected_meshes = self.select_meshes(selected_connector, simple_ee)\n\n if self.speedup:\n self.urdf_string = \"\"\n else:\n # Process the urdf string by calling the process_urdf method. Parse, convert from xacro and write to string\n self.urdf_string = self.process_urdf()\n\n # Create the dictionary with the relevant info on the selected module, so that the GUI can dispaly it.\n data = {'name': simple_ee.name,\n 'type': simple_ee.type,\n 'flange_size': simple_ee.flange_size,\n 'selected_connector': selected_connector,\n 'selected_meshes': selected_meshes,\n 'urdf_string': self.urdf_string} \n\n return data\n\n\n def add_wheel_module(self, wheel_filename, steering_filename, offsets={}, reverse=False, robot_id=(0,0)):\n steering_data = self.add_module(steering_filename, offsets, reverse, robot_id=robot_id[0])\n wheel_data = self.add_module(wheel_filename, offsets, reverse, robot_id=robot_id[1])\n\n return wheel_data, steering_data\n \n\n def add_addon(self, addon_filename):\n new_addon = None\n try:\n addons_dict = self.modular_resources_manager.get_available_addons_dict()\n new_addon = addons_dict[addon_filename]\n if new_addon['header']['type'] == 'drillbit':\n self.parent_module.addon_elements += self.add_drillbit(length=new_addon['parameters']['length'], radius=new_addon['parameters']['radius'], mass=new_addon['parameters']['mass'])\n elif new_addon['header']['type'] == 'handle':\n self.parent_module.addon_elements += self.add_handle(x_offset=new_addon['parameters']['x_offset'], y_offset=new_addon['parameters']['y_offset'], z_offset=new_addon['parameters']['z_offset'], mass=new_addon['parameters']['mass'], radius=new_addon['parameters']['radius'])\n else:\n self.logger.info('Addon type not supported')\n\n except FileNotFoundError:\n raise FileNotFoundError(addon_filename+' was not found in the available resources')\n\n\n def add_module(self, filename, offsets={}, reverse=False, addons =[], robot_id=0, active_ports=3, is_structural=True, module_name=None):\n \"\"\"Add a module specified by filename as child of the currently selected module.\n\n Parameters\n ----------\n filename: str\n String with the name of the YAML file to load, describing the module parameters\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n reverse: bool\n Bool value expressing if the module is mounted in reverse direction (true) or in standard one (false).\n By default it is false.\n Not used for hub types (cube, mobile base, etc.).\n robot_id: int\n Value of the robot_id set in the firmware of the module.\n This is obtained in Discovery Mode when reading the JSON from the EtherCAT master. This is not used when in Bulding Mode.\n active_ports: int\n The number of active ports of the module (how many ports have established a connection to a module).\n This is the integer conversion of the 4-bit binary string where each bit represent one port (1 if port is active, 0 if port is unactive)\n is_structural: bool\n Bool value expressing if the module is structural (true) or not (false).\n Used only for hub types (cube, mobile base, etc.).\n\n Returns\n -------\n data: dict\n Dictionary with as entries all the relevant info on the newly added module.\n In particular the updated and newly processed urdf string.\n\n \"\"\"\n # global tag, parent_module\n self.print(path_name)\n self.print(filename)\n\n try:\n module_dict = self.modular_resources_manager.get_available_modules_dict()[filename]\n template_dict = self.modular_resources_manager.get_available_modules_dict()['template.yaml']\n if filename.lower().endswith(('.yaml', '.yml')):\n # Load the module from YAML and create a ModuleNode instance\n new_module = ModuleNode.module_from_yaml_dict(module_dict, self.parent_module, template_dict, reverse)\n self.print(\"Module loaded from YAML: \" + new_module.name)\n elif filename.lower().endswith(('.json')):\n # Load the module from YAML and create a ModuleNode instance\n new_module = ModuleNode.module_from_json_dict(module_dict, self.parent_module, template_dict, reverse)\n self.print(\"Module loaded from JSON: \" + new_module.name)\n except KeyError:\n raise KeyError(filename+' was not found in the available resources')\n\n # Socket module is a custom type. It behaves differently from other link modules because it has no electronics onboard. Its parent should always be the base_link. On the hardware it will actually be connected to a non-structural hub, which therefore will not be part of the URDF, so we consider the base_link to be the parent in any case. This means the ports of the hub will not actually be occupied, so potentially there is no limit to how many sockets could be connected (>3).\n if new_module.type is ModuleType.SOCKET:\n self.parent_module = new_module.parent = self.base_link\n\n # If the parent is a hub module, it means we are starting a new branch.\n # Then assign the correct tag (A, B, C, ...) to the new module (and therefore start a new branch)\n # by looking at the current tag_num (1, 2, 3, ...) and so at how many branches are already present in the robot.\n # If the parent is any other kind of module, assign as tag the same of his parent.\n if (\n self.parent_module.type in ModuleClass.hub_modules() | {ModuleType.BASE_LINK} \n and new_module.type not in ModuleClass.hub_modules()\n ):\n self.tag_num += 1\n tag_letter = self.branch_switcher.get(self.tag_num)\n setattr(new_module, 'tag', tag_letter)\n else:\n setattr(new_module, 'tag', self.parent_module.tag)\n\n self.print('new_module.tag:', new_module.tag)\n\n # Set attributes of the newly added module object\n setattr(new_module, 'i', self.parent_module.i)\n setattr(new_module, 'p', self.parent_module.p)\n # flange_size is already set from the YAML file\n # setattr(new_module, 'flange_size', self.parent_module.flange_size)\n\n setattr(new_module, 'offsets', offsets)\n setattr(new_module, 'reverse', reverse)\n setattr(new_module, 'robot_id', robot_id)\n\n # Attribute specifying if the module is structural or not. Useful for those types of modules that are not structural (e.g. hubs), in particular if they are present in the network and discovered by EtherCAT, but they are not part of the robot structure.\n if hasattr(new_module.header, 'is_structural'):\n setattr(new_module, 'is_structural', new_module.header.is_structural)\n else:\n # if the attribute is not present, set it, otherwise leave it as it is (it has been set from the YAML/JSON file)\n setattr(new_module, 'is_structural', is_structural)\n\n self.print(\"parent module:\", self.parent_module.name, \", type :\", self.parent_module.type)\n\n # Update the EtherCAT port connected to the electro-mechanical interface where the new module/slave will be added \n #################################################\n # non-hub modules:\n # 1 2 3 4\n # o o o o\n # | | | |\n # input port output port nothing nothing\n #################################################\n # cube modules:\n # 1 2 3 4\n # o o o o\n # | | | |\n # com-exp upper port front port nothing\n #################################################\n setattr(new_module, 'current_port', 1)\n self.print('new_module.current_port :', new_module.current_port)\n\n # save the active ports as a binary string\n setattr(new_module, 'active_ports', \"{0:04b}\".format(active_ports))\n self.print('active_ports: ', new_module.active_ports)\n\n # save the occupied ports as a binary string\n setattr(new_module, 'occupied_ports', \"0001\")\n self.print('occupied_ports: ', new_module.occupied_ports)\n\n # add list of addons as attribute\n setattr(new_module, 'addon_elements', [])\n\n # add list of urdf elements as attribute\n setattr(new_module, 'xml_tree_elements', [])\n\n # add list of xml elements with an associated visual mesh as attribute\n setattr(new_module, 'mesh_names', [])\n\n # add list of connectors names as attribute. The 0 connector is added by default. The others will be added by the add_connectors() method\n setattr(new_module, 'connectors', ['connector_0'])\n\n # For certain types of modules, the model is considered as floating base, i.e. the base_link is not fixed to the world frame, but is connected through a floating joint.\n # WARNING: this changes the behavior of the whole URDF not only for this module\n if new_module.type in {'mobile_base'}:\n self.set_floating_base(True)\n\n # Depending on the type of the parent module and the new module, call the right method to add the new module.\n # Add the module to the correct chain via the 'add_to_chain' method.\n if self.parent_module.type == 'joint':\n if new_module.type in { 'joint', 'wheel' }:\n # joint + joint\n self.print(\"joint + joint\")\n self.joint_after_joint(new_module, self.parent_module, offsets=offsets, reverse=reverse)\n elif new_module.type in { 'cube', 'mobile_base' }:\n # joint + hub\n self.print(\"joint + hub\")\n self.hub_after_joint(new_module, self.parent_module, offsets=offsets, reverse=reverse, module_name=module_name)\n else:\n # joint + link\n self.print(\"joint + link\")\n self.link_after_joint(new_module, self.parent_module, offsets=offsets, reverse=reverse)\n elif self.parent_module.type == 'wheel':\n # TODO: prevent adding modules after wheels in a better way (raise exception?)\n return {'result': 'ERROR: module cannot be added after wheel module. Select another chain or remove the wheel module.'}\n elif self.parent_module.type in {'cube', \"mobile_base\"}:\n if new_module.type in { 'joint', 'wheel' }:\n # hub + joint\n self.print(\"hub + joint\")\n self.joint_after_hub(new_module, self.parent_module, offsets=offsets, reverse=reverse)\n elif new_module.type in { 'cube', 'mobile_base' }:\n # hub + hub\n self.print(\"hub + hub\")\n self.hub_after_hub(new_module, self.parent_module, offsets=offsets, reverse=reverse, module_name=module_name)\n else:\n # hub + link\n self.print(\"hub + link\")\n self.link_after_hub(new_module, self.parent_module, offsets=offsets, reverse=reverse)\n else:\n if new_module.type in { 'joint', 'wheel' }:\n # link + joint\n self.print(\"link + joint\")\n self.joint_after_link(new_module, self.parent_module, offsets=offsets, reverse=reverse)\n elif new_module.type in { 'cube', 'mobile_base' }:\n # link + hub\n self.print(\"link + hub\")\n self.hub_after_link(new_module, self.parent_module, offsets=offsets, reverse=reverse, module_name=module_name)\n else:\n # link + link\n self.print(\"link + link\")\n self.link_after_link(new_module, self.parent_module, offsets=offsets, reverse=reverse)\n\n # # TODO: check if this is correct\n # # Add the module to the list of chains if there is at least a joint before it\n # if new_module.i > 0:\n # self.add_to_chain(new_module)\n self.add_to_chain(new_module)\n\n # Update the parent_module attribute of the URDF_writer class\n self.parent_module = new_module\n\n # Select the current connector of the new module\n selected_connector = self.select_connector(new_module, port_idx=new_module.current_port)\n # Select the meshes to highlight in the GUI\n selected_meshes = self.select_meshes(selected_connector, new_module)\n\n for addon in addons:\n try:\n self.add_addon(addon_filename=addon)\n except FileNotFoundError:\n self.logger.error(f'Addon {addon} not found, skipping it')\n\n # add meshes to the map\n self.mesh_to_module_map.update({k: new_module.name for k in new_module.mesh_names})\n\n if self.speedup:\n self.urdf_string = \"\"\n else:\n # Process the urdf string by calling the process_urdf method. Parse, convert from xacro and write to string\n self.urdf_string = self.process_urdf()\n\n # update the urdf file, adding the new module\n # string = write_urdf(path_name + '/urdf/ModularBot_test.urdf', urdf_tree)\n\n if self.verbose:\n # Render tree\n for pre, _, node in anytree.render.RenderTree(self.base_link):\n self.print(\"%s%s: %d\" % (pre, node.name, node.robot_id))\n\n # Create a dictionary containing the urdf string just processed and other parameters needed by the web app\n data = {'name': new_module.name,\n 'type': new_module.type,\n 'flange_size': new_module.flange_size,\n 'selected_connector': selected_connector,\n 'selected_meshes': selected_meshes,\n 'urdf_string': self.urdf_string} \n\n self.info_print(\"Module added to URDF: \" + new_module.name + \" (\" + new_module.type + \")\")\n\n return data\n\n def add_gazebo_element(self, new_module_obj, gazebo_obj, new_module_name):\n \"\"\"\n Add a gazebo element to the new module\n \"\"\"\n # Add the gazebo element to the new module\n if gazebo_obj is not None:\n gazebo_el_name = 'gazebo_' + new_module_name\n gazebo_if_el = ET.SubElement(self.root,\n 'xacro:xacro_if_guard',\n value=\"${GAZEBO_URDF}\",\n name = gazebo_el_name)\n new_module_obj.xml_tree_elements.append(gazebo_el_name)\n \n gazebo_el = ET.SubElement(gazebo_if_el,\n 'gazebo',\n reference=new_module_name)\n self.add_gazebo_element_children(gazebo_obj, gazebo_el)\n\n\n def add_gazebo_element_children(self, gazebo_child_obj, gazebo_element):\n \"\"\"\n Add the gazebo element children to the new module\n \"\"\"\n for key, value in vars(gazebo_child_obj).items():\n gazebo_child_el = ET.SubElement(gazebo_element, key)\n if isinstance(value, ModuleNode.Module.Attribute):\n self.add_gazebo_element_children(value, gazebo_child_el)\n else:\n gazebo_child_el.text = str(value)\n\n \n def update_module(self, selected_module=0, offsets={}, reverse=False, addons=[]):\n if selected_module == 0:\n selected_module = (self.parent_module)\n # If the selected module is a connector module, select his parent (the hub) instead\n if '_con' in selected_module.name:\n selected_module = selected_module.parent\n\n self.info_print('Updating module: ' + str(selected_module.name))\n \n # Update generator expression\n self.update_generators()\n\n # Update offsets. MEMO: to be fixed! must apply offsets not overwrite\n for node in self.urdf_nodes_generator:\n try:\n if node.attrib['name'] == selected_module.fixed_joint_name:\n for key in offsets.keys():\n node.set(key, str(offsets[key]))\n except (KeyError, AttributeError):\n pass\n\n # update generator expression\n self.update_generators()\n\n # remove addons\n if(getattr(selected_module, 'addon_elements')):\n for node in self.urdf_nodes_generator:\n try:\n if node.attrib['name'] in selected_module.addon_elements:\n # remove mesh from list of meshes and from the map\n if node.attrib['name'] in selected_module.mesh_names:\n selected_module.mesh_names.remove(node.attrib['name'])\n self.mesh_to_module_map.pop(node.attrib['name'])\n # remove node from tree\n self.root.remove(node)\n except KeyError:\n pass\n\n for addon in addons:\n try:\n self.add_addon(addon_filename=addon)\n except FileNotFoundError:\n self.logger.error(f'Addon {addon} not found, skipping it')\n\n self.mesh_to_module_map.update({k: selected_module.name for k in selected_module.mesh_names})\n\n # Select the current connector of the new module\n selected_connector = self.select_connector(selected_module, port_idx=selected_module.current_port)\n # Select the meshes to highlight in the GUI\n selected_meshes = self.select_meshes(selected_connector, selected_module)\n\n if self.speedup:\n self.urdf_string = \"\"\n else:\n # Process the urdf string by calling the process_urdf method. Parse, convert from xacro and write to string\n # Update the urdf file, removing the module\n self.urdf_string = self.process_urdf()\n\n # Create a dictionary containing the urdf string just processed and other parameters needed by the web app\n data = {'name': selected_module.name,\n 'type': selected_module.type,\n 'flange_size': selected_module.flange_size,\n 'selected_connector': selected_connector,\n 'selected_meshes': selected_meshes,\n 'urdf_string': self.urdf_string} \n \n return data\n\n\n def remove_module(self, selected_module=0):\n \"\"\"Remove the selected module (and all its childs and descendants) and return info on its parent\n\n Parameters\n ----------\n selected_module: ModuleNode.ModuleNode\n NodeModule object of the module to remove. Default value is 0, in which case the current parent_module is selected as the module to be removed.\n\n Returns\n -------\n data: dict\n Dictionary with as entries all the relevant info on the parent module of the removed module.\n In particular the updated and newly processed urdf string, so without the removed modules.\n\n \"\"\"\n # If no selected_module argument was passed to the method,\n # select the current parent module to be the one to remove\n if selected_module == 0:\n selected_module = (self.parent_module)\n\n self.info_print('Removing module: ' + str(selected_module.name) + ' (and all its descendants)')\n\n # Remove the module childs and its descendants recursively\n for child in selected_module.children:\n self.print('eliminate child: ' + child.name + ' of type: ' + child.type + ' of parent: ' + selected_module.name)\n self.remove_module(child)\n\n # update generator expression\n self.update_generators()\n\n xml_elements_to_remove = []\n # remove addons\n if(getattr(selected_module, 'addon_elements')):\n xml_elements_to_remove += selected_module.addon_elements\n # remove module xml elements\n if(getattr(selected_module, 'xml_tree_elements')):\n xml_elements_to_remove += selected_module.xml_tree_elements\n \n # remove all required xml elements from the tree\n for node in self.urdf_nodes_generator:\n try:\n if node.attrib['name'] in xml_elements_to_remove:\n # remove mesh from list of meshes and from the map\n if node.attrib['name'] in selected_module.mesh_names:\n selected_module.mesh_names.remove(node.attrib['name'])\n self.mesh_to_module_map.pop(node.attrib['name'])\n # remove node from tree\n self.root.remove(node)\n except KeyError:\n pass\n\n # save parent of the module to remove. This will be the last element of the chain after removal,\n # and its data will be returned by the function\n father = selected_module.parent\n\n # remove the module from the list of chains\n self.remove_from_chain(selected_module)\n\n # switch depending on module type\n if selected_module.type in ModuleClass.joint_modules():\n self.control_plugin.remove_joint(selected_module.name)\n\n elif selected_module.type is ModuleType.GRIPPER:\n # TO BE FIXED: ok for ros_control. How will it be for xbot2?\n self.control_plugin.remove_joint(selected_module.name+'_finger_joint1')\n self.control_plugin.remove_joint(selected_module.name+'_finger_joint2')\n\n elif selected_module.type in ModuleClass.hub_modules():\n # if the module is a hub, remove it from the list of hubs\n self.listofhubs.remove(selected_module)\n\n # if the parent module is a hub, decrease the tag number. A chain has been removed, tag should be reset accordingly\n if (\n father.type in ModuleClass.hub_modules() | {ModuleType.BASE_LINK} \n and selected_module.type not in ModuleClass.hub_modules()\n ):\n self.tag_num -= 1\n\n if self.speedup:\n self.urdf_string = \"\"\n else:\n # Process the urdf string by calling the process_urdf method. Parse, convert from xacro and write to string\n # Update the urdf file, removing the module\n self.urdf_string = self.process_urdf()\n\n # Update the parent_module attribute of the URDF_writer class\n self.parent_module = father\n\n # Select the current connector of the new module\n selected_connector = self.select_connector(father, port_idx=self.connector_to_port_idx(father.connector_idx, father))\n # Select the meshes to highlight in the GUI\n selected_meshes = self.select_meshes(selected_connector, father)\n \n\n # Create a dictionary containing the urdf string just processed and other parameters needed by the web app\n data = {'name': father.name,\n 'type': father.type,\n 'flange_size': father.flange_size,\n 'selected_connector': selected_connector,\n 'selected_meshes': selected_meshes,\n 'urdf_string': self.urdf_string} \n\n # before deleting selected_module set his parent property to None. Otherwise this will mess up the obj tree\n selected_module.parent = None\n\n # delete object selected_module\n del selected_module\n\n if self.verbose:\n # Render tree\n for pre, _, node in anytree.render.RenderTree(self.base_link):\n self.print(\"%s%s\" % (pre, node.name))\n\n return data\n\n def access_module_by_id(self, queried_module_id):\n \"\"\"Find the selected module object by searching its ID in the tree and returns it. Moreover, sets it as the current parent_module.\n\n Parameters\n ----------\n queried_module_id: int\n The id of the module to access. It will be used to search the tree and find the relative ModuleNode object\n\n Returns\n -------\n last_module: ModuleNode.ModuleNode\n The object of the module with the id as passed by the arg.\n\n \"\"\"\n # global parent_module\n self.print('queried_module_id: ', queried_module_id)\n\n # Serch the tree by id for the selected module\n queried_module = anytree.search.findall_by_attr(self.base_link, queried_module_id, name='robot_id')[0]\n\n self.print('queried_module.type: ', queried_module.type)\n\n # Update parent_module attribute\n self.parent_module = queried_module\n\n return queried_module\n\n def access_module_by_name(self, queried_module_name):\n \"\"\"Find the selected module object in the tree and returns it. Moreover, sets it as the current parent_module.\n\n Parameters\n ----------\n queried_module_name: str\n String with the name of the module to access. It will be used to search the tree and find the relative ModuleNode object\n\n Returns\n -------\n last_module: ModuleNode.ModuleNode\n The object of the module with the name as passed by the arg.\n\n \"\"\"\n # global parent_module\n self.print('queried_module_name: ', queried_module_name)\n\n # Serch the tree by name for the selected module\n queried_module = anytree.search.findall_by_attr(self.base_link, queried_module_name)[0]\n\n self.print('queried_module.type: ', queried_module.type)\n\n # Update parent_module attribute\n self.parent_module = queried_module\n\n return queried_module\n \n def select_module_from_id(self, id, current_port=None):\n \"\"\"Allows to select a module from the tree. An inner call to access_module_by_id sets the selected module as the\n current parent module. Returns info on the selected module, so that the GUI can display it.\n\n Parameters\n ----------\n id: int\n The id of the module to select. It will be used to call the access_module_by_id method.\n The corresponding object module data is then put in a dictionary and returned.\n\n current_port: int\n Represent the current port. If the module is a hub/box it is used to select tjhe connector to be used.\n\n Returns\n -------\n data: dict\n The dictionary containing all necessary data about the selected module.\n\n \"\"\"\n # global parent_module\n self.print('id: ', id)\n\n # Call the access_module_by_id method to find the selected module\n selected_module = self.access_module_by_id(id)\n\n # Select the current connector of the selected module\n selected_connector = self.select_connector(selected_module, port_idx=current_port)\n # Select the meshes to highlight in the GUI\n selected_meshes = self.select_meshes(selected_connector, selected_module)\n\n # Create the dictionary with the relevant info on the selected module, so that the GUI can dispaly it.\n data = {'name': selected_module.name,\n 'type': selected_module.type,\n 'flange_size': selected_module.flange_size,\n 'selected_connector': selected_connector,\n 'selected_meshes': selected_meshes,\n 'urdf_string': self.urdf_string} \n\n return data\n\n def select_module_from_name(self, name, current_port=None):\n \"\"\"Allows to select a module from the tree. An inner call to access_module_by_name sets the selected module as the\n current parent module. Returns info on the selected module, so that the GUI can display it.\n\n Parameters\n ----------\n name: str\n String with the name of the module to select or the name of the mesh clicked on the GUI. It will be used to call the access_module_by_name method.\n The corresponding object module data is then put in a dictionary and returned.\n\n current_port: int\n Represent the current port. If the module is a hub/box it is used to select tjhe connector to be used.\n\n Returns\n -------\n data: dict\n The dictionary containing all necessary data about the selected module.\n\n \"\"\"\n\n self.print(name)\n\n # If the name of the mesh clicked on the GUI is not the name of the module, but the name of the mesh, we need to\n # find the module object from the mesh name. The mesh_to_module_map dictionary is used for this. Default value\n # is the name itself, so if the name is not in the dictionary, it is the name of the module itself.\n selected_module_name = self.mesh_to_module_map.get(name, name)\n\n # Call access_module_by_name to get the object with the requested name and sets it as parent.\n # The method doing the real work is actually access_module_by_name\n selected_module = self.access_module_by_name(selected_module_name)\n\n # Select the current connector of the selected module\n selected_connector = self.select_connector(selected_module, connector_name=name, port_idx=current_port)\n # Select the meshes to highlight in the GUI\n selected_meshes = self.select_meshes(selected_connector, selected_module)\n\n # Create the dictionary with the relevant info on the selected module, so that the GUI can dispaly it.\n data = {'name': selected_module.name,\n 'type': selected_module.type,\n 'flange_size': selected_module.flange_size,\n 'selected_connector': selected_connector,\n 'selected_meshes': selected_meshes,\n 'urdf_string': self.urdf_string} \n\n return data\n \n\n def port_to_connector_idx(self, port_idx, module):\n \"\"\"Convert the port index to the connector index, for the given module.\n\n Parameters\n ----------\n port_idx: int\n The index of the port to convert.\n\n module: ModuleNode.ModuleNode\n The module to compute the connector index for.\n\n Returns\n -------\n connector_idx: int\n The index of the connector corresponding to the port index.\n\n \"\"\"\n # MYNOTE: this part is used only in Discovery mode for now.\n # TODO: this works only for hub trees of maximum depth 2. For deeper trees, this should be revised.\n idx_offset = 0\n # If the hub is not structural, we need to take into account the other children the parent hub might have.\n # If the hub is not structural, by default its parent must be a hub as well. Non-structural hubs can only be\n # connected to structural hubs (or other non-structural hubs) and be a \"children hub\". Their only purpose is to \n # \"increase\" the number of ports of its parent hub (and therefore its available connectors). \n # The connectors are shared between the parent and children hubs, so their index must be computed accordingly.\n if module.type in ModuleClass.hub_modules() and module.parent.type in ModuleClass.hub_modules() and not module.is_structural:\n # # The current port used by the parent hub to connect to the hub we are computing the transforms of.\n # parent_current_port = 1 << self.eth_to_physical_port_idx(module.parent.current_port)\n # # The ports of the parent hub already occupied before adding the current hub.\n # parent_already_occupied_ports = int(module.parent.occupied_ports, 2) & ~parent_current_port\n # # The ports 1, 2 and 3\n # non_zero_ports = int(\"1110\", 2)\n # # The ports of the parent hub already occupied before adding the current hub, excluding the port 0.\n # parent_ports_occupied_before_hub = (parent_already_occupied_ports & non_zero_ports)\n # # The number of children the parent hub has before adding the current hub.\n # n_children_before_hub = 0\n # for i in range(4):\n # if parent_ports_occupied_before_hub & (1 << i):\n # n_children_before_hub += 1\n\n # The number of hubs children the parent hub has after adding the current hub.\n parent_elder_hubs_children = module.parent.n_children_hubs - 1\n # The index offset is computed by looking at the number of children hubs and non-hubs the parent hub has before adding the current hub.\n if parent_elder_hubs_children > 0:\n # Count the number of non-structural hubs children the parent hub has (sieblings of the current hub)\n # Remove the current hub from the count, should not be taken into account when counting the index.\n nonstructural_hub_children = self.count_children_non_structural_hubs(module.parent, count=-1)\n # We take into account the other hubs connected to get the right index. We have 4 connectors per hub, but since port 0 is occupied by the hub-hub connection, each child hub increase the index by 3\n idx_offset += (4-1)*nonstructural_hub_children\n # We take into account that one port on the current hub (parent) is used to establish a connection with a second hub, and that should not be taken into account when counting the index\n idx_offset -= 1*nonstructural_hub_children\n # # Each hub sibling increases the index offset by 1!\n # idx_offset += (1)*parent_elder_hubs_children \n \n # The number of non-hubs children the parent hub has before adding the current hub.\n #parent_elder_nonhubs_children = n_children_before_hub - parent_elder_hubs_children\n # # the number of non-hubs children increases the index offset by 1 (since each non-hub has 2 connectors, but one is used to connect to the parent hub).\n # idx_offset +=(parent_elder_nonhubs_children)*1\n #MYNOTE: this is kind of magic\n idx_offset += module.parent.current_port - 1\n \n # indexes for connector and selected port are the same, unless the hub is connected to another non-structural hub\n connector_idx = port_idx + idx_offset\n \n # We need to add an offset to the connector index introduced by the other non-structural hubs already connected to the current hub\n if module.type in ModuleClass.hub_modules():\n # Count the number of non-structural hubs children the current hub has\n nonstructural_hub_children = self.count_children_non_structural_hubs(module)\n # We take into account the other hubs connected to get the right index. We have 4 connectors per hub, but since port 0 is occupied by the hub-hub connection, each child hub increase the index by 3\n connector_idx += (4-1)*nonstructural_hub_children\n # We take into account that one port on the current hub (parent) is used to establish a connection with a second hub, and that should not be taken into account when counting the index\n connector_idx -= 1*nonstructural_hub_children\n\n return connector_idx\n \n\n def count_children_non_structural_hubs(self, module, count=0):\n \"\"\"Count all non-strucural hubs children and grandchildren of the given module recursively.\n\n Parameters\n ----------\n module: ModuleNode.ModuleNode\n The module to compute the offset for.\n\n count: int\n The current offset count. Default value is 0.\n\n Returns\n -------\n count: int\n The offset of the connector index for the given module.\n\n \"\"\"\n for child in module.children:\n count = self.count_children_non_structural_hubs(child, count)\n if child.type in ModuleClass.hub_modules() and not child.is_structural:\n count += 1\n return count\n \n\n def connector_to_port_idx(self, connector_idx, module):\n \"\"\"Convert the connector index to the port index.\n\n Parameters\n ----------\n connector_idx: int\n The index of the connector to convert.\n\n Returns\n -------\n port_idx: int\n The index of the port corresponding to the connector index.\n\n \"\"\"\n # MYNOTE: this part is used only in Building mode for now. When the differences between the two modes will be removed, the implemantation of this function will be the reverse of the port_to_connector_idx function.\n\n # connector index is the same as the port index for the first 4 ports\n port_idx = connector_idx\n\n return port_idx\n \n\n def eth_to_physical_port_idx(self, eth_port_idx):\n \"\"\"Convert the EtherCAT port index to the physical port index. This is necessary because the EtherCAT master\n scans the ports in a different order than the physical one.\n\n Parameters\n ----------\n\n eth_port_idx: int\n The index of the EtherCAT port to convert.\n\n Returns\n -------\n physical_port_idx: int\n The index of the physical port corresponding to the EtherCAT port index.\n\n \"\"\"\n eth_to_physical_port_map = {\n 0: 0,\n 1: 3,\n 2: 1,\n 3: 2\n }\n return eth_to_physical_port_map[eth_port_idx]\n \n\n def set_current_port(self, module, port_idx=None):\n \"\"\"Set the current port of the module, i.e. the one where the new module will be added to.\n The current port is the first free one, i.e. the first one seen from the EtherCAT master scan.\n If the port_idx argument is passed, the current port is set to the one specified by it.\n\n Parameters\n ----------\n module: ModuleNode.ModuleNode\n The object of the module to set the current port to.\n\n port_idx: int\n The index of the port to select as the current one.\n\n Returns\n -------\n module.current_port: int\n The port selected as the current one.\n\n \"\"\"\n # If the port index is not None, it means that the user has selected it from the GUI. Value is overwritten\n if port_idx is not None:\n module.current_port = port_idx\n else:\n #MYNOTE: this part is used only in Discovery mode for now. occupied ports gets updated only in Discovery mode for now\n # binary XOR: the free ports are the ones that are active but not occupied\n free_ports = int(module.active_ports, 2) ^ int(module.occupied_ports, 2)\n self.print(module.name + \" active_ports: \" + module.active_ports + \" - \" + \"occupied_ports: \" + module.occupied_ports + \" =\")\n self.print(\"{0:04b}\".format(free_ports))\n\n # remap the ports from the physical order to the EtherCAT order: 3, 2, 1, 0 -> 2, 1, 3, 0. \n # See EtherCAT slave documentation for more info \n free_ports_remapped = ((free_ports & int(\"0110\", 2)) << 1) + ((free_ports & int(\"1000\", 2)) >> 2)\n self.print(\"{0:04b}\".format(free_ports_remapped))\n\n # By default the selected port is the first free one (the firt one seen from the EtherCAT master scan)\n selected_eth_port = self.ffs(free_ports_remapped)\n self.print('selected EtherCAT port :', selected_eth_port)\n\n # MYNOTE: this part is not needed. We are not interested in the physical port index, but in the EtherCAT port index, so that it matches the order of the ports in the EtherCAT master scan.\n # # remap the ports from the EtherCAT order to the physical order: 2, 1, 3, 0 -> 3, 2, 1, 0.\n # selected_physical_port = self.eth_to_physical_port_idx(selected_eth_port)\n # self.print('selected physical port :', selected_physical_port)\n\n # Set the current_port attribute of the module\n module.current_port = selected_eth_port\n\n self.print('module.current_port :', module.current_port)\n\n return module.current_port \n \n\n def select_connector(self, module, connector_name=None, port_idx=None):\n \"\"\"Select the connector of the module to which the new module will be added to.\n If no `connector_name` is passed, the connector is the first free one, i.e. the first one seen from the EtherCAT master scan. (Discovery mode)\n Otherwise the connector name is selected as the one passed as argument. (Building mode)\n\n Parameters\n ----------\n module: ModuleNode.ModuleNode\n The object of the module to set the current port to.\n\n connector_name: str\n String with the name of the connector. Could come from the name of the mesh clicked on the GUI and associated to the connector.\n\n port_idx: int\n The index of the port to select as the current one.\n\n Returns\n -------\n selected_connector: str\n The name of the connector currently selected.\n \"\"\"\n\n # If the selected mesh is the one of a connector, we need to set the right port\n if connector_name in module.connectors:\n # The connector index is retrieved from the list of connectors of the module\n connector_idx = module.connectors.index(connector_name)\n # Convert the connector index to the port index\n current_port = self.connector_to_port_idx(connector_idx, module)\n # TODO: the current port is not at the moment. This is currently done only in Discovery mode. In Building mode the current port is not used.\n # Set the name of the selected connector\n selected_connector = connector_name\n else:\n # Set the current port of the module\n self.set_current_port(module, port_idx=port_idx)\n # Convert the port index to the connector index\n connector_idx = self.port_to_connector_idx(module.current_port, module) \n # Set the name of the selected connector. If the index is out of range, it means that the module has only one connector, so we use as name the module name itself.\n # TODO: add connectors also for modules with only one connector, so to avoid this and have a uniform behavior\n if 0 <= connector_idx < len(module.connectors):\n selected_connector = module.connectors[connector_idx]\n else:\n selected_connector = module.name\n\n setattr(module, 'connector_idx', connector_idx)\n\n self.print('selected_connector :', selected_connector)\n\n return selected_connector\n \n\n def select_meshes(self, selected_connector, module):\n \"\"\"Select the mesh of the module to be highlighted on the GUI.\n\n Parameters\n ----------\n selected_connector: str\n String with the name of the connector.\n\n module: ModuleNode.ModuleNode\n The object of the module to select the mesh from.\n\n Returns\n -------\n selected_mesh: list\n The names of the meshes currently selected.\n \"\"\"\n\n if selected_connector in module.connectors:\n # If the selected mesh is the one of a connector, we select as mesh only the one associated to the connector\n selected_meshes = [selected_connector]\n else:\n # Otherwise we select all the meshes of the module\n selected_meshes = module.mesh_names\n\n self.print('selected_mesh :', selected_meshes)\n\n return selected_meshes\n\n\n @staticmethod\n def ffs(x):\n \"\"\"Returns the index, counting from 0, of the\n least significant set bit in `x`.\n \"\"\"\n return (x & -x).bit_length() - 1\n\n # TODO: handle reverse also for links\n def add_link(self, new_Link, parent_name, transform, reverse):\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(transform)\n\n if new_Link.type in ModuleClass.link_modules() - {ModuleType.SIZE_ADAPTER}:\n setattr(new_Link, 'name', 'L_' + str(new_Link.i) + '_link_' + str(new_Link.p) + new_Link.tag)\n self.add_link_element(new_Link.name, new_Link, 'body_1') # , type='link')\n \n elif new_Link.type is ModuleType.DAGANA:\n setattr(new_Link, 'name', 'dagana' + new_Link.tag)\n ET.SubElement(self.root,\n \"xacro:add_dagana\",\n type=\"link\",\n name=new_Link.name,\n father=parent_name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n # add the xacro:add_dagana element to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.name)\n new_Link.mesh_names += [new_Link.name + '_top_link', new_Link.name + '_bottom_link']\n\n setattr(new_Link, 'dagana_joint_name', new_Link.name + '_claw_joint')\n setattr(new_Link, 'dagana_link_name', new_Link.name + '_bottom_link')\n setattr(new_Link, 'dagana_tcp_name', new_Link.name + '_tcp')\n setattr(new_Link, 'tcp_name', 'ee' + new_Link.tag)\n ET.SubElement(self.root,\n \"xacro:add_tcp\",\n type=\"pen\",\n name=new_Link.tcp_name,\n father=new_Link.dagana_tcp_name,\n x=\"0.0\",\n y=\"0.0\",\n z=\"0.0\",\n roll=\"0.0\",\n pitch=\"0.0\",\n yaw=\"0.0\")\n # add the xacro:add_tcp element to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.tcp_name)\n\n # the dagana gets added to the chain. it's needed in the joint map and in the config!\n # self.add_to_chain(new_Link)\n self.control_plugin.add_joint(new_Link.dagana_joint_name)\n\n return\n\n elif new_Link.type is ModuleType.DRILL:\n setattr(new_Link, 'name', 'drill' + new_Link.tag)\n self.add_link_element(new_Link.name, new_Link, 'body_1') # , type='link')\n \n setattr(new_Link, 'camera_name', 'drill_camera' + new_Link.tag)\n ET.SubElement(self.root,\n \"xacro:add_realsense_d_camera\",\n type=\"link\",\n name=new_Link.camera_name,\n parent_name=new_Link.name)\n # add the xacro:add_realsense_d_camera to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.camera_name)\n new_Link.mesh_names.append(new_Link.camera_name)\n\n # \n # # \n # \n # \n # \n\n x_ee, y_ee, z_ee, roll_ee, pitch_ee, yaw_ee = ModuleNode.get_xyzrpy(tf.transformations.numpy.array(new_Link.kinematics.link.pose))\n setattr(new_Link, 'tcp_name', 'ee' + new_Link.tag)\n ET.SubElement(self.root,\n \"xacro:add_tcp\",\n type=\"pen\",\n name=new_Link.tcp_name,\n father=new_Link.name,\n x=x_ee,\n y=y_ee,\n z=z_ee,\n roll=roll_ee,\n pitch=pitch_ee,\n yaw=yaw_ee)\n # add the xacro:add_tcp element to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.tcp_name)\n\n # the drill gets added to the chain although it's not a joint. it's needed in the joint map and in the config!\n # self.add_to_chain(new_Link)\n\n elif new_Link.type is ModuleType.END_EFFECTOR:\n setattr(new_Link, 'name', 'end_effector' + new_Link.tag)\n self.add_link_element(new_Link.name, new_Link, 'body_1') # , type='link')\n\n x_ee, y_ee, z_ee, roll_ee, pitch_ee, yaw_ee = ModuleNode.get_xyzrpy(tf.transformations.numpy.array(new_Link.kinematics.link.pose))\n setattr(new_Link, 'tcp_name', 'ee' + new_Link.tag)\n ET.SubElement(self.root,\n \"xacro:add_tcp\",\n type=\"pen\",\n name=new_Link.tcp_name,\n father=new_Link.name,\n x=x_ee,\n y=y_ee,\n z=z_ee,\n roll=roll_ee,\n pitch=pitch_ee,\n yaw=yaw_ee)\n # add the xacro:add_tcp element to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.tcp_name)\n \n elif new_Link.type is ModuleType.TOOL_EXCHANGER:\n setattr(new_Link, 'name', 'tool_exchanger' + new_Link.tag)\n self.add_link_element(new_Link.name, new_Link, 'body_1') # , type='tool_exchanger')\n\n # the end-effector gets added to the chain although it's not a joint. it's needed in the joint map and in the config!\n # self.add_to_chain(new_Link)\n # HACK: add pen after tool_exchanger\n setattr(new_Link, 'tcp_name', 'pen' + new_Link.tag)\n ET.SubElement(self.root,\n \"xacro:add_tcp\",\n type=\"pen\",\n name=new_Link.tcp_name,\n father=new_Link.name,\n x=\"0.0\",\n y=\"0.0\",\n z=\"0.222\",\n roll=\"0.0\",\n pitch=\"0.0\",\n yaw=\"0.0\")\n # add the xacro:add_tcp element to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.tcp_name)\n \n elif new_Link.type is ModuleType.GRIPPER:\n setattr(new_Link, 'name', 'gripper' + new_Link.tag)\n self.add_link_element(new_Link.name, new_Link, 'body_1') # , type='gripper_body')\n \n # the end-effector gets added to the chain although it's not a joint. it's needed in the joint map and in the config!\n # self.add_to_chain(new_Link)\n # add fingers and tcp after gripper\n setattr(new_Link, 'tcp_name', 'TCP_' + new_Link.name)\n setattr(new_Link, 'joint_name_finger1', new_Link.name + '_finger_joint1')\n setattr(new_Link, 'joint_name_finger2', new_Link.name + '_finger_joint2')\n \n # TODO: add_gripper_fingers still use the xacro to load the yaml file and get the parameters. It should be changed to use the python function for uniformity\n ET.SubElement(self.root,\n \"xacro:add_gripper_fingers\",\n type=\"gripper_fingers\",\n name=new_Link.name,\n joint_name_finger1=new_Link.joint_name_finger1,\n joint_name_finger2=new_Link.joint_name_finger2,\n TCP_name=new_Link.tcp_name,\n filename=new_Link.filename)\n # add the xacro:add_gripper_fingers element to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.name)\n new_Link.mesh_names += [new_Link.name + '_finger1', new_Link.name + '_finger2']\n\n # TO BE FIXED: ok for ros_control. How will it be for xbot2?\n self.control_plugin.add_joint(new_Link.joint_name_finger1)\n self.control_plugin.add_joint(new_Link.joint_name_finger2)\n\n elif new_Link.type is ModuleType.SIZE_ADAPTER:\n setattr(new_Link, 'name', 'L_' + str(new_Link.i) + '_size_adapter_' + str(new_Link.p) + new_Link.tag)\n ET.SubElement(self.root,\n \"xacro:add_size_adapter\",\n type=\"size_adapter\",\n name=new_Link.name,\n filename=new_Link.filename,\n size_z=new_Link.kinematics.link.n_l,\n # size_in=new_Link.size_in,\n # size_out=new_Link.size_out\n )\n # add the xacro:add_size_adapter element to the list of urdf elements\n new_Link.xml_tree_elements.append(new_Link.name)\n new_Link.mesh_names.append(new_Link.name)\n setattr(new_Link, 'flange_size', new_Link.size_out)\n\n self.add_gazebo_element(new_Link, new_Link.gazebo.body_1, new_Link.name)\n\n if new_Link.type in ModuleClass.end_effector_modules():\n fixed_joint_name = new_Link.name + '_fixed_joint'\n else:\n fixed_joint_name = 'L_' + str(new_Link.i) + '_fixed_joint_' + str(new_Link.p) + new_Link.tag\n\n ET.SubElement(self.root,\n \"xacro:add_fixed_joint\",\n name=fixed_joint_name,\n type=\"fixed_joint\",\n father=parent_name,\n child=new_Link.name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n # add the xacro:add_gripper_fingers element to the list of urdf elements\n new_Link.xml_tree_elements.append(fixed_joint_name)\n setattr(new_Link, 'fixed_joint_name', fixed_joint_name)\n \n return\n\n\n def get_hub_output_transform(self, hub):\n\n connector_name = 'Con_' + str(hub.connector_idx) + '_tf'\n try:\n interface_transform = getattr(hub, connector_name)\n except AttributeError:\n self.error_print('AttributeError: ' + connector_name + ' not found in hub ' + hub.name + '. Either something went wrong during the discovery or the resources should be updated.')\n raise AttributeError\n # if not hub.is_structural:\n # interface_transform = tf.transformations.identity_matrix()\n\n self.print('hub.current_port:', hub.current_port)\n self.print('interface_transform: ', interface_transform)\n\n return interface_transform\n\n\n def get_joint_output_transform(self, past_Joint):\n return past_Joint.Distal_tf\n\n\n def get_link_output_transform(self, past_Link):\n return past_Link.Homogeneous_tf\n\n\n def get_joint_name(self, module):\n if module.type in ModuleClass.joint_modules() | {ModuleType.DRILL}:\n return module.name\n elif module.type is ModuleType.DAGANA:\n return module.dagana_joint_name\n else:\n return None\n\n def get_proximal_transform(self, interface_transform, offsets, reverse):\n # compute offset\n T = tf.transformations.translation_matrix((offsets.get('x', 0.0), offsets.get('y', 0.0), offsets.get('z', 0.0)))\n R = tf.transformations.euler_matrix(offsets.get('roll', 0.0), offsets.get('pitch', 0.0), offsets.get('yaw', 0.0), 'sxyz')\n offset_transform = tf.transformations.concatenate_matrices(T, R)\n \n transform = ModuleNode.get_rototranslation(interface_transform,\n offset_transform)\n # If the module is mounted in the opposite direction rotate the final frame by 180 deg., as per convention\n if reverse:\n transform = ModuleNode.get_rototranslation(transform,\n tf.transformations.rotation_matrix(3.14, self.yaxis))\n\n return transform\n \n # HACK: to handle 90° offset between PINO and CONCERT flanges\n def apply_adapter_transform_rotation(self, interface_transform, size1, size2):\n if size2 < size1:\n self.info_print(\"Size mismatch: \" + size1 + \" vs \" + size2 + \" ---> Rotating input connector of 90°\")\n transform = ModuleNode.get_rototranslation(interface_transform,\n tf.transformations.rotation_matrix(1.57,\n self.zaxis))\n else:\n transform = interface_transform\n\n return transform\n\n def add_origin(self, parent_el, pose):\n # x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(pose) # TODO: migrate to JSON format and use this\n \n ET.SubElement(parent_el, \"origin\",\n xyz=str(pose.x) + \" \" + str(pose.y) + \" \" + str(pose.z),\n rpy=str(pose.roll) + \" \" + str(pose.pitch) + \" \" + str(pose.yaw))\n\n\n def add_geometry(self, parent_el, geometry):\n geometry_el = ET.SubElement(parent_el, \"geometry\")\n if geometry.type == \"mesh\":\n ET.SubElement(geometry_el, \"mesh\",\n filename=geometry.parameters.file,\n scale=' '.join(str(x) for x in geometry.parameters.scale))\n elif geometry.type == \"box\":\n ET.SubElement(geometry_el, \"box\",\n size=' '.join(str(x) for x in geometry.parameters.size))\n elif geometry.type == \"cylinder\":\n ET.SubElement(geometry_el, \"cylinder\",\n radius=str(geometry.parameters.radius),\n length=str(geometry.parameters.length))\n elif geometry.type == \"sphere\":\n ET.SubElement(geometry_el, \"sphere\",\n radius=str(geometry.parameters.radius))\n\n \n def add_material(self, parent_el, color):\n material_el = ET.SubElement(parent_el, \"material\", \n name = color.material_name)\n if hasattr(color, 'rgba'):\n ET.SubElement(material_el, \"color\",\n rgba=' '.join(str(x) for x in color.rgba))\n if hasattr(color, 'texture'):\n ET.SubElement(material_el, \"texture\",\n filename=color.texture.filename)\n\n\n def add_inertial(self, parent_el, dynamics, gear_ratio=1.0):\n inertial_el = ET.SubElement(parent_el, \"inertial\")\n # We interpret the mass as a flag to enable/disable the inertial properties\n if dynamics.mass:\n ET.SubElement(inertial_el, \"origin\",\n xyz=str(dynamics.CoM.x) + \" \" + str(dynamics.CoM.y) + \" \" + str(dynamics.CoM.z),\n rpy=str(0) + \" \" + str(0) + \" \" + str(0))\n ET.SubElement(inertial_el, \"mass\",\n value=str(dynamics.mass))\n ET.SubElement(inertial_el, \"inertia\",\n ixx=str(dynamics.inertia_tensor.I_xx),\n ixy=str(dynamics.inertia_tensor.I_xy),\n ixz=str(dynamics.inertia_tensor.I_xz),\n iyy=str(dynamics.inertia_tensor.I_yy),\n iyz=str(dynamics.inertia_tensor.I_yz),\n izz=str(gear_ratio*gear_ratio*dynamics.inertia_tensor.I_zz))\n # If the mass is 0.0 we set the inertial properties to a default value to avoid issues with the dynamics libraries using the URDF\n else:\n ET.SubElement(inertial_el, \"mass\",\n value=str(1e-04))\n ET.SubElement(inertial_el, \"inertia\", \n ixx=str(1e-09),\n ixy=str(0),\n ixz=str(0),\n iyy=str(1e-09),\n iyz=str(0),\n izz=str(1e-09))\n\n\n def add_link_element(self, link_name, module_obj, body_name, is_geared=False):\n link_el = ET.SubElement(self.root,\n 'link',\n name=link_name)\n # Add the link to the list of urdf elements of the module\n module_obj.xml_tree_elements.append(link_name)\n module_obj.mesh_names.append(link_name)\n\n visual_bodies = getattr(module_obj.visual, body_name, None)\n collision_bodies = getattr(module_obj.collision, body_name, None)\n dynamics_body = getattr(module_obj.dynamics, body_name, None)\n\n for body in visual_bodies or []:\n visual_el = ET.SubElement(link_el,\n 'visual')\n self.add_origin(visual_el, body.pose)\n self.add_geometry(visual_el, body)\n if hasattr(body.parameters, 'color'):\n self.add_material(visual_el, body.parameters.color)\n \n for body in collision_bodies or []:\n collision_el = ET.SubElement(link_el,\n 'collision')\n self.add_origin(collision_el, body.pose)\n self.add_geometry(collision_el, body)\n\n if dynamics_body:\n if is_geared:\n self.add_inertial(link_el, dynamics_body, module_obj.actuator_data.gear_ratio)\n else:\n self.add_inertial(link_el, dynamics_body)\n\n\n def add_joint(self, new_Joint, parent_name, transform, reverse):\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(transform)\n\n if new_Joint.type is ModuleType.JOINT:\n setattr(new_Joint, 'name', 'J' + str(new_Joint.i) + new_Joint.tag)\n setattr(new_Joint, 'distal_link_name', 'L_' + str(new_Joint.i) + new_Joint.tag)\n elif new_Joint.type is ModuleType.WHEEL:\n setattr(new_Joint, 'name', 'J_wheel' + new_Joint.tag)\n setattr(new_Joint, 'distal_link_name', 'wheel' + new_Joint.tag)\n setattr(new_Joint, 'stator_name', new_Joint.name + '_stator')\n setattr(new_Joint, 'fixed_joint_name', \"fixed_\" + new_Joint.name)\n ET.SubElement(self.root, \"xacro:add_fixed_joint\",\n type=\"fixed_joint_stator\",\n name=new_Joint.fixed_joint_name,\n father=parent_name, \n child=new_Joint.stator_name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n # add the xacro:add_fixed_joint element to the list of urdf elements\n new_Joint.xml_tree_elements.append(new_Joint.fixed_joint_name)\n\n self.collision_elements.append((parent_name, new_Joint.stator_name))\n\n # mesh_transform = ModuleNode.get_rototranslation(tf.transformations.rotation_matrix(-1.57, self.zaxis),\n # tf.transformations.rotation_matrix(3.14, self.xaxis))\n mesh_transform = tf.transformations.identity_matrix()\n\n # If the module is mounted in the opposite direction rotate the final frame by 180 deg., as per convention\n if reverse:\n prox_mesh_transform = ModuleNode.get_rototranslation(mesh_transform, tf.transformations.rotation_matrix(-3.14, self.yaxis))\n prox_mesh_transform = ModuleNode.get_rototranslation(prox_mesh_transform, tf.transformations.inverse_matrix(new_Joint.Proximal_tf))\n # prox_mesh_transform = ModuleNode.get_rototranslation(mesh_transform, tf.transformations.translation_matrix((-0.0591857,0,-0.095508)))#tf.transformations.inverse_matrix(new_Joint.Proximal_tf))\n # prox_mesh_transform = ModuleNode.get_rototranslation(prox_mesh_transform, tf.transformations.rotation_matrix(3.14, self.xaxis))\n # prox_mesh_transform = ModuleNode.get_rototranslation(prox_mesh_transform,\n # tf.transformations.rotation_matrix(1.57, self.zaxis))\n else:\n prox_mesh_transform = mesh_transform\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(prox_mesh_transform)\n\n # Add proximal link\n self.add_link_element(new_Joint.stator_name, new_Joint, 'body_1')\n self.add_gazebo_element(new_Joint, new_Joint.gazebo.body_1, new_Joint.stator_name)\n\n joint_transform = ModuleNode.get_rototranslation(tf.transformations.identity_matrix(),\n new_Joint.Proximal_tf)\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(joint_transform)\n\n actuator_data = new_Joint.actuator_data\n upper_lim = str(actuator_data.upper_limit)\n lower_lim = str(actuator_data.lower_limit)\n effort = str(actuator_data.effort)\n velocity = str(actuator_data.velocity)\n\n ET.SubElement(self.root,\n \"xacro:add_joint\",\n type=\"joint\",\n name=new_Joint.name,\n father=new_Joint.stator_name,\n child=new_Joint.distal_link_name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw,\n upper_lim=upper_lim,\n lower_lim=lower_lim,\n effort=effort,\n velocity=velocity)\n # add the xacro:add_joint element to the list of urdf elements\n new_Joint.xml_tree_elements.append(new_Joint.name)\n\n ####\n #ET.SubElement(self.xbot2_pid, \"xacro:add_xbot2_pid\", name=new_Joint.name, profile=\"small_mot\")\n self.control_plugin.add_joint(new_Joint.name,\n control_params=new_Joint.xbot_gz if hasattr(new_Joint, 'xbot_gz') else None)\n ####\n\n if reverse:\n dist_mesh_transform = ModuleNode.get_rototranslation(new_Joint.Distal_tf, mesh_transform)\n else:\n dist_mesh_transform = mesh_transform\n\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(dist_mesh_transform)\n\n # Add distal link\n self.add_link_element(new_Joint.distal_link_name, new_Joint, 'body_2')\n self.add_gazebo_element(new_Joint, new_Joint.gazebo.body_2, new_Joint.distal_link_name)\n \n # Add proximal/distal links pair to the list of collision elements to ignore\n self.collision_elements.append((new_Joint.stator_name, new_Joint.distal_link_name))\n\n if reverse:\n new_Joint.Distal_tf = ModuleNode.get_rototranslation(new_Joint.Distal_tf,\n tf.transformations.rotation_matrix(3.14, self.yaxis))\n\n # add the fast rotor part to the inertia of the link/rotor part as a new link. NOTE: right now this is\n # attached at the rotating part not to the fixed one (change it so to follow Pholus robot approach)\n # TODO: create a switch between the different methods to consider the fast rotor part\n if hasattr(new_Joint.dynamics, 'body_2_fast'):\n setattr(new_Joint, 'fixed_joint_rotor_fast_name', \"fixed_\" + new_Joint.distal_link_name + '_rotor_fast')\n ET.SubElement(self.root,\n \"xacro:add_fixed_joint\",\n type=\"fixed_joint\",\n name=new_Joint.fixed_joint_rotor_fast_name,\n father=new_Joint.distal_link_name, # stator_name, #\n child=new_Joint.distal_link_name + '_rotor_fast',\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n # add the xacro:add_fixed_joint element to the list of urdf elements\n new_Joint.xml_tree_elements.append(new_Joint.fixed_joint_rotor_fast_name)\n \n self.add_link_element(new_Joint.distal_link_name + '_rotor_fast', new_Joint, 'body_2_fast', is_geared=True)\n\n\n def add_hub(self, new_Hub, parent_name, transform, hub_name=None):\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(transform)\n\n if hub_name:\n setattr(new_Hub, 'name', hub_name)\n else:\n setattr(new_Hub, 'name', 'L_' + str(new_Hub.i) + '_link_' + str(new_Hub.p) + new_Hub.tag)\n\n self.add_link_element(new_Hub.name, new_Hub, 'body_1')\n self.add_gazebo_element(new_Hub, new_Hub.gazebo.body_1, new_Hub.name)\n \n self.add_connectors(new_Hub)\n\n fixed_joint_name = 'fixed_' + new_Hub.name\n\n ET.SubElement(self.root,\n \"xacro:add_fixed_joint\",\n name=fixed_joint_name,\n type=\"fixed_joint\",\n father=parent_name,\n child=new_Hub.name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n # add the xacro:add_fixed_joint element to the list of urdf elements\n new_Hub.xml_tree_elements.append(fixed_joint_name)\n setattr(new_Hub, 'fixed_joint_name', fixed_joint_name)\n\n if new_Hub.type is ModuleType.MOBILE_BASE:\n ET.SubElement(self.root, \n \"xacro:add_mobile_base_sensors\",\n name=new_Hub.name + '_sensors',\n parent_name=new_Hub.name)\n # add the xacro:add_mobile_base_sensors element to the list of urdf elements\n new_Hub.xml_tree_elements.append(new_Hub.name + '_sensors') \n\n # Add hub and parent links pair to the list of collision elements to ignore\n self.collision_elements.append((parent_name, new_Hub.name)) \n\n \n # noinspection PyPep8Naming\n def link_after_hub(self, new_Link, past_Hub, offsets, reverse):\n \"\"\"Adds to the URDF tree a link module as a child of a hub module\n\n Parameters\n ----------\n new_Link: ModuleNode.ModuleNode\n ModuleNode object of the link module to add\n\n past_Hub: ModuleNode.ModuleNode\n ModuleNode object of the hub module to which attach the link\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n setattr(new_Link, 'p', 0) # past_Hub.p + 1)\n setattr(new_Link, 'i', 0) # past_Hub.i)\n\n if past_Hub.is_structural:\n parent_name = past_Hub.name\n else:\n parent_name = past_Hub.parent.name\n\n interface_transform = self.get_hub_output_transform(past_Hub)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse)\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Hub.flange_size, new_Link.flange_size)\n\n self.add_link(new_Link, parent_name, transform, reverse)\n\n self.collision_elements.append((past_Hub.name, new_Link.name))\n\n\n # noinspection PyPep8Naming\n def joint_after_hub(self, new_Joint, past_Hub, offsets, reverse):\n \"\"\"Adds to the URDF tree a joint module as a child of a hub module\n\n Parameters\n ----------\n new_Joint: ModuleNode.ModuleNode\n ModuleNode object of the joint module to add\n\n past_Hub: ModuleNode.ModuleNode\n ModuleNode object of the hub module to which the joint will be attached\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n if past_Hub.is_structural:\n parent_name = past_Hub.name\n else:\n parent_name = past_Hub.parent.name\n\n interface_transform = self.get_hub_output_transform(past_Hub)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse)\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Hub.flange_size, new_Joint.flange_size)\n\n setattr(new_Joint, 'i', 1)\n setattr(new_Joint, 'p', 0)\n\n self.add_joint(new_Joint, parent_name, transform, reverse)\n\n \n def hub_after_hub(self, new_Hub, past_Hub, offsets, reverse, module_name=None):\n \"\"\"Adds to the URDF tree a hub module as a child of a hub module\n\n Parameters\n ----------\n new_Hub: ModuleNode.ModuleNode\n ModuleNode object of the hub module to add\n\n past_Hub: ModuleNode.ModuleNode\n ModuleNode object of the hub module to which the hub will be attached\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n if past_Hub.is_structural:\n parent_name = past_Hub.name\n else:\n parent_name = past_Hub.parent.name\n\n setattr(new_Hub, 'i', 0)\n setattr(new_Hub, 'p', past_Hub.p + 1)\n\n interface_transform = self.get_hub_output_transform(past_Hub)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse)\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Hub.flange_size, new_Hub.flange_size)\n\n # Set the number of child hubs to 0 (it will be incremented when a child hub is added)\n setattr(new_Hub, 'n_children_hubs', 0)\n\n if new_Hub.is_structural:\n self.add_hub(new_Hub, parent_name, transform, hub_name=module_name)\n else:\n # HACK: we set the name of the non-structural hub to be the same as the parent. This is needed to correctly write the SRDF chains!\n setattr(new_Hub, 'name', parent_name)\n # HACK: we set the connectors of the non-structural hub to be the same as the parent.\n new_Hub.connectors = past_Hub.connectors\n # if the parent is a hub, the n_children_hubs attribute is incremented, in order to keep track of the number of hubs connected to the parent hub and therefore the number of ports occupied. This is needed to select the right connector where to connect the new module \n self.parent_module.n_children_hubs += 1\n \n # Add the hub to the list of hubs\n self.listofhubs.append(new_Hub) \n\n\n def hub_after_link(self, new_Hub, past_Link, offsets, reverse, module_name=None):\n \"\"\"Adds to the URDF tree a hub module as a child of a link module\n\n Parameters\n ----------\n new_Hub: ModuleNode.ModuleNode\n ModuleNode object of the hub module to add\n\n past_Link: ModuleNode.ModuleNode\n ModuleNode object of the link module to which the hub will be attached\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n setattr(new_Hub, 'i', past_Link.i)\n setattr(new_Hub, 'p', past_Link.p + 1)\n\n interface_transform = self.get_link_output_transform(past_Link)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse=reverse) # TODO check reverse\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Link.flange_size, new_Hub.flange_size)\n\n parent_name = past_Link.name\n\n # Set the number of child hubs to 0 (it will be incremented when a child hub is added)\n setattr(new_Hub, 'n_children_hubs', 0)\n\n if new_Hub.is_structural:\n self.add_hub(new_Hub, parent_name, transform, hub_name=module_name)\n\n # Add the hub to the list of hubs\n self.listofhubs.append(new_Hub) \n\n\n def hub_after_joint(self, new_Hub, past_Joint, offsets, reverse, module_name=None):\n \"\"\"Adds to the URDF tree a hub module as a child of a joint module\n\n Parameters\n ----------\n new_Hub: ModuleNode.ModuleNode\n ModuleNode object of the hub module to add\n\n past_Joint: ModuleNode.ModuleNode\n ModuleNode object of the joint module to which the hub will be attached\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n setattr(new_Hub, 'i', past_Joint.i)\n setattr(new_Hub, 'p', past_Joint.p + 1)\n\n interface_transform = self.get_joint_output_transform(past_Joint)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse=reverse) # TODO check reverse\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Joint.flange_size, new_Hub.flange_size)\n\n parent_name = past_Joint.distal_link_name\n\n # Set the number of child hubs to 0 (it will be incremented when a child hub is added)\n setattr(new_Hub, 'n_children_hubs', 0)\n\n if new_Hub.is_structural:\n self.add_hub(new_Hub, parent_name, transform, hub_name=module_name)\n \n # Add the hub to the list of hubs\n self.listofhubs.append(new_Hub) \n\n\n # noinspection PyPep8Naming\n def link_after_joint(self, new_Link, past_Joint, offsets, reverse):\n \"\"\"Adds to the URDF tree a link module as a child of a joint module\n\n Parameters\n ----------\n new_Link: ModuleNode.ModuleNode\n ModuleNode object of the link module to add\n\n past_Joint: ModuleNode.ModuleNode\n ModuleNode object of the joint module to which attach the link\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n setattr(new_Link, 'i', past_Joint.i)\n setattr(new_Link, 'p', past_Joint.p + 1)\n\n interface_transform = self.get_joint_output_transform(past_Joint)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse)\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Joint.flange_size, new_Link.flange_size)\n\n parent_name = past_Joint.distal_link_name\n\n self.add_link(new_Link, parent_name, transform, reverse)\n\n self.collision_elements.append((past_Joint.distal_link_name, new_Link.name))\n\n # noinspection PyPep8Naming\n def joint_after_joint(self, new_Joint, past_Joint, offsets, reverse):\n \"\"\"Adds to the URDF tree a joint module as a child of a joint module\n\n Parameters\n ----------\n new_Joint: ModuleNode.ModuleNode\n ModuleNode object of the joint module to add\n\n past_Joint: ModuleNode.ModuleNode\n ModuleNode object of the joint module to which the joint will be attached\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n interface_transform = self.get_joint_output_transform(past_Joint)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse)\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Joint.flange_size, new_Joint.flange_size)\n\n setattr(new_Joint, 'i', past_Joint.i + 1)\n setattr(new_Joint, 'p', 0)\n\n parent_name = 'L_' + str(past_Joint.i) + past_Joint.tag\n\n self.add_joint(new_Joint, parent_name, transform, reverse)\n\n # noinspection PyPep8Naming\n def joint_after_link(self, new_Joint, past_Link, offsets, reverse):\n \"\"\"Adds to the URDF tree a joint module as a child of a link module\n\n Parameters\n ----------\n new_Joint: ModuleNode.ModuleNode\n ModuleNode object of the joint module to add\n\n past_Link: ModuleNode.ModuleNode\n ModuleNode object of the link module to which the joint will be attached\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n interface_transform = self.get_link_output_transform(past_Link)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse)\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Link.flange_size, new_Joint.flange_size)\n\n setattr(new_Joint, 'i', past_Link.i + 1)\n setattr(new_Joint, 'p', 0)\n\n parent_name = past_Link.name\n\n self.add_joint(new_Joint, parent_name, transform, reverse)\n\n # noinspection PyPep8Naming\n def link_after_link(self, new_Link, past_Link, offsets, reverse):\n \"\"\"Adds to the URDF tree a joint module as a child of a link module\n\n Parameters\n ----------\n new_Link: ModuleNode.ModuleNode\n ModuleNode object of the link module to add\n\n past_Link: ModuleNode.ModuleNode\n ModuleNode object of the link module to which the joint will be attached\n\n offsets: dict\n Dictionary containing the various offsets ('x','y','z','roll','pitch','yaw') between the parent module output frame and the module input frame. Es. offsets = {'x': 1.0, 'y': 2.0, 'yaw': 1.57}\n \"\"\"\n\n setattr(new_Link, 'i', past_Link.i)\n setattr(new_Link, 'p', past_Link.p + 1)\n\n interface_transform = self.get_link_output_transform(past_Link)\n\n transform = self.get_proximal_transform(interface_transform, offsets, reverse)\n\n # HACK: to handle 90° offset between PINO and CONCERT flanges\n transform = self.apply_adapter_transform_rotation(transform, past_Link.flange_size, new_Link.flange_size)\n\n parent_name = past_Link.name\n\n self.add_link(new_Link, parent_name, transform, reverse)\n\n self.collision_elements.append((past_Link.name, new_Link.name))\n\n\n # TODO: remove hard-coded values\n def write_problem_description_multi(self):\n basic_probdesc_filename = self.resource_finder.get_filename('cartesio/ModularBot_cartesio_IK_config.yaml',\n ['data_path'])\n # basic_probdesc_filename = path_name + '/cartesio/ModularBot_cartesio_config.yaml'\n probdesc_filename = path_name + '/ModularBot/cartesio/ModularBot_cartesio_IK_config.yaml'\n # probdesc_filename = \"/tmp/modular/cartesio/ModularBot_cartesio_multichain_config.yaml\"\n # probdesc_filename = self.resource_finder.get_filename('cartesio/ModularBot_cartesio_multichain_config.yaml',\n # 'modularbot_path')\n probdesc = OrderedDict([])\n\n with open(basic_probdesc_filename, 'r') as stream:\n try:\n probdesc = ordered_load(stream, yaml.SafeLoader)\n # cartesio_stack['EE']['base_link'] = self.listofchains[0]\n #self.print(list(probdesc.items())[0])\n except yaml.YAMLError as exc:\n self.print(exc)\n\n #self.print(probdesc.items())\n i = 0\n tasks = []\n stack = [tasks]\n active_modules_chains = self.get_actuated_modules_chains()\n for joints_chain in active_modules_chains:\n ee_name = \"EE_\" + str(i + 1)\n tasks.append(ee_name)\n probdesc['stack'] = stack\n probdesc[ee_name] = copy.deepcopy(probdesc['EE'])\n\n tip_link = self.find_chain_tip_link(joints_chain)\n probdesc[ee_name]['distal_link'] = tip_link\n\n base_link = self.find_chain_base_link(joints_chain)\n probdesc[ee_name]['base_link'] = base_link\n # probdesc[ee_name]['type'] = \"Interaction\"\n probdesc[ee_name]['type'] = \"Cartesian\"\n probdesc[ee_name]['lambda'] = 0.1\n\n i += 1\n\n probdesc.pop('EE', None)\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(probdesc_filename)):\n try:\n os.makedirs(os.path.dirname(probdesc_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(probdesc_filename, 'w') as outfile:\n # ordered_dump(probdesc, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(probdesc, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4,\n canonical=False)\n return probdesc\n\n # temporary solution for single chain robots\n # useful to run CartesianImpedanceController automatically\n def write_problem_description(self):\n basic_probdesc_filename = self.resource_finder.get_filename('cartesio/ModularBot_cartesio_config.yaml',\n ['data_path'])\n # basic_probdesc_filename = path_name + '/cartesio/ModularBot_cartesio_config.yaml'\n probdesc_filename = path_name + '/ModularBot/cartesio/ModularBot_cartesio_config.yaml'\n ##probdesc_filename = self.resource_finder.get_filename('cartesio/ModularBot_cartesio_config.yaml',\n ## 'modularbot_path')\n #probdesc_filename = \"/tmp/modular/cartesio/ModularBot_cartesio_config.yaml\"\n probdesc = OrderedDict([])\n\n with open(basic_probdesc_filename, 'r') as stream:\n try:\n probdesc = ordered_load(stream, yaml.SafeLoader)\n # cartesio_stack['EE']['base_link'] = self.listofchains[0]\n self.print(list(probdesc.items())[0])\n except yaml.YAMLError as exc:\n self.print(exc)\n\n self.print(probdesc.items())\n active_modules_chains = self.get_actuated_modules_chains()\n joints_chain = active_modules_chains[0]\n tip_link = self.find_chain_tip_link(joints_chain)\n probdesc['EE']['distal_link'] = tip_link\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(probdesc_filename)):\n try:\n os.makedirs(os.path.dirname(probdesc_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(probdesc_filename, 'w') as outfile:\n #ordered_dump(probdesc, stream=outfile, Dumper=yaml.SafeDumper, default_flow_style=False, line_break='\\n\\n', indent=4)\n ordered_dump(probdesc, stream=outfile, default_flow_style=False, line_break='\\n\\n', indent=4, canonical = False)\n return probdesc\n\n\n def write_lowlevel_config(self, use_robot_id=False):\n \"\"\"Creates the low level config file needed by XBotCore \"\"\"\n lowlevel_config = self.control_plugin.write_lowlevel_config(use_robot_id)\n\n return lowlevel_config\n\n def write_joint_map(self, use_robot_id=False):\n \"\"\"Creates the joint map needed by XBotCore \"\"\"\n joint_map = self.control_plugin.write_joint_map(use_robot_id)\n\n return joint_map\n\n def write_srdf(self, builder_joint_map=None, compute_acm=True):\n \"\"\"Generates a basic srdf so that the model can be used right away with XBotCore\"\"\"\n \n global path_name\n srdf_filename = path_name + '/ModularBot/srdf/ModularBot.srdf'\n # srdf_filename = path_superbuild + '/configs/ADVR_shared/ModularBot/srdf/ModularBot.srdf'\n # srdf_filename = self.urdf_writer.resource_finder.get_filename('srdf/ModularBot.srdf', 'modularbot_path')\n # srdf_filename = \"/tmp/modular/srdf/ModularBot.srdf\"\n \n # Generate srdf string\n srdf_string = self.control_plugin.write_srdf(builder_joint_map)\n\n # Compute Allowed Collision Matrix (ACM) using MoveIt!\n if compute_acm:\n srdf_string = self.add_acm_to_srdf(srdf_string)\n\n # Create folder if doesen't exist\n if not os.path.exists(os.path.dirname(srdf_filename)):\n try:\n os.makedirs(os.path.dirname(srdf_filename))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n\n with open(srdf_filename, 'w+') as f:\n f.write(srdf_string)\n\n return srdf_string\n \n def add_acm_to_srdf(self, srdf):\n \"\"\"Compute Allowed Collision Matrix (ACM) using MoveIt!\"\"\"\n \n try:\n # importing python bindings of https://github.com/ADVRHumanoids/moveit_compute_default_collisions\n from moveit_compute_default_collisions import pymcdc\n\n # ensure the urdf string has been already generated\n if getattr(self, 'urdf_string', None) is None:\n raise RuntimeError(\"URDF string not generated yet, please call write_urdf() or process_urdf() first\")\n\n # set verbosity level of the mcdc module\n if self.logger.level == logging.DEBUG:\n mcdc_verbose = True\n self.print(\"Allowed Collision Matrix (ACM) computation\")\n else:\n mcdc_verbose = False\n\n # generate acm and write it into srdf\n acm = pymcdc.MoveitComputeDefaultCollisions()\n acm.setVerbose(mcdc_verbose)\n acm.initFromString(self.urdf_string, srdf, False)\n acm.computeDefaultCollisions(int(1e5))\n if mcdc_verbose:\n acm.printDisabledCollisions()\n srdf_with_acm = acm.getXmlString()\n srdf = srdf_with_acm \n\n except ImportError:\n self.info_print(\"Cannot import moveit_compute_default_collisions (pymcdc), skipping ACM computation\")\n\n return srdf\n\n # Function writin the urdf file after converting from .xacro (See xacro/__init__.py for reference)\n def write_urdf(self):\n \"\"\"Returns the string with the URDF, after writing it to file\"\"\"\n global path_name # , path_superbuild\n\n urdf_filename = path_name + '/ModularBot/urdf/ModularBot.urdf'\n # urdf_filename = path_superbuild + '/configs/ADVR_shared/ModularBot/urdf/ModularBot.urdf'\n # urdf_filename = self.resource_finder.get_filename('urdf/ModularBot.urdf', 'modularbot_path')\n # urdf_filename= '/tmp/modular/urdf/ModularBot.urdf'\n out = xacro.open_output(urdf_filename)\n\n gazebo_urdf_filename = path_name + '/ModularBot/urdf/ModularBot.gazebo.urdf'\n gazebo_out = xacro.open_output(gazebo_urdf_filename)\n\n # get xml string from ET\n xmlstr = xml.dom.minidom.parseString(ET.tostring(self.urdf_tree.getroot())).toprettyxml(indent=\" \")\n\n # write preprocessed xml to file\n urdf_xacro_filename = path_name + '/ModularBot/urdf/ModularBot.urdf.xacro'\n # # urdf_xacro_filename = self.resource_finder.get_filename('urdf/ModularBot.urdf.xacro', 'modularbot_path')\n # # urdf_xacro_filename = '/tmp/modular/urdf/ModularBot.urdf.xacro'\n preprocessed_out = xacro.open_output(urdf_xacro_filename)\n preprocessed_out.write(xmlstr)\n preprocessed_out.close()\n\n # write the URDF for Gazebo\n string_urdf_gz = self.process_urdf(xacro_mappings={'gazebo_urdf': 'true', 'velodyne': 'true', 'realsense': 'true', 'ultrasound': 'true'})\n gazebo_out.write(string_urdf_gz)\n gazebo_out.close()\n\n # write the URDF\n string_urdf_xbot = self.process_urdf(xacro_mappings={'gazebo_urdf': 'false', 'velodyne': 'false', 'realsense': 'false', 'ultrasound': 'false'})\n out.write(string_urdf_xbot)\n out.close()\n\n self.urdf_string = string_urdf_xbot\n\n return string_urdf_xbot\n\n # Save URDF/SRDF etc. in a directory with the specified robot_name\n def deploy_robot(self, robot_name='modularbot', deploy_dir=None):\n script = self.resource_finder.get_filename('deploy.sh', ['data_path'])\n\n try:\n if deploy_dir is None:\n deploy_dir = self.resource_finder.get_expanded_path(['deploy_dir'])\n if self.verbose:\n output = subprocess.check_output([script, robot_name, \"--destination-folder\", deploy_dir, \"-v\"])\n else:\n output = subprocess.check_output([script, robot_name, \"--destination-folder\", deploy_dir])\n except (subprocess.CalledProcessError, FileNotFoundError, RuntimeError) as e:\n self.error_print(f\"An error occurred when executing deploy script: {script}. Aborting.\")\n raise e\n\n self.info_print(str(output, 'utf-8', 'ignore'))\n\n hubs = self.findall_by_type(types=ModuleClass.hub_modules())\n if hubs is not None:\n for hub_module in (hub for hub in hubs if hub.is_structural):\n self.add_connectors(hub_module)\n\n return robot_name\n\n # Remove connectors when deploying the robot\n def remove_all_connectors(self):\n\n # update generator expression\n self.update_generators()\n\n # Catch KeyError when the node has no child element and continue with the loop.\n for node in self.urdf_nodes_generator:\n try:\n node_type = node.attrib['type']\n if node_type == 'connectors':\n self.print('removing node:', node.attrib)\n self.root.remove(node)\n except KeyError:\n #self.print('missing type', node.attrib['name'])\n continue\n\n\n def findall_by_type(self, types=[]):\n # Serch the tree by name for the selected module\n modulenodes = anytree.search.findall(self.base_link, filter_=lambda node: node.type in types)\n return modulenodes\n\n def add_connectors(self, modulenode):\n max_num_con = 20\n for i in range(1, max_num_con):\n if hasattr(modulenode, 'Con_{}_tf'.format(i)):\n con_tf = getattr(modulenode, 'Con_{}_tf'.format(i))\n x, y, z, roll, pitch, yaw = ModuleNode.get_xyzrpy(con_tf)\n con_name = modulenode.name + '_con{}'.format(i)\n ET.SubElement(self.root,\n \"xacro:add_connector\",\n name=con_name,\n type='connectors',\n parent_name=modulenode.name,\n x=x,\n y=y,\n z=z,\n roll=roll,\n pitch=pitch,\n yaw=yaw)\n modulenode.xml_tree_elements.append(con_name)\n modulenode.mesh_names.append(con_name)\n modulenode.connectors.append(con_name)\n \n def compute_payload(self, samples):\n self.model_stats.update_model()\n return self.model_stats.compute_payload(n_samples=samples)\n \n\n def compute_stats(self, samples):\n self.model_stats.update_model()\n return self.model_stats.compute_stats(n_samples=samples)\n\n\nfrom contextlib import contextmanager\nimport sys, os\n\n\n@contextmanager\ndef suppress_stdout():\n \"\"\"\n context manager redirecting all output from stdout to\n stderr\n \"\"\"\n old_stdout = sys.stdout\n sys.stdout = sys.stderr\n try:\n yield\n finally:\n sys.stdout = old_stdout\n\n\ndef write_file_to_stdout(urdf_writer: UrdfWriter, homing_map, robot_name='modularbot'):\n\n import argparse\n parser = argparse.ArgumentParser(prog='Modular URDF/SRDF generator and deployer',\n usage='./script_name.py --output urdf writes URDF to stdout \\n./script_name.py --deploy deploy_dir generates a ros package at deploy_dir')\n\n parser.add_argument('--output', '-o', required=False, choices=('urdf', 'srdf'), help='write requested file to stdout and exit')\n parser.add_argument('--xacro-args', '-a', required=False, nargs='*', help='xacro arguments in key:=value format')\n parser.add_argument('--deploy', '-d', required=False, help='directory where to deploy the package')\n parser.add_argument('--robot-name', '-r', required=False, help='name of the robot')\n args = parser.parse_args()\n\n if args.robot_name is not None:\n robot_name = args.robot_name\n\n xacro_mappings = {}\n if args.xacro_args:\n for arg in args.xacro_args:\n key, value = arg.split(':=')\n xacro_mappings[key] = value\n\n content = None\n with suppress_stdout():\n\n urdf_writer.remove_all_connectors()\n\n if args.output == 'urdf':\n content = urdf_writer.process_urdf(xacro_mappings=xacro_mappings)\n open(f'/tmp/{robot_name}.urdf', 'w').write(content)\n\n elif args.output == 'srdf':\n urdf_writer.urdf_string = urdf_writer.process_urdf(xacro_mappings=xacro_mappings)\n content = urdf_writer.write_srdf(homing_map)\n open(f'/tmp/{robot_name}.srdf', 'w').write(content)\n\n if content is not None:\n print(content)\n\n if args.deploy is not None:\n urdf_writer.write_urdf()\n urdf_writer.write_lowlevel_config()\n urdf_writer.write_problem_description_multi()\n urdf_writer.write_srdf(homing_map)\n urdf_writer.write_joint_map()\n\n urdf_writer.deploy_robot(robot_name, args.deploy)\n","repo_name":"ADVRHumanoids/modular_hhcm","sub_path":"src/modular/URDF_writer.py","file_name":"URDF_writer.py","file_ext":"py","file_size_in_byte":179484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"37172869041","text":"#\n# File: AWESEM_Constants.py\n# ------------------------------\n# Author: Brion Ye\n# Date:\n#\n# Description:\n# This file holds all the project constant variables\n# and should be used mainly for debugging purposes.\n# All user-approved variables are handled through\n# the GUI instead.\n#\n# Edits:\n# - Erick Blankenberg, adapted to use teensy 3.6.\n#\n\nfrom PyQt5.QtGui import *\n\n# Math Constants\npi = 3.1415926535\nmill = 1000000\n\n# Size of scan area\ndefw = 400\ndefh = 400\n\n# Background Image\nIMG = QImage('grid.png')\n\n# Defaults\nXHz = 50 # Hertz\nYHz = 0.05\nXMag = 1.65 # Magnitude in volts\nYMag = 1.65\nXWave = 3 # Waveform: 0 = Sine, 1 = Sawtooth, 3 = Triangle\nYWave = 3\n\n# Resolution of generated waveform LUT\nwaveRes = 1000\n\n# Display Thread stats\nPIX_PER_UPDATE = 25000\nDISP_PERIOD = 1000 #?\n\n# Data Thread Stats\nADC_BUFFERSIZE = 1024 # NOTE: Check the PiPion firmware before changing this.\nADC_SAMPLEFREQUENCY = 14000 # Hertz, frequency of ADC sampling.\nADC_POLLPERIOD = 1.0 / float(ADC_SAMPLEFREQUENCY/ADC_BUFFERSIZE) * 0.9\nDISPLAY_POLLPERIOD = ADC_POLLPERIOD * 0.9","repo_name":"Eblanken/Prakash_AWESEM","sub_path":"Version 2.0/Software/Main/QT Application v3_PiPion/AWESEM_Constants.py","file_name":"AWESEM_Constants.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"13995196975","text":"from __future__ import division\n\ndescription = r'''\nCSV file to dataset.\n\nRead a CSV file, with any single character separator, with or without quotes.\nLabels from first line or specified in options.\n'''\n\n\nimport os\nimport cffi\n\nimport report\nfrom extras import OptionString\nimport blob\nimport gzutil\nfrom dataset import DatasetWriter\n\n\noptions = {\n\t'filename' : OptionString,\n\t'separator' : ',',\n\t'labelsonfirstline' : True,\n\t'labels' : [], # Mandatory if not labelsonfirstline, always sets labels if set.\n\t'hashlabel' : None,\n\t'quote_support' : False, # 'foo',\"bar\" style CSV\n\t'rename' : {}, # Labels to replace (if they are in the file) (happens first)\n\t'discard' : set(), # Labels to not include (if they are in the file)\n\t'allow_bad' : False, # Still succeed if some lines have too few/many fields.\n}\n\ndatasets = ('previous', )\n\n\nffi = cffi.FFI()\nffi.cdef('''\nint import_slice(const char *fn, const int slices, const int sliceno, const int skip_line, const int field_count, const char *out_fns[], const char separator, int hash_idx, uint64_t *res_num, const int quote_support);\n''')\nbackend = ffi.verify(r'''\n#include \n#include \n\n#define err1(v) if (v) goto err\n#define Z (128 * 1024)\n\ntypedef struct {\n\tgzFile fh;\n\tint len;\n\tint pos;\n\tchar buf[Z + 1];\n} g;\n\nstatic int read_chunk(g *g, int offset)\n{\n\tconst int len = gzread(g->fh, g->buf + offset, Z - offset);\n\tif (len <= 0) return 1;\n\tg->len = offset + len;\n\tg->buf[g->len] = 0;\n\tg->pos = 0;\n\treturn 0;\n}\n\nstatic char *read_line(g *g)\n{\n\tif (g->pos >= g->len) {\n\t\tif (read_chunk(g, 0)) return 0;\n\t}\n\tchar *ptr = g->buf + g->pos;\n\tchar *end = strchr(ptr, '\\n');\n\tif (!end) {\n\t\tconst int linelen = g->len - g->pos;\n\t\tmemmove(g->buf, g->buf + g->pos, linelen);\n\t\tif (read_chunk(g, linelen)) { // if eof\n\t\t\tg->pos = g->len;\n\t\t\tg->buf[linelen] = 0;\n\t\t\treturn linelen ? g->buf : 0;\n\t\t}\n\t\tptr = g->buf;\n\t\tend = strchr(ptr, '\\n');\n\t\tif (!end) end = ptr + g->len; // very long line - split it\n\t}\n\tconst int linelen = end - ptr;\n\tg->pos += linelen + 1;\n\tptr[linelen] = 0;\n\tif (linelen && ptr[linelen - 1] == '\\r') ptr[linelen - 1] = 0;\n\treturn ptr;\n}\n\n#define HANDLE_UNQUOTED \\\n\tdo { \\\n\t\tchar *end = strchr(line, separator); \\\n\t\tif (end) { \\\n\t\t\tif (i == field_count - 1) goto bad; \\\n\t\t\t*end = '\\n'; \\\n\t\t\tfield_len[i] = end - line; \\\n\t\t} else { \\\n\t\t\tif (i != field_count - 1) goto bad; \\\n\t\t\tfield_len[i] = strlen(line); \\\n\t\t\tline[field_len[i]] = '\\n'; \\\n\t\t} \\\n\t\tfield[i] = line; \\\n\t\tline = end + 1; \\\n\t} while (0)\n\nint import_slice(const char *fn, const int slices, const int sliceno, const int skip_line, const int field_count, const char *out_fns[], const char separator, int hash_idx, uint64_t *res_num, const int quote_support)\n{\n\tint res = 1;\n\tg g;\n\tg.fh = gzopen(fn, \"rb\");\n\tif (!g.fh) return 1;\n\tg.pos = g.len = 0;\n\tchar *line;\n\tif (skip_line) read_line(&g);\n\tgzFile outfh[field_count];\n\tfor (int i = 0; i < field_count; i++) {\n\t\toutfh[i] = 0;\n\t}\n\tPyGILState_STATE gstate = PyGILState_Ensure();\n\tuint64_t (*hash)(const void *ptr, const uint64_t len) = PyCapsule_Import(\"gzutil._C_hash\", 0);\n\terr1(!hash);\n\tfor (int i = 0; i < field_count; i++) {\n\t\tif (out_fns[i]) {\n\t\t\toutfh[i] = gzopen(out_fns[i], \"ab\");\n\t\t\terr1(!outfh[i]);\n\t\t}\n\t}\n\tlong lineno = -1;\n\twhile ((line = read_line(&g))) {\n\t\tlineno++;\n\t\tif (hash_idx == -1) {\n\t\t\tif (lineno % slices != sliceno) continue;\n\t\t}\n\t\tchar *field[field_count];\n\t\tint field_len[field_count];\n\t\tif (quote_support) {\n\t\t\tfor (int i = 0; i < field_count; i++) {\n\t\t\t\tif (*line == '\"' || *line == '\\'') {\n\t\t\t\t\tconst char q = *line;\n\t\t\t\t\tchar *end = line + 1;\n\t\t\t\t\twhile (*end) {\n\t\t\t\t\t\tend = strchr(end, q);\n\t\t\t\t\t\tif (!end // Broken quoting. How regrettable.\n\t\t\t\t\t\t || !end[1] // EOL\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tif (end) end++; // pretend separator\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (end[1] == separator) {\n\t\t\t\t\t\t\tend++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// we'll just assume it was a quote, because what else to do?\n\t\t\t\t\t\tend += 2;\n\t\t\t\t\t}\n\t\t\t\t\tint len;\n\t\t\t\t\tchar *ptr = line;\n\t\t\t\t\tif (end) {\n\t\t\t\t\t\tlen = end - line;\n\t\t\t\t\t\tline = end;\n\t\t\t\t\t\tif (*line) {\n\t\t\t\t\t\t\tif (i == field_count - 1) goto bad; // too many fields\n\t\t\t\t\t\t\tline++;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (i != field_count - 1) goto bad; // too few fields\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (i != field_count - 1) goto bad;\n\t\t\t\t\t\tlen = strlen(line);\n\t\t\t\t\t}\n\t\t\t\t\t// Field is still quoted, now we remove that.\n\t\t\t\t\tlen--; // separator\n\t\t\t\t\tif (ptr[len] == q) len--; // end quote, if it's there\n\t\t\t\t\tptr++; // start quote\n\t\t\t\t\tfor (int j = 0; j < len - 1; j++) { // collapse doubles\n\t\t\t\t\t\tif (ptr[j] == q && ptr[j + 1] == q) {\n\t\t\t\t\t\t\tmemmove(ptr + j + 1, ptr + j + 2, len - j - 2);\n\t\t\t\t\t\t\tj++;\n\t\t\t\t\t\t\tlen--;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tptr[len] = '\\n';\n\t\t\t\t\tfield[i] = ptr;\n\t\t\t\t\tfield_len[i] = len;\n\t\t\t\t} else {\n\t\t\t\t\tHANDLE_UNQUOTED;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor (int i = 0; i < field_count; i++) {\n\t\t\t\tHANDLE_UNQUOTED;\n\t\t\t}\n\t\t}\n\t\tif (hash_idx != -1) {\n\t\t\tint h = hash(field[hash_idx], field_len[hash_idx]) % slices;\n\t\t\tif (h != sliceno) continue;\n\t\t}\n\t\tfor (int i = 0; i < field_count; i++) {\n\t\t\tif (outfh[i]) {\n\t\t\t\tconst int len = field_len[i] + 1;\n\t\t\t\terr1(gzwrite(outfh[i], field[i], len) != len);\n\t\t\t}\n\t\t}\n\t\tres_num[1]++;\n\t\tcontinue;\nbad:\n\t\tif (!res_num[0]) {\n\t\t\tprintf(\"Line %ld bad (further bad lines in slice %d not reported)\\n\", lineno, sliceno);\n\t\t}\n\t\tres_num[0]++;\n\t}\n\tres = 0;\nerr:\n\tfor (int i = 0; i < field_count; i++) {\n\t\tif (outfh[i] && gzclose(outfh[i])) res = 1;\n\t}\n\tgzclose(g.fh);\n\tPyGILState_Release(gstate);\n\treturn res;\n}\n''', libraries=['z'], extra_compile_args=['-std=c99'])\n\ndef prepare(SOURCE_DIRECTORY):\n\tseparator = options.separator\n\tassert len(separator) == 1\n\tfilename = os.path.join(SOURCE_DIRECTORY, options.filename)\n\torig_filename = filename\n\n\tif filename.lower().endswith('.zip'):\n\t\tfrom zipfile import ZipFile\n\t\tfilename = 'extracted'\n\t\twith ZipFile(orig_filename, 'r') as z:\n\t\t\tinfos = z.infolist()\n\t\t\tassert len(infos) == 1, 'There is only support for ZIP files with exactly one member.'\n\t\t\t# Wouldn't it be nice if ZipFile.extract let me choose the filename?\n\t\t\twith open(filename, 'wb') as ofh:\n\t\t\t\tzfh = z.open(infos[0])\n\t\t\t\twhile True:\n\t\t\t\t\tdata = zfh.read(1024 * 1024)\n\t\t\t\t\tif not data:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tofh.write(data)\n\n\tif options.labelsonfirstline:\n\t\twith gzutil.GzBytesLines(filename, strip_bom=True) as fh:\n\t\t\tlabels_str = next(fh).decode('ascii', 'replace').encode('ascii', 'replace') # garbage -> '?'\n\t\tif options.quote_support:\n\t\t\tlabels = []\n\t\t\tsep = options.separator\n\t\t\twhile labels_str is not None:\n\t\t\t\tif labels_str.startswith(('\"', \"'\",)):\n\t\t\t\t\tq = labels_str[0]\n\t\t\t\t\tpos = 1\n\t\t\t\t\twhile pos + 1 < len(labels_str):\n\t\t\t\t\t\tpos = labels_str.find(q, pos)\n\t\t\t\t\t\tif pos == -1: # all is lost\n\t\t\t\t\t\t\tpos = len(labels_str) - 1\n\t\t\t\t\t\tif pos + 1 == len(labels_str): # eol\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tif labels_str[pos + 1] == sep:\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t# we'll just assume it was a quote, because what else to do?\n\t\t\t\t\t\tlabels_str = labels_str[:pos] + labels_str[pos + 1:]\n\t\t\t\t\t\tpos += 1\n\t\t\t\t\tlabels.append(labels_str[1:pos])\n\t\t\t\t\tif len(labels_str) > pos + 1:\n\t\t\t\t\t\tlabels_str = labels_str[pos + 2:]\n\t\t\t\t\telse:\n\t\t\t\t\t\tlabels_str = None\n\t\t\t\telse:\n\t\t\t\t\tif sep in labels_str:\n\t\t\t\t\t\tfield, labels_str = labels_str.split(sep, 1)\n\t\t\t\t\telse:\n\t\t\t\t\t\tfield, labels_str = labels_str, None\n\t\t\t\t\tlabels.append(field)\n\t\telse:\n\t\t\tlabels = labels_str.split(options.separator)\n\tlabels = options.labels or labels # only from file if not specified in options\n\tassert labels, \"No labels\"\n\tlabels = [options.rename.get(x, x) for x in labels]\n\tassert '' not in labels, \"Empty label for column %d\" % (labels.index(''),)\n\tassert len(labels) == len(set(labels)), \"Duplicate labels: %r\" % (labels,)\n\n\tdw = DatasetWriter(\n\t\tcolumns={n: 'bytes' for n in labels},\n\t\tfilename=orig_filename,\n\t\thashlabel=options.hashlabel,\n\t\tcaption='csvimport of ' + orig_filename,\n\t\tprevious=datasets.previous,\n\t\tmeta_only=True,\n\t)\n\n\treturn separator, filename, orig_filename, labels, dw,\n\n\ndef analysis(sliceno, prepare_res, params):\n\t\"\"\" reading complete file, writing to this slice only\"\"\"\n\n\tseparator, filename, _, labels, dw = prepare_res\n\n\tif options.hashlabel:\n\t\thash_ix = labels.index(options.hashlabel)\n\telse:\n\t\thash_ix = -1\n\n\tcopied_lines = 0\n\tn_labels = len(labels)\n\n\tres_num = ffi.new('uint64_t [2]')\n\tres_num[0] = 0 # broken_lines\n\tres_num[1] = copied_lines\n\tout_fns = [ffi.NULL if l in options.discard else ffi.new('char []', dw.column_filename(l).encode('ascii')) for l in labels]\n\terr = backend.import_slice(filename, params.slices, sliceno, options.labelsonfirstline, n_labels, out_fns, separator, hash_ix, res_num, options.quote_support)\n\tassert not err, \"c import_slice returned error\"\n\n\tres = dict(\n\t\tnum_broken_lines = res_num[0],\n\t\tnum_lines = res_num[1],\n\t)\n\treturn res\n\n\n\ndef synthesis(prepare_res, analysis_res, params):\n\tfrom math import sqrt\n\n\tseparator, filename, orig_filename, labels, dw = prepare_res\n\tlabels = [n for n in labels if n not in options.discard]\n\n\tif filename != orig_filename:\n\t\tos.unlink(filename)\n\n\t# aggregate typing and statistics\n\tres = {}\n\tres['num_broken_lines'] = 0\n\tres['num_lines'] = 0\n\tres['lines_per_slice'] = []\n\tfor sliceno, tmp in enumerate(analysis_res):\n\t\tres['num_broken_lines'] += tmp['num_broken_lines']\n\t\tres['num_lines'] += tmp['num_lines']\n\t\tres['lines_per_slice'].append(tmp['num_lines'])\n\t\tdw.set_lines(sliceno, tmp['num_lines'])\n\n\tblob.save(res, 'import')\n\n\t# write report\n\tr = report.report()\n\tif not res['num_lines']:\n\t\tr.println('No lines read - empty file!')\n\t\tr.close()\n\t\treturn\n\tr.println('Number of rows read\\n')\n\tr.println(' slice lines')\n\tfor sliceno, nlines in enumerate(res['lines_per_slice']):\n\t\tif res['num_lines']:\n\t\t\tr.println(' %2d %9d (%6.2f%%)' %(sliceno, nlines, 100*nlines/res['num_lines']))\n\t\telse:\n\t\t\tr.println(' %2d %9d ' %(sliceno, nlines, 100*nlines/res['num_lines']))\n\tr.println(' total %9d' %(res['num_lines'],))\n\tstdev = sqrt(sum((x-res['num_lines']/params.slices)**2 for x in res['lines_per_slice'])/params.slices)\n\tr.println('\\n hash stdev %9d (%6.2f%%)' % (stdev, round(100*stdev/res['num_lines'])))\n\tr.line()\n\n\tr.println('Number of columns %9d' % len(labels,))\n\tr.close()\n\n\tif res['num_broken_lines'] and not options.allow_bad:\n\t\traise Exception('%d bad lines without options.allow_bad' % (res['num_broken_lines'],))\n","repo_name":"linusw/ExpertmakerAccelerator","sub_path":"default_analysis/a_csvimport.py","file_name":"a_csvimport.py","file_ext":"py","file_size_in_byte":10544,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"39835065284","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport urllib2\nimport re\nimport csv\nfrom BeautifulSoup import BeautifulSoup\n\nOUTPUT_CSV = 'output.csv'\nCONTENTS_URL = 'http://www.cikrf.ru/newsite/politparty/reg_politparty.jsp'\nENCODING = 'cp1251'\nTITLE = [\n u'Наименование',\n u'Дата регистрации',\n u'Регистрационный номер',\n u'Адрес интернет-сайта',\n]\n\ndef writeRow(data):\n data = [unicode(value).encode('utf-8').strip() for value in data]\n output.writerow(data)\n\noutput = csv.writer(open(OUTPUT_CSV, 'wb'), delimiter=';', quotechar='\"', )\nwriteRow(TITLE)\n\nconnection = urllib2.urlopen(CONTENTS_URL)\ncontents = BeautifulSoup(connection, fromEncoding=ENCODING, convertEntities=BeautifulSoup.HTML_ENTITIES)\nheader = contents.find('h3')\ntable = header.findNext('table')\nrows = table.findAll('tr')[1:]\n\nfor row in rows:\n cells = row.findAll('td')[1:]\n values = [' '.join(cell.findAll(text=True)).replace('\\n', ' ') for cell in cells]\n writeRow(values)","repo_name":"arty-name/Open-Data-Parsers","sub_path":"Перечень зарегистрированных политических партий/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"46"} +{"seq_id":"17191836806","text":"import aiohttp\nimport asyncio\nimport threading\n\nfrom classes.EventSource import EventSource\n\nAPI_BASEURL = \"http://localhost:8000\"\n\nAPI_GET_HELLO = \"/api/hello\"\nAPI_POST_CREATE_GAME = \"/api/chess\"\nAPI_POST_SAVE_MOVE = \"/api/chess/{id}/move/{move}\"\nAPI_GET_SUGGEST_MOVE = \"/api/chat/{id}/suggest\"\nAPI_GET_CHAT = \"/api/chat/{id}?message={message}\"\n\n\nclass ApiError:\n def __init__(self, message: str = \"\", source: str = \"\", status: int = 0):\n self.message = message\n self.source = source\n self.status = status\n\n\nclass ApiGameCreated:\n def __init__(self, data: dict):\n self.data = data\n\n @property\n def id(self) -> int:\n return self.data[\"id\"]\n\n @property\n def fen(self) -> str:\n return self.data[\"fen\"]\n\n\nclass ApiMove:\n def __init__(self, data: dict):\n self.data = data\n\n @property\n def id(self) -> int:\n return self.data[\"id\"]\n\n @property\n def fen(self) -> str:\n return self.data[\"fen\"]\n\n @property\n def uci(self) -> str:\n return self.data[\"uci\"]\n\n @property\n def ply(self) -> int:\n return self.data[\"ply\"]\n\n @property\n def san(self) -> str:\n return self.data[\"san\"]\n\n @property\n def turn(self) -> int:\n return (self.data[\"ply\"] + 1) % 2\n\n @property\n def outcome(self) -> str:\n return self.data[\"outcome\"]\n\n\nclass ChatGptApi(object):\n def __init__(self):\n self.game_data: ApiGameCreated = None\n\n self.loop = asyncio.new_event_loop()\n\n ## Start a new thread that will exit when the main thread ends (daemon=True)\n threading.Thread(\n target=self.loop.run_forever, daemon=True, name=\"ChatGptApi\"\n ).start()\n\n self.on_api_hello = EventSource(\"on_api_hello\")\n self.on_api_error = EventSource(\"on_api_error\")\n self.on_api_moved = EventSource(\"on_api_moved\")\n self.on_api_suggest = EventSource(\"on_api_suggest\")\n self.on_api_chat = EventSource(\"on_api_chat\")\n self.on_api_created = EventSource(\"on_api_created\")\n\n @property\n def id(self) -> int:\n return self.game_data.id if self.game_data else 0\n\n def hello(self):\n \"\"\"Greetings from the API\"\"\"\n asyncio.run_coroutine_threadsafe(self._hello(), self.loop)\n\n async def _hello(self):\n await self._invoke(\"get\", API_GET_HELLO, self.on_api_hello)\n\n def create_game(self) -> str:\n \"\"\"Create a new game\"\"\"\n asyncio.run_coroutine_threadsafe(self._create_game(), self.loop)\n\n async def _create_game(self):\n await self._invoke(\n \"post\",\n API_POST_CREATE_GAME,\n self._save_game,\n json={\"event\": \"ChessGPT\"},\n )\n\n def _save_game(self, data):\n self.game_data = ApiGameCreated(data)\n self.on_api_created(self.game_data)\n\n def make_move(self, move: str):\n \"\"\"Make a move in the game\"\"\"\n asyncio.run_coroutine_threadsafe(self._make_move(move), self.loop)\n\n async def _make_move(self, move: str):\n await self._invoke(\n \"post\",\n API_POST_SAVE_MOVE.format(id=self.id, move=move),\n lambda data: self.on_api_moved(ApiMove(data)),\n )\n\n def suggest_move(self):\n \"\"\"Suggest a move in the game\"\"\"\n asyncio.run_coroutine_threadsafe(self._suggest_move(), self.loop)\n\n async def _suggest_move(self):\n await self._invoke(\n \"get\",\n API_GET_SUGGEST_MOVE.format(id=self.id),\n self.on_api_suggest,\n )\n\n def chat(self, message: str):\n \"\"\"Send a message in the game\"\"\"\n asyncio.run_coroutine_threadsafe(self._chat(message), self.loop)\n\n async def _chat(self, message: str):\n await self._invoke(\n \"get\",\n API_GET_CHAT.format(id=self.id, message=message),\n self.on_api_chat,\n )\n\n async def _invoke(self, method: str, url: str, callback: callable, json=None):\n try:\n async with aiohttp.ClientSession() as session:\n async with session.request(\n method, API_BASEURL + url, json=json\n ) as response:\n if response.status == 200:\n if response.content_type == \"application/json\":\n data = await response.json()\n callback(data)\n else:\n data = await response.text()\n callback(data)\n elif response.status == 400:\n error = await response.json()\n self.on_api_error(\n ApiError(\n source=url,\n status=response.status,\n message=error[\"error\"],\n )\n )\n else:\n self.on_api_error(\n ApiError(\n source=url,\n status=response.status,\n message=response.reason,\n )\n )\n except Exception as e:\n self.on_api_error(ApiError(source=url, message=str(e), status=0))\n","repo_name":"jsuddsjr/chessgpt","sub_path":"game/classes/ChatGptApi.py","file_name":"ChatGptApi.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"21744486957","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport json\nimport datetime\nfrom matplotlib.colors import Normalize, LogNorm\nfrom read_Kp import read_Kp\n\nnorm = LogNorm(vmin=1e-10, vmax=1e-4)\nfigsize = (15,5)\n\nMINTIME = datetime.datetime(datetime.MINYEAR, 1, 1)\n\ndef time_to_days(t):\n \"\"\"\n Takes a time (t) in the form of datetime.datetime and returns the\n number of days since January 1st in datetime.MINYEAR.\n\n Parameters:\n\n t (datetime.datetime) : Any time.\n\n Returns:\n\n days (float) : The number of days by which t is after January\n 1st in datetime.MINYEAR\n \"\"\"\n delta = t-MINTIME\n return delta.total_seconds()/86400\n\ndef days_to_time(d):\n \"\"\"\n Takes a (float) number of days and returns the datetime.datetime\n that number of days after January 1st in datetime.MINYEAR.\n\n Parameters:\n\n days (float) : Any positive number of days.\n\n Returns:\n\n t (datetime.datetime) : The time d days after January 1st in\n datetime.MINYEAR\n \"\"\"\n return MINTIME + datetime.timedelta(days=d)\n\nif __name__ == \"__main__\":\n dir_path = \"example\"\n with open(dir_path + '/models_input.json', \"r\") as inputJSON:\n models_input = json.load(inputJSON)\n L_range = models_input[\"L_range\"]\n t_range = models_input[\"t_range\"]\n print(t_range)\n VAP_PSD = np.array(models_input[\"PSD\"])\n VAP_points = np.array(models_input[\"VAP_points\"])\n with open(dir_path + '/models_output.json', \"r\") as outputJSON:\n models_output = json.load(outputJSON)\n diffusion_PSD = np.array(models_output[\"diffusion_output\"])\n kalman_PSD = np.array(models_output[\"kalman_output\"])\n innovation = np.array(models_output[\"innovation\"])\n\n def pcolor_data_from_PSD(PSD):\n nT, nL = PSD.shape\n times = np.vectorize(days_to_time)(np.linspace(t_range[0], t_range[1], nT))\n Li = np.linspace(L_range[0], L_range[1], nL)\n X = np.array([times for i in range(nL)])\n Y = np.transpose([Li for i in range(nT)])\n Z = np.transpose(PSD)\n assert X.shape == Y.shape == Z.shape\n return X, Y, Z\n\n Kp_data = read_Kp(dir_path + \"/Kp_data.lst\")\n Kp_times = list(sorted(Kp_data.keys()))\n Kp_times = [t for t in Kp_times if days_to_time(t_range[0]) <= t <=\n days_to_time(t_range[1])]\n Kp_values = [Kp_data[t] for t in Kp_times]\n assert(Kp_times != [])\n plt.figure(figsize=figsize)\n plt.title(\"Kp data\")\n plt.plot(Kp_times, Kp_values)\n plt.xlabel('Time')\n plt.ylabel('Kp')\n plt.xticks(rotation=90)\n plt.tight_layout()\n plt.savefig(dir_path + \"/Kp.png\")\n plt.show()\n\n X, Y, Z = pcolor_data_from_PSD(VAP_PSD)\n plt.figure(figsize=figsize)\n c = plt.pcolor(X, Y, Z, norm=norm, cmap=plt.cm.rainbow)\n cbar = plt.colorbar(c)\n cbar.set_label('Density $(c/(cm MeV))^3/sr$', rotation=270)\n plt.title(\"Interpolated Van Allen Probe PSD\")\n plt.xlabel('Time')\n plt.ylabel('L $(R_E)$')\n plt.xticks(rotation=90)\n plt.tight_layout()\n plt.savefig(dir_path + \"/VAP_interpolated.png\")\n plt.show()\n\n X, Y, Z = pcolor_data_from_PSD(VAP_points)\n plt.figure(figsize=figsize)\n c = plt.pcolor(X, Y, Z, norm=norm, cmap=plt.cm.rainbow)\n cbar = plt.colorbar(c)\n cbar.set_label('Density $(c/(cm MeV))^3/sr$', rotation=270)\n plt.title(\"Van Allen Probe Point Densities\")\n plt.xlabel('Time')\n plt.ylabel('L $(R_E)$')\n plt.xticks(rotation=90)\n plt.tight_layout()\n plt.savefig(dir_path + \"/VAP_points.png\")\n plt.show()\n\n X, Y, Z = pcolor_data_from_PSD(diffusion_PSD)\n plt.figure(figsize=figsize)\n plt.title(\"Diffusion Model PSD\")\n c = plt.pcolor(X, Y, Z, norm=norm, cmap=plt.cm.rainbow)\n cbar = plt.colorbar(c)\n cbar.set_label('Density $(c/(cm MeV))^3/sr$', rotation=270)\n plt.xlabel('Time')\n plt.ylabel('L $(R_E)$')\n plt.xticks(rotation=90)\n plt.tight_layout()\n plt.savefig(dir_path + \"/Diffusion_model.png\")\n plt.show()\n\n X, Y, Z = pcolor_data_from_PSD(kalman_PSD)\n plt.figure(figsize=figsize)\n c=plt.pcolor(X, Y, Z, norm=norm, cmap=plt.cm.rainbow)\n cbar = plt.colorbar(c)\n plt.title(\"Kalman Model PSD\")\n cbar.set_label('Density $(c/(cm MeV))^3/sr$', rotation=270)\n plt.xlabel('Time')\n plt.ylabel('L $(R_E)$')\n plt.xticks(rotation=90)\n plt.tight_layout()\n plt.savefig(dir_path + \"/Kalman_model.png\")\n plt.show()\n\n Li = np.linspace(L_range[0], L_range[1], innovation.shape[1])\n plt.figure(figsize=figsize)\n plt.plot(Li, np.nanmean(innovation, axis=0))\n plt.title(\"EnKF Innovation averaged through time\")\n plt.xlabel('L $(R_E)$')\n plt.ylabel('Innovation')\n plt.savefig(dir_path + '/EnKF_innovation.png')\n plt.show()\n","repo_name":"alexjradcliffe/bas-project","sub_path":"plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":4810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"14636492978","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDodge Ball 13-1: \n 可以輕易地建立兩顆球\n \n@author: Jeff\n\"\"\"\n\nimport pygame\nimport math, random\n\n#常數 - 視窗寬、高\nSCREEN_WIDTH = 640\nSCREEN_HEIGHT = 480\n\n#常數 - 顏色\nBLACK = ( 0, 0, 0)\nWHITE = (255, 255, 255)\nRED = (255, 0, 0)\nGREEN = ( 0, 255, 0)\nBLUE = ( 0, 0, 255)\n\n#球的類別\nclass Ball:\n def __init__(self):\n self.R = 25 #球所有的的變數全部搬過來\n self.SPEED = 10\n self.ANGLE = random.randint(1, 360)/180*math.pi \n self.x = random.randint(self.R, SCREEN_WIDTH-self.R)\n self.y = random.randint(self.R, SCREEN_HEIGHT-self.R)\n self.x_speed = self.SPEED * math.sin(self.ANGLE)\n self.y_speed = self.SPEED * math.cos(self.ANGLE)\n \n def move(self):\n self.x += self.x_speed #所有變數 ball_ 變成 ball.\n self.y += self.y_speed\n if self.x+self.R > SCREEN_WIDTH or self.x-self.R < 0:\n self.x_speed *= -1\n if self.y+self.R > SCREEN_HEIGHT or self.y-self.R < 0:\n self.y_speed *= -1\n\n#主程式\ndef main():\n\n pygame.init()\n screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))\n pygame.display.set_caption(\"Dodge Ball\")\n\n clock = pygame.time.Clock()\n \n ball_list = []\n for i in range(2): #建立兩顆球\n ball = Ball()\n ball_list.append(ball)\n \n running = True\n while running:\n \n #輸入\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n \n #計算\n for ball in ball_list: #兩顆球都要移動\n ball.move()\n \n #更新畫面\n screen.fill(WHITE)\n for ball in ball_list: #兩顆球都要被畫出來\n pygame.draw.circle(screen, BLUE, (ball.x,ball.y), ball.R)\n \n \n clock.tick(30)\n pygame.display.update()\n \n \n pygame.quit()\n\n\n#程式起點\nif __name__ == \"__main__\":\n main()","repo_name":"JeffCodingMentor/myPyLessons","sub_path":"pygame/DodgeBall/D13-1.py","file_name":"D13-1.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"71207352138","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport numpy_indexed as npi\nimport time\nimport os\ndef ComputeKmeans(x, y, label, total_data, num_centroids):\n \"\"\"\n Cluster a dataset using Kmeans Method\n :param x:\n :param y:\n :param label:\n :param total_data:\n :param num_centroids:\n :return:\n \"\"\"\n matrix = np.column_stack((x, y))\n data = np.zeros((total_data, 3))\n data[:, :2] = matrix\n s = False\n while (not s):\n try:\n c_test = num_centroids # number of centroids guessed\n centroidx = []\n centroidy = []\n flag = False\n centroidupx = np.zeros(c_test)\n centroidupy = np.zeros(c_test)\n comp = np.zeros(int(c_data))\n for i in xrange(c_test):\n if ((comp.sum() == c_data) and (i < c_test)):\n comp = np.zeros(int(c_data))\n while (not flag):\n j = np.random.randint(0, int(c_data))\n if comp[j] == 0:\n comp[j] = 1\n flag = True\n centroidx = np.append(centroidx, np.random.normal(np.random.randint(10, 60), np.random.randint(5, 10), 1))\n centroidy = np.append(centroidy, np.random.normal(np.random.randint(10, 60), np.random.randint(5, 10), 1))\n flag = False\n centroids = np.column_stack((centroidx, centroidy))\n new_label_new = np.zeros(matrix[:, 0].size)\n new_label_old = np.ones(matrix[:, 0].size)\n dist = np.zeros(centroids[:, 0].size)\n iter = 0\n # looping until no data point were reassingned\n while (iter < 50):\n a = np.zeros((c_test, 1))\n for i in xrange(matrix[:, 0].size):\n for j in xrange(centroids[:, 0].size):\n dist[j] = np.sqrt(sum((matrix[i, :] - centroids[j, :]) ** 2))\n new_label_new[i], = np.where(dist == dist.min())\n if (np.array_equal(new_label_new, new_label_old)):\n break;\n s = True\n else:\n new_label_old = np.copy(new_label_new)\n unique = np.unique(new_label_new)\n data[:, 2] = new_label_new\n for i in xrange(new_label_new.size):\n for j in xrange(unique.size):\n if (new_label_old[i] == unique[j]):\n a[j] = a[j] + 1\n\n centroidup = npi.GroupBy(data[:, 2]).sum(data)[1]\n centroidup = centroidup[:, :2]\n centroids = centroidup / a\n centroidupx = centroids[:, 0]\n centroidupy = centroids[:, 1]\n s = True\n\n plt.scatter(x, y, c=new_label_new, cmap='rainbow')\n plt.scatter(centroidx, centroidy, c='green', marker='8')\n plt.scatter(centroidupx, centroidupy, c='black')\n plt.grid(True)\n plt.show()\n iter = iter + 1\n\n except Exception as e:\n print (str(e))\n return matrix, centroids, data","repo_name":"cafeemymelo/KMEANS","sub_path":"Kmeans/kmeansMethod.py","file_name":"kmeansMethod.py","file_ext":"py","file_size_in_byte":3226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"17686920611","text":"# 시은 풀이 - 시간 초과\nclass Solution(object):\n def maxProfit(self, prices):\n max_profit = 0\n\n for i, buy_price in enumerate(prices[:-1]):\n sell_price = max(prices[i + 1:])\n profit = sell_price - buy_price\n max_profit = max(profit, max_profit)\n\n return max_profit\n\n# 시은 풀이 - 1068ms\nclass Solution2(object):\n def maxProfit(self, prices):\n n = len(prices)\n\n # buy[i]: min(buy[i-1], prices[i])\n # : i번째 날까지의 최저점\n buy = [prices[0]] + [0 for i in range(n - 1)]\n\n for i in range(1, n):\n buy[i] = min(buy[i - 1], prices[i])\n\n # sell[i]: max(sell[i+1], prices[i])\n # : i번째 날부터의 최고점\n sell = [0 for i in range(n - 1)] + [prices[-1]]\n\n for i in reversed(range(0, n - 1)):\n sell[i] = max(sell[i + 1], prices[i])\n\n # profit[i]: sell[i] - buy[i]\n # : i번째 날 최고 수익\n profit = [sell[i] - buy[i] for i in range(n)]\n\n # 최고 수익 반환\n return max(profit)\n\n# 교재 풀이 - 1715ms\nclass Solution2(object):\n def maxProfit(self, prices):\n max_profit = 0\n min_price = sys.maxsize\n\n for price in prices:\n max_profit = max(price - min_price, max_profit)\n min_price = min(price, min_price)\n\n return max_profit\n\n","repo_name":"taeyoungYoo/Algorithm-GoogleMLBootcamp","sub_path":"Array/[Leet] 121_Best Time to Buy and Sell Stock/121_sieun.py","file_name":"121_sieun.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"46"} +{"seq_id":"30139097328","text":"\"\"\"class Learning\"\"\" \nclass Dog:\n \n tricks = []\n \n # kind = 'canine'\n \n def __init__(self,name):\n self.name = name\n \n def add_tricks(self,trick):\n self.tricks.append(trick) \nd = Dog('Fido') \ne = Dog('Buddy') \nd.add_tricks('roll over') \ne.add_tricks('play dead') \n# print(d.kind)\nprint(d.name)\n# print(e.kind)\nprint(e.name)\nprint(d.tricks)\nprint(e.tricks)","repo_name":"slayerten/2022_new_python","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"73046931658","text":"import pytest\nfrom pyrocoto import Workflow, Task, Offset, DataDep, TaskDep\nimport os\nfrom distutils import dir_util\n\n\n@pytest.fixture\ndef data_dir(tmpdir, request):\n '''\n Fixture responsible for searching a folder with the same name of test\n module and, if available, moving all contents to a temporary directory so\n tests can use them freely.\n '''\n os.chdir(str(tmpdir))\n file = request.module.__file__\n test_dir, _ = os.path.split(file)\n basename = os.path.splitext(file)[0]\n print(test_dir)\n testdata = os.path.join(test_dir,basename)\n print(testdata)\n if os.path.isdir(testdata):\n print(testdata)\n print(str(tmpdir))\n dir_util.copy_tree(testdata, str(tmpdir))\n return tmpdir\n\n\n#@pytest.fixture\n#def setup(data_dir):\n# config=configparser.ConfigParser()\n# configfile = 'pyrocoto.ini'\n# test_settings = {'account': 'test_account',\n# 'walltime': '00:20:00',\n# 'maxtries': '2',\n# 'queue': 'test_queue',\n# 'memory': '4000M',\n# 'cores': '1'}\n# config['default'] = test_settings\n# with open(configfile,'w') as f:\n# config.write(f)\n\nclass MySerialTask(Task):\n def __init__(self, d):\n ''' set a bunch of default settings '''\n self.account = 'myproject'\n self.cores = '1'\n self.memory = '2G'\n self.queue = 'queue_for_my_serial_task'\n self.walltime = '00:10:00'\n super().__init__(d)\n\n\n\n\ndef test_mytasks_workflow(data_dir, request):\n\n flow = Workflow(_shared=False)\n hourly = flow.define_cycle('hourly','0 * * * * *')\n\n bunch_of_args = ['thing1', 'thing2', 'thing3']\n for arg in bunch_of_args:\n @flow.task()\n def task():\n name = f'task{arg}'\n cycledefs = hourly\n command = f'/runcommand @Y@m@d@H {arg}'\n jobname = f'task1_@Y@m@d@H_{arg}'\n join = f'/task1_@Y@m@d@H_{arg}.join'\n dependency = DataDep(f'file_needed_for_{arg}')\n return MySerialTask(locals())\n\n\n flow.set_log('log_task.@Y@m@d@H')\n\n wf_name = request.node.name[5:]\n wf_file = f'{wf_name}.xml'\n flow.write_xml(str(data_dir.join(wf_file)))\n\n validationfile = f'{wf_name}.validate'\n with open(validationfile) as f, open(wf_file) as f2:\n assert f.read() == f2.read()\n\ndef test_shared_workflow(data_dir, request):\n\n flow = Workflow()\n hourly = flow.define_cycle('hourly','0 * * * * *')\n\n @flow.task()\n def task1():\n name = 'task1'\n cycledefs = hourly\n command = '/runcommand @Y@m@d@H'\n jobname = 'task1_@Y@m@d@H'\n join = '/task1_@Y@m@d@H.join'\n dependency = DataDep('file_needed')\n return MySerialTask(locals())\n\n flow = Workflow()\n print(flow.tasks)\n\n @flow.task()\n def task2():\n name = f'task2'\n cycledefs = 'hourly'\n final = 'true'\n command = '/runcommand @Y@m@d@H'\n jobname = 'task2_@Y@m@d@H'\n join = '/task2_@Y@m@d@H_{arg}.join'\n dependency = TaskDep('task1')\n return MySerialTask(locals())\n\n flow.set_log('log_task.@Y@m@d@H')\n\n wf_name = request.node.name[5:]\n wf_file = f'{wf_name}.xml'\n flow.write_xml(str(data_dir.join(wf_file)))\n\n validationfile = f'{wf_name}.validate'\n with open(validationfile) as f, open(wf_file) as f2:\n assert f.read() == f2.read()\n","repo_name":"AdamSchnapp/pyrocoto","sub_path":"tests/integ/test_custom_tasks.py","file_name":"test_custom_tasks.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"74994123019","text":"def get_protein_dict(cif_data):\n \"\"\" Parse cif_data dict for a subset of its data.\n\n Notes\n -----\n cif_data dict contains all the data from the .cif file, with values as strings.\n This function returns a more 'human readable' dictionary of key-value pairs.\n The keys have simpler (and still often more descriptive!) names, and the values are not restricted to being strings.\n To add more key-value pairs to the protein_dict, follow the patterns used in this function.\n Add the key and youre name for it to mmcif_data_names.\n Will it need further parsing, like with the dates in the function below?\n If the value is not a string, add it to a list of data-types at the end of the function.\n More information on what key-value pairs can be obtained can be gleaned by examining cif_data and/or by viewing the\n mmcif resource on the PDB website: http://mmcif.wwpdb.org/docs/pdb_to_pdbx_correspondences.html\n WARNING: Do not alter the keys of protein_dict without caution.\n The keys of protein_dict MUST match the column names of the Protein model in the protgraph database.\n\n Parameters\n ----------\n cif_data : dict\n Key/value pairs taken directly from a .cif file.\n Output of the function dict_from_mmcif.\n\n Returns\n -------\n protein_dict : dict\n A dictionary containing a parsed subset of the data in cif_data.\n The keys have the same name as fields in the Protein model.\n \"\"\"\n\n # Dictionary relating the keys of protein_dict (column names in Protein model) to the keys of cif_data.\n mmcif_data_names = {\n 'keywords': '_struct_keywords.text',\n 'header': '_struct_keywords.pdbx_keywords',\n 'space_group': '_symmetry.space_group_name_H-M',\n 'experimental_method': '_exptl.method',\n 'crystal_growth': '_exptl_crystal_grow.pdbx_details',\n 'resolution': '_refine.ls_d_res_high',\n 'r_value_obs': '_refine.ls_R_factor_obs',\n 'atoms_protein': '_refine_hist.pdbx_number_atoms_protein',\n 'atoms_solvent': '_refine_hist.number_atoms_solvent',\n 'atoms_ligand': '_refine_hist.pdbx_number_atoms_ligand',\n 'atoms_nucleic_acid': '_refine_hist.pdbx_number_atoms_nucleic_acid',\n 'atoms_total': '_refine_hist.number_atoms_total',\n 'title': '_struct.title',\n 'pdb_descriptor': '_struct.pdbx_descriptor',\n 'model_details': '_struct.pdbx_model_details',\n 'casp_flag': '_struct.pdbx_CASP_flag',\n 'model_type_details': '_struct.pdbx_model_type_details',\n 'ncbi_taxonomy': '_entity_src_nat.pdbx_ncbi_taxonomy_id',\n 'ncbi_taxonomy_gene': '_entity_src_gen.pdbx_gene_src_ncbi_taxonomy_id',\n 'ncbi_taxonomy_host_org': '_entity_src_gen.pdbx_host_org_ncbi_taxonomy_id',\n }\n\n # Set up initial protein_dict.\n protein_dict = {}\n for column_name, cif_name in mmcif_data_names.items():\n try:\n data = cif_data[cif_name]\n except IndexError:\n data = None\n except KeyError:\n data = None\n protein_dict[column_name] = data\n\n # These entries are modified from the mmcif dictionary.\n # There may be many revision dates in cif_data. We save the original deposition, release and last_modified dates.\n # If there are many dates, they will be in a list in cif_data, otherwise it's one date in a string\n # Is there a tidier way to do this?\n if isinstance(cif_data['_database_PDB_rev.date_original'], str):\n protein_dict['deposition_date'] = cif_data['_database_PDB_rev.date_original']\n else:\n protein_dict['deposition_date'] = cif_data['_database_PDB_rev.date_original'][0]\n if isinstance(cif_data['_database_PDB_rev.date'], str):\n protein_dict['release_date'] = cif_data['_database_PDB_rev.date']\n protein_dict['last_modified_date'] = cif_data['_database_PDB_rev.date']\n else:\n protein_dict['release_date'] = cif_data['_database_PDB_rev.date'][0]\n protein_dict['last_modified_date'] = cif_data['_database_PDB_rev.date'][-1]\n\n # crystal_growth should be a string or None\n crystal_growth = protein_dict['crystal_growth']\n if type(crystal_growth) == list and len(crystal_growth) >= 1:\n protein_dict['crystal_growth'] = crystal_growth[0]\n else:\n protein_dict['crystal_growth'] = None\n\n # taxonomy data types should be ints, not lists\n taxonomy_keys = ['ncbi_taxonomy', 'ncbi_taxonomy_gene', 'ncbi_taxonomy_host_org']\n for taxonomy_key in taxonomy_keys:\n if protein_dict[taxonomy_key]:\n if type(protein_dict[taxonomy_key]) == list:\n try:\n protein_dict[taxonomy_key] = int(protein_dict[taxonomy_key][0])\n except ValueError or IndexError:\n protein_dict[taxonomy_key] = None\n\n # Convert data types from strings to their correct data type.\n ints = ['atoms_ligand', 'atoms_nucleic_acid', 'atoms_protein', 'atoms_solvent', 'atoms_total']\n floats = ['r_value_obs', 'resolution']\n dates = ['deposition_date', 'release_date', 'last_modified_date']\n\n for k, v in protein_dict.items():\n if v:\n if v == '?' or v == 'None' or v == '.':\n protein_dict[k] = None\n elif k in ints:\n protein_dict[k] = int(v)\n elif k in floats:\n protein_dict[k] = float(v)\n elif k in dates:\n protein_dict[k] = datetime.datetime.strptime(v, '%Y-%m-%d')\n # Parse awkward strings from cif_data.\n elif type(v) == str:\n v = v.replace('loop_', '')\n v = v.replace(' # ', '')\n if v[0] == v[-1] == '\\'':\n protein_dict[k] = v[1:-1]\n\n return protein_dict","repo_name":"s2e-lab/Code-Smell-Code-Generation","sub_path":"Validation/PylintSamples/W0711_59874.py","file_name":"W0711_59874.py","file_ext":"py","file_size_in_byte":5763,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"46"} +{"seq_id":"24001378277","text":"from functions import *\n\n# create chatbot \nhome_bot = create_bot('Jordan')\n\n# train all data\ntrain_all_data(home_bot)\n\n# check identity\nidentity = input(\"State your identity please: \")\n\n# rules for responding to different identities\n# write your code here\n\n# custom data\nhouse_owner = [\n \"Who is owner of this house?\",\n \"Saki Fukushima is the owner of this house.\"\n]\ncustom_train(home_bot, house_owner)\n\nprint(\"------ Training custom data ------\")\n# write and train your custom data here IF the identity is Saki\n# write your code here\n\n# start chatbot\nstart_chatbot(home_bot)","repo_name":"sakifukushima/chatbot","sub_path":"homebot.py","file_name":"homebot.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"872543080","text":"from tkinter.messagebox import showerror\n\n\ndef checkAxiomFormat(axiomStr):\n \"\"\"\n Checks if the axiom string has the correct format\n :param axiomStr: str with axiom\n :return: true if correct\n \"\"\"\n if len(axiomStr) == 0:\n showerror('Missing Entry', 'The \"Axiom\" must not be empty.')\n return False\n elif not axiomStr in [\"F\", \"G\", \"R\", \"L\"]:\n showerror('Wrong Entry', 'The axiom must be an element from (\"F\", \"G\", \"R\", \"L\").')\n return False\n else:\n return True\n\n\ndef checkAngleFormat(angleStr):\n \"\"\"\n Checks if the angle string has the correct format\n :param angleStr: str with angle\n :return: true if correct\n \"\"\"\n try:\n if not angleStr.count('.') == 1:\n showerror('Wrong Format', 'In \"Angle\" must be a number with \".\" (dot). Do not use \",\" (comma).')\n return False\n elif float(angleStr) < 0.0:\n showerror('Wrong Format', '\"Angle\" must bigger then 0.')\n return False\n else:\n return True\n except BaseException:\n showerror('Wrong Format', 'In \"Angle\" must be a number with \".\" (dot). Do not use \",\" (comma).')\n return False\n\n\ndef checkIterationFormat(iterationStr):\n \"\"\"\n Checks if the iteration string has the correct format\n :param iterationStr: str with iteration number\n :return: true if correct\n \"\"\"\n if not iterationStr.isnumeric():\n showerror('Wrong Format', '\"Iteration\" must be a positive number.')\n return False\n else:\n return True\n\n\ndef checkRuleFormat(ruleStr):\n \"\"\"\n Checks if the rule string has the correct format\n :param ruleStr: str with rule\n :return: true if correct\n \"\"\"\n if ruleStr.count('=') > 1:\n showerror('Wrong Format', '\"Rule\" must contain only one \"=\", e.g. \"F=FF+[+F-F-F]-[-F+F+F]\".')\n return False\n elif len(ruleStr) == 0:\n showerror('Missing Entry', 'The \"Rule\" must not be empty.')\n return False\n elif not '=' in ruleStr:\n showerror('Wrong Format', '\"Rule\" must contain \"=\", e.g. \"F=FF+[+F-F-F]-[-F+F+F]\".')\n return False\n else:\n return True","repo_name":"leoseg/Lindmayer","sub_path":"format_checks.py","file_name":"format_checks.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"21535377180","text":"import hyper_tools\nimport deep_tools\nimport math\nimport numpy as np\n\nimport parti_tools\nfrom matplotlib import pyplot as plt\n\n\ndef line_minimisation(given_parti,given_shear):\n number_of_steps = int(len(given_parti)/2)+1\n\n got_parti=[]\n got_parti = hyper_tools.hyper_parti(given_parti,given_shear)\n got_der = hyper_tools.read_der_parti(got_parti)\n step = deep_tools.scalar_prod(1/number_of_steps,got_der)\n\n mink =0\n minl = hyper_tools.length_hyper_parti(got_parti)\n\n new_shear = 0\n last_shear = 0\n new_parti = []\n steps = 0\n last_shear = given_shear\n\n for k in range(number_of_steps):\n steps = k\n new_shear = deep_tools.subtract_vector(last_shear,step)\n new_parti = hyper_tools.hyper_parti(given_parti,new_shear)\n new_length = hyper_tools.length_hyper_parti(new_parti)\n if new_length >= minl:\n return [last_shear,steps]\n else:\n last_shear = new_shear\n\n return [new_shear,steps]\n\n\ndef gradient_descent(given_parti,given_shear):\n loops = 0\n steps = 0\n got_parti = []\n got_parti = parti_tools.expand_parti(given_parti)\n got_parti = parti_tools.add_affixes(given_parti)\n got_parti = hyper_tools.hyper_parti(got_parti,given_shear)\n old_length = hyper_tools.length_hyper_parti(got_parti)\n new_parti = []\n new_shear = [0,0,0]\n old_shear = given_shear\n while True:\n loops +=1\n line_min = line_minimisation(given_parti,new_shear)\n new_shear = line_min[0]\n new_steps = line_min[1]\n steps += new_steps\n new_parti = hyper_tools.hyper_parti(given_parti,new_shear)\n new_length = hyper_tools.length_hyper_parti(new_parti)\n if new_length < old_length:\n old_length = new_length\n old_shear = new_shear\n else:\n return [old_shear,old_length,loops,steps]\n\n\n\ndef gradient_descent_plot(given_parti,given_shear,word):\n plt.ion()\n got_parti = []\n got_parti = parti_tools.expand_parti(given_parti)\n got_parti = parti_tools.add_affixes(given_parti)\n got_parti = hyper_tools.hyper_parti(got_parti,given_shear)\n old_length = hyper_tools.length_hyper_parti(got_parti)\n new_parti = []\n new_shear = [0,0,0]\n old_shear = given_shear\n n=[]\n x=[]\n y=[]\n count = 0\n while True:\n count += 1\n n.append(count)\n x.append(new_shear[0])\n y.append(new_shear[1])\n\n line_min = line_minimisation(given_parti,new_shear)\n new_shear = line_min[0]\n new_steps = line_min[1]\n new_parti = hyper_tools.hyper_parti(given_parti,new_shear)\n new_length = hyper_tools.length_hyper_parti(new_parti)\n if new_length < old_length:\n old_length = new_length\n old_shear = new_shear\n if new_length < 0.0001:\n break\n else:\n pass\n else:\n break\n\n fig, ax = plt.subplots()\n ax.scatter(x[:-1], y[:-1], color='red')\n ax.scatter(x[-1], y[-1], color='blue', marker=\"x\")\n\n for i, txt in enumerate(n[:-1]):\n ax.annotate(txt, (x[i], y[i]))\n\n ax.set_title('The descent started at \"1\" and then followed the dots.\\n '\n 'The blue cross indicates the estimated minimum')\n plt.show()\n\n print('')\n wanna_heat = input('It is possible that this was underwhelming... it might get (although it might not)\\n'\n 'to see it on a heat map.This was maybe underwhelming... Press \"Q\" to quit, \"H\" to get\\n'\n 'the heat map, an anything else to go back to the main menu. ')\n deep_tools.wanna_quit(wanna_heat)\n deep_tools.limpia()\n if wanna_heat in ['h', 'H']:\n max_x = max(x)+2\n min_x = min(x)-2\n max_y = max(y)+2\n min_y = min(y)-2\n\n steps = 100\n step_x = (max_x-min_x)/steps\n step_y = (max_y-min_y)/steps\n\n center = [0, 0]\n data = np.empty((steps, steps))\n for k in range(steps):\n for n in range(steps):\n shear = [(min_x+k*step_x), (min_y+n*step_y),(-min_x-k*step_x-min_y-n*step_y)]\n data[steps-1-n, k] = math.log(hyper_tools.length_trace_free_group_word(word, shear))\n\n plt.imshow(data, cmap='autumn', interpolation='nearest')\n plt.colorbar()\n\n\n for k in range(len(x)-1):\n plt.plot(int((x[k]-min_x)/step_x), steps-1-int((y[k]-min_y)/step_y), color='blue', marker=\".\", markersize=10)\n kstr = str(k+1)\n plt.text(int((x[k]-min_x)/step_x), steps-1-int((y[k]-min_y)/step_y), kstr)\n\n plt.plot(int((x[-1]-min_x)/step_x), steps-1-int((y[-1]-min_y)/step_y), color='blue', marker=\"x\", markersize=10)\n\n\n plt.title('The descent started at \"1\" and then followed the dots.\\n '\n 'The blue cross indicates the estimated minimum')\n plt.show()\n else:\n pass\n\n deep_tools.limpia()\n\n\ndef check_minimisation_radius(parti,shear,length,radius):\n k = 1\n minimal = False\n while not minimal:\n [min_length, min_shear] = minimize_around(parti, shear, k*radius, 200*k)\n if min_length < length:\n k = 2*k\n else:\n minimal = True\n\n return k\n\n\ndef minimize_around(parti,shear,tol,steps=None):\n min_length = 1000000\n back_shear = [0,0,0]\n if steps is None:\n steps = 1000\n for n in range(steps):\n new_shear = deep_tools.add_vector(shear,[math.cos(n*math.pi/steps)*tol,math.sin(n*math.pi/steps)*tol,\n -math.cos(n*math.pi/steps)-math.sin(n*math.pi/steps)*tol])\n parti = hyper_tools.hyper_parti(parti,new_shear)\n new_length = hyper_tools.length_hyper_parti(parti)\n if new_length < min_length:\n min_length = new_length\n back_shear = new_shear\n else:\n pass\n return [min_length,back_shear]\n\n\n\n","repo_name":"juan-souto/torusgeod","sub_path":"minimisation.py","file_name":"minimisation.py","file_ext":"py","file_size_in_byte":5903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"14962528902","text":"import itertools\n\ndef solution(orders, course):\n answer = []\n\n all_course = [[] for _ in range(course[-1]+1)]\n course_list = [[] for _ in range(course[-1]+1)]\n num_of_course = [[] for _ in range(course[-1]+1)]\n\n for num_food in course:\n for order in orders:\n all_course[num_food] = all_course[num_food]+list(itertools.combinations(list(sorted(order)), num_food))\n\n #각 음식마다 갯수를 카운트 하여 course는 course_list에 append 갯수는 num_of_curese에 append\n for num_food in course:\n for ic, c in enumerate(all_course[num_food]):\n # 만약에 카운트 된적이 없다면\n if c not in course_list[num_food]:\n # 이전것은 카운트 되었으므로 제외하고 그 수를 num_of_course에 저장\n # print(all_course[num_food][ic:].count(c))\n num_of_course[num_food].append(all_course[num_food][ic:].count(c))\n # course_list에 c 저장\n course_list[num_food].append(c)\n\n maximum_nums = [[] for _ in range(course[-1]+1)]\n for i, v in enumerate(num_of_course):\n if len(v) != 0:\n maximum_nums[i].append(max(v))\n maximum_nums\n\n for num_food, v in enumerate(maximum_nums):\n if len(v) != 0 and v[0]>1:\n for i, course in enumerate(course_list[num_food]):\n if num_of_course[num_food][i] == v[0]:\n answer.append(''.join(course_list[num_food][i]))\n answer.sort()\n return answer","repo_name":"ShinWon-Chul/AlgorithmWithPython","sub_path":"programmers/2021_KAKAO_BLIND_RECRUITMENT/메뉴 리뉴얼.py","file_name":"메뉴 리뉴얼.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"28754874504","text":"def ODP(CASRN, AvailableMethods=False, Method=None):\n r'''This function handles the retrieval of a chemical's Ozone Depletion\n Potential, relative to CFC-11 (trichlorofluoromethane). Lookup is based on\n CASRNs. Will automatically select a data source to use if no Method is\n provided; returns None if the data is not available.\n\n Returns the ODP of a chemical according to [2]_ when a method is not\n specified. If a range is provided in [2]_, the highest value is returned.\n\n Parameters\n ----------\n CASRN : string\n CASRN [-]\n\n Returns\n -------\n ODP : float or str\n Ozone Depletion potential, [(impact/mass chemical)/(impact/mass CFC-11)];\n if method selected has `string` in it, this will be returned as a\n string regardless of if a range is given or a number\n methods : list, only returned if AvailableMethods == True\n List of methods which can be used to obtain ODP with the\n given inputs\n\n Other Parameters\n ----------------\n Method : string, optional\n The method name to use. Accepted methods are 'ODP2 Max', 'ODP2 Min', \n 'ODP2 string', 'ODP2 logarithmic average', and methods for older values\n are 'ODP1 Max', 'ODP1 Min', 'ODP1 string', and 'ODP1 logarithmic average'.\n All valid values are also held in the list ODP_methods.\n Method : string, optional\n A string for the method name to use, as defined by constants in\n ODP_methods\n AvailableMethods : bool, optional\n If True, function will determine which methods can be used to obtain\n the ODP for the desired chemical, and will return methods\n instead of the ODP\n\n Notes\n -----\n Values are tabulated only for a small number of halogenated hydrocarbons,\n responsible for the largest impact. The original values of ODP as defined\n in the Montreal Protocol are also available, as methods with the `ODP1`\n prefix.\n\n All values are somewhat emperical, as actual reaction rates of chemicals\n with ozone depend on temperature which depends on latitude, longitude,\n time of day, weather, and the concentrations of other pollutants.\n\n All data is from [1]_. Several mixtures listed in [1]_ are not included\n here as they are not pure species.\n Methods for values in [2]_ are 'ODP2 Max', 'ODP2 Min', 'ODP2 string',\n 'ODP2 logarithmic average', and methods for older values are 'ODP1 Max',\n 'ODP1 Min', 'ODP1 string', and 'ODP1 logarithmic average'.\n\n Examples\n --------\n Dichlorotetrafluoroethane, according to [2]_.\n\n >>> ODP(CASRN='76-14-2')\n 0.58\n\n References\n ----------\n .. [1] US EPA, OAR. \"Ozone-Depleting Substances.\" Accessed April 26, 2016.\n https://www.epa.gov/ozone-layer-protection/ozone-depleting-substances.\n .. [2] WMO (World Meteorological Organization), 2011: Scientific Assessment\n of Ozone Depletion: 2010. Global Ozone Research and Monitoring\n Project-Report No. 52, Geneva, Switzerland, 516 p.\n https://www.wmo.int/pages/prog/arep/gaw/ozone_2010/documents/Ozone-Assessment-2010-complete.pdf\n '''\n def list_methods():\n methods = []\n if CASRN in ODP_data.index:\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2 Max']):\n methods.append(ODP2MAX)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1 Max']):\n methods.append(ODP1MAX)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2 Design']):\n methods.append(ODP2LOG)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1 Design']):\n methods.append(ODP1LOG)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2 Min']):\n methods.append(ODP2MIN)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1 Min']):\n methods.append(ODP1MIN)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP2']):\n methods.append(ODP2STR)\n if not pd.isnull(ODP_data.at[CASRN, 'ODP1']):\n methods.append(ODP1STR)\n methods.append(NONE)\n return methods\n if AvailableMethods:\n return list_methods()\n if not Method:\n Method = list_methods()[0]\n\n if Method == ODP2MAX:\n return float(ODP_data.at[CASRN, 'ODP2 Max'])\n elif Method == ODP1MAX:\n return float(ODP_data.at[CASRN, 'ODP1 Max'])\n elif Method == ODP2MIN:\n return float(ODP_data.at[CASRN, 'ODP2 Min'])\n elif Method == ODP1MIN:\n return float(ODP_data.at[CASRN, 'ODP1 Min'])\n elif Method == ODP2LOG:\n return float(ODP_data.at[CASRN, 'ODP2 Design'])\n elif Method == ODP1LOG:\n return float(ODP_data.at[CASRN, 'ODP1 Design'])\n elif Method == ODP2STR:\n return str(ODP_data.at[CASRN, 'ODP2'])\n elif Method == ODP1STR:\n return str(ODP_data.at[CASRN, 'ODP1'])\n elif Method == NONE:\n return None\n else:\n raise Exception('Failure in in function')","repo_name":"MichaelFu1998-create/security_scanning","sub_path":"codesearchnet/codesearchnet_6737.py","file_name":"codesearchnet_6737.py","file_ext":"py","file_size_in_byte":4924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"18405871534","text":"# Jake Daniels\n# MATH 4610\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef explicitEuler(f, x0, t0, T, n):\n h = (T - t0) / n\n f0 = f(t0, x0)\n tval = []\n xval = []\n tval.append(t0)\n xval.append(x0)\n for i in range(1, n):\n t1 = t0 + h\n x1 = x0 + h * f0\n x0 = x1\n t0 = t1\n tval.append(t0)\n xval.append(x0)\n f0 = f(t0, x0)\n return tval, xval\n","repo_name":"jake-daniels16/math4610","sub_path":"Derivative Approximation/Methods/explicitEuler.py","file_name":"explicitEuler.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"7474510549","text":"def solution(skill, skill_trees):\n answer = 0\n s=dict()\n for skill_tree in skill_trees:\n for i in skill:\n s[i]=100\n for idx,tree in enumerate(skill_tree):\n if tree in s:\n s[tree]=idx\n check=[s[i] for i in skill]\n if check==sorted(check):\n answer+=1\n return answer\n","repo_name":"Ta-Ye/CodeTest","sub_path":"Programmers/Summer Winter Coding/스킬트리.py","file_name":"스킬트리.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"12294608483","text":"from __future__ import annotations\n\nimport dataclasses\nimport re\n\nfrom .. import config, h, t\nfrom .. import messages as m\n\n\ndef addAttributeInfoSpans(doc: t.SpecT) -> None:\n #
automatically gets a appended to it\n # (and same for and ).\n for dt in h.findAll(\"dt\", doc):\n dfn = h.find(\"dfn\", dt)\n if dfn is None:\n continue\n if h.find(\"span[data-attribute-info], span[data-dict-member-info]\", dt) is not None:\n # Already has a span, nothing to add\n continue\n dfnType = dfn.get(\"data-dfn-type\")\n if dfnType == \"attribute\":\n attrName = \"data-attribute-info\"\n elif dfnType == \"dict-member\":\n attrName = \"data-dict-member-info\"\n else:\n continue\n spanFor = h.firstLinkTextFromElement(dfn)\n if spanFor is None:\n continue\n # Internal slots (denoted by [[foo]] naming scheme) don't have attribute info\n if spanFor.startswith(\"[[\"):\n continue\n if dfn.get(\"data-dfn-for\"):\n spanFor = dfn.get(\"data-dfn-for\", \"\") + \"/\" + spanFor\n # If there's whitespace after the dfn, clear it out\n if h.emptyText(dfn.tail, wsAllowed=True):\n dfn.tail = None\n h.insertAfter(dfn, \", \", h.E.span({attrName: \"\", \"for\": spanFor}))\n\n\ndef fillAttributeInfoSpans(doc: t.SpecT) -> None:\n for el in h.findAll(\"span[data-attribute-info], span[data-dict-member-info]\", doc):\n if not h.isEmpty(el):\n # Manually filled, bail\n return\n\n info = getTargetInfo(doc, el)\n if info is None:\n continue\n\n h.appendChild(el, htmlFromInfo(info))\n\n\n@dataclasses.dataclass\nclass TargetInfo:\n type: str\n nullable: bool = False\n readonly: bool = False\n default: str | None = None\n\n\ndef getTargetInfo(doc: t.SpecT, el: t.ElementT) -> TargetInfo | None:\n if el.get(\"data-attribute-info\") is not None:\n refType = \"attribute\"\n else:\n refType = \"dict-member\"\n\n referencedAttribute = el.get(\"for\")\n if not referencedAttribute:\n m.die(\"Missing for='' reference in attribute info span.\", el=el)\n return None\n if \"/\" in referencedAttribute:\n interface, referencedAttribute = referencedAttribute.split(\"/\")\n targets = h.findAll(\n 'a[data-link-type={2}][data-lt=\"{0}\"][data-link-for=\"{1}\"]'.format(referencedAttribute, interface, refType),\n doc,\n )\n else:\n targets = h.findAll(\n f'a[data-link-type={refType}][data-lt=\"{referencedAttribute}\"]',\n doc,\n )\n\n if len(targets) == 0:\n m.die(f\"Couldn't find target {referencedAttribute} '{refType}':\\n{h.outerHTML(el)}\", el=el)\n return None\n elif len(targets) > 1:\n m.die(f\"Multiple potential target {referencedAttribute}s '{refType}':\\n{h.outerHTML(el)}\", el=el)\n return None\n\n target = targets[0]\n\n type = target.get(\"data-type\", \"\").strip()\n if type.endswith(\"?\"):\n nullable = True\n type = type[:-1]\n else:\n nullable = False\n default = target.get(\"data-default\")\n readonly = target.get(\"data-readonly\") is not None\n return TargetInfo(type, nullable, readonly, default)\n\n\ndef htmlFromInfo(info: TargetInfo) -> t.NodesT:\n deco = []\n if re.match(r\"\\w+<\\w+(\\s*,\\s*\\w+)*>\", info.type):\n # Simple higher-kinded types\n match = re.match(r\"(\\w+)<(\\w+(?:\\s*,\\s*\\w+)*)>\", info.type)\n assert match is not None\n types = [h.E.a({\"data-link-type\": \"idl-name\"}, x.strip()) for x in match.group(2).split(\",\")]\n deco.extend([\" of type \", match.group(1), \"<\", config.intersperse(types, \", \"), \">\"])\n elif \"<\" in info.type or \"(\" in info.type:\n # Unions or more-complex higher-kinded types\n # Currently just bail, but I need to address this at some point.\n deco.extend(\n [\n \" of type \",\n h.E.code({\"class\": \"idl-code\"}, info.type),\n ],\n )\n else:\n # Everything else\n deco.extend(\n [\n \" of type \",\n h.E.a({\"data-link-type\": \"idl-name\"}, info.type),\n ],\n )\n\n if info.readonly:\n deco.append(\", readonly\")\n if info.nullable:\n deco.append(\", nullable\")\n if info.default is not None:\n deco.append(\", defaulting to \")\n deco.append(h.E.code(info.default))\n\n return deco\n","repo_name":"speced/bikeshed","sub_path":"bikeshed/dfns/attributeInfo.py","file_name":"attributeInfo.py","file_ext":"py","file_size_in_byte":4539,"program_lang":"python","lang":"en","doc_type":"code","stars":973,"dataset":"github-code","pt":"46"} +{"seq_id":"14541786149","text":"from peano4.solversteps.ActionSet import ActionSet\n\n\nimport jinja2\n\n\nclass PlotGridInPeanoBlockFormat(ActionSet):\n NoMetaFile = \"no-meta-file\"\n CountTimeSteps = \"count-time-steps\"\n \n def __init__(self, filename, cell_unknown=None, time_stamp_evaluation=NoMetaFile, guard_predicate=\"true\", additional_includes=\"\"):\n \"\"\"\n Plot only the grid structure\n \n :Attibutes:\n \n filename: String\n Name of the output file.\n \n cell_unknown: None or cell data \n If you use cell unknowns, pass any unknown in. As we do not dump\n any semantic information about unknowns, it does not matter which \n one you choose. If you don't have cell unknowns at all, pass in \n None.\n \n time_stamp_evaluation: String\n C++ expression returning a double. You can also hand in NoMetaFile\n or CountTimeSteps. \n \n \"\"\"\n self.d = {}\n self.d[ \"FILENAME\" ] = filename\n self.d[ \"CELL_WRAPPER\" ] = \"Cell\"\n if cell_unknown!=None:\n self.d[ \"CELL_WRAPPER\" ] += cell_unknown.name\n self.d[ \"GUARD_PREDICATE\" ] = guard_predicate\n self.additional_includes = additional_includes\n self.d[ \"TIMESTAMP\" ] = time_stamp_evaluation\n \n\n __Template_Constructor = \"\"\"\n _writer = nullptr;\n _dataWriter = nullptr;\n _treeNumber = treeNumber;\n\n // An MPI lock (critical section) would be important!\n \n logDebug( \"PlotGrid2PlotGridInPeanoBlockFormat1()\", \"created tree instance for \" << treeNumber );\n\"\"\"\n\n\n def get_constructor_body(self):\n return self.__Template_Constructor.format(**self.d)\n\n\n __Template_EndTraversal = jinja2.Template(\"\"\"\n assertion1(_dataWriter!=nullptr,_treeNumber);\n\n _dataWriter->close();\n _writer->writeToFile();\n \n delete _dataWriter;\n delete _writer;\n\n _dataWriter = nullptr;\n _writer = nullptr;\n\"\"\")\n\n \n def get_destructor_body(self):\n return \"\"\n\n\n def get_body_of_getGridControlEvents(self):\n return \" return std::vector< peano4::grid::GridControlEvent >();\\n\" \n\n\n def get_action_set_name(self):\n return __name__.replace(\".py\", \"\").replace(\".\", \"_\")\n\n\n def user_should_modify_template(self):\n return False\n\n\n __Template_TouchCellFirstTime = jinja2.Template(\"\"\" \n if ( {{GUARD_PREDICATE}} ) {\n int vertexIndices[TwoPowerD];\n\n int indices = _writer->plotPatch(\n marker.x() - marker.h() * 0.5,\n marker.h()\n );\n\n assertion( _dataWriter!=nullptr );\n \n double markerData[] = {\n marker.hasBeenRefined() ? 1.0 : 0.0,\n marker.willBeRefined() ? 1.0 : 0.0,\n marker.isLocal() ? 1.0 : 0.0,\n marker.isEnclaveCell() ? 1.0 : 0.0\n };\n _dataWriter->plotCell(indices,markerData);\n }\n\"\"\")\n\n\n __Template_BeginTraversal = jinja2.Template(\"\"\"\n tarch::mpi::Lock lock( _semaphore );\n \n static int counter = -1;\n counter++;\n\n std::ostringstream snapshotFileName;\n snapshotFileName << \"{{FILENAME}}-\" << counter;\n\n if (tarch::mpi::Rank::getInstance().getNumberOfRanks()>0 ) {\n snapshotFileName << \"-rank-\" << tarch::mpi::Rank::getInstance().getRank();\n }\n\n {% if TIMESTAMP==\\\"\"\"\" + NoMetaFile + \"\"\"\\\" %}\n _writer = new tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter(\n Dimensions, snapshotFileName.str(), \"{{FILENAME}}\",\n tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter::IndexFileMode::NoIndexFile,\n 0.0\n );\n {% elif TIMESTAMP==\\\"\"\"\" + CountTimeSteps + \"\"\"\\\" %}\n static int timeStep = -1;\n timeStep++;\n _writer = new tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter(\n Dimensions, snapshotFileName.str(), \"{{FILENAME}}\",\n tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter::IndexFileMode::AppendNewData,\n timeStep\n );\n {% else %}\n _writer = new tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter(\n Dimensions, snapshotFileName.str(), \"{{FILENAME}}\",\n tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter::IndexFileMode::AppendNewData,\n {{TIMESTAMP}}\n ); \n {% endif %}\n \n _dataWriter = _writer->createCellDataWriter( \"cell-marker\", 1, 4, \"is-refined,has-been-refined,local,enclave\" );\n\"\"\")\n\n\n def get_body_of_operation(self,operation_name):\n result = \"\\n\"\n if operation_name==ActionSet.OPERATION_TOUCH_CELL_FIRST_TIME:\n result = self.__Template_TouchCellFirstTime.render(**self.d) \n if operation_name==ActionSet.OPERATION_BEGIN_TRAVERSAL:\n result = self.__Template_BeginTraversal.render(**self.d) \n if operation_name==ActionSet.OPERATION_END_TRAVERSAL:\n result = self.__Template_EndTraversal.render(**self.d) \n return result\n\n\n def get_attributes(self):\n return \"\"\"\n static tarch::mpi::BooleanSemaphore _semaphore;\n \n int _treeNumber;\n\n tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter* _writer;\n tarch::plotter::griddata::blockstructured::PeanoTextPatchFileWriter::CellDataWriter* _dataWriter;\n\"\"\"\n\n\n def get_includes(self):\n return \"\"\"\n#include \"tarch/plotter/griddata/blockstructured/PeanoTextPatchFileWriter.h\"\n#include \"tarch/multicore/Lock.h\"\n#include \"tarch/multicore/BooleanSemaphore.h\"\n#include \"tarch/mpi/Lock.h\"\n#include \"tarch/mpi/BooleanSemaphore.h\"\n#include \"peano4/parallel/SpacetreeSet.h\"\n\"\"\" + self.additional_includes\n\n\n def get_static_initialisations(self,full_qualified_classname):\n return \"\"\"\ntarch::mpi::BooleanSemaphore \"\"\" + full_qualified_classname + \"::_semaphore(\\\"\"\"\" + full_qualified_classname + \"\"\"\\\");\n\"\"\"\n \n\n\n","repo_name":"kittytastic/Peano-Fork","sub_path":"python/peano4/toolbox/PlotGridInPeanoBlockFormat.py","file_name":"PlotGridInPeanoBlockFormat.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"35917174350","text":" # -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 9 14:56:07 2018\n\n@author: Russel\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\n\nos.chdir(\"d:/data_files\")\nadvt=pd.read_csv(\"advertising.csv\")\n\n\n'''plt.scatter(advt['TV'],advt['sales'])\nplt.xlabel(\"TV\")\n\nplt.scatter(advt['radio'],advt['sales'])\nplt.xlabel(\"radio\")'''\n\nadvt=advt.drop(\"srno\",axis=1)\n\ntrain,test=model_selection.train_test_split(advt,test_size=0.25,random_state=42)\nprint(train.shape)\nprint(test.shape)\n\ny_train=train['sales']\nX_train=train[['TV','radio','newspaper']]\n\ny_test=train['sales']\nX_test=train[['TV','radio','newspaper']]\n\nlinmod=linear_model.LinearRegression()\nlinmod.fit(X_train,y_train)\nprint(\"intercept : \",linmod.intercept_)\n\nprint(\"TV :\",linmod.coef_[0])\nprint(\"radio :\",linmod.coef_[1])\n\n#sales=2.921 + 0.0457 * TV + 0.188 * radio\n\nadj_r_sq=linmod.score(X_train,y_train)\nprint(\"adj_r_sq :\",adj_r_sq)\nadvt['sales'].head()\n\nadvt[:3]\npredicted_sales=linmod.predict(X_test)\n#print(predicted_sales)\n#(predicted_sales - y_advt)**2\nprint(\"rms :\",np.average((predicted_sales - y_test)**2))\n\nprint(\"rmsc :\",np.sqrt(np.average((predicted_sales - y_test)**2)))\n\n\n\n\n\n\n","repo_name":"jeetsaha5338/College_Study","sub_path":"TRAINNING/ML/Globesyn/work/done/advt_new.py","file_name":"advt_new.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"8451184900","text":"\nimport pyshark\n\ntrace_input = pyshark.FileCapture(\"project2_part1.pcap\", display_filter='udp and not dns and not browser and not mdns and not cups and not nbns and not auto_rp and not smb_netlogon')\n\nip_dict = {}\n\nfor packet in trace_input:\n ip_src = packet.ip.src\n ip_dst = packet.ip.dst\n ip_endpoints = (ip_src, ip_dst)\n \n if ip_endpoints in ip_dict:\n ttl_dict = ip_dict[ip_endpoints]\n ttl = int(packet.ip.ttl)\n if ttl not in ttl_dict:\n ttl_dict.add(ttl)\n else:\n ip_dict[ip_endpoints] = set()\n ip_dict[ip_endpoints].add(int(packet.ip.ttl))\n\nfor endpoint in ip_dict:\n if len(ip_dict[endpoint]) > 60:\n print (endpoint)","repo_name":"svkatta/CS526","sub_path":"NetworkSecurity/p1.8.py","file_name":"p1.8.py","file_ext":"py","file_size_in_byte":741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"27737067358","text":"\"\"\"\nDefines a trait editor for a figure, based on an example by Gael Varoquaux.\n\"\"\"\n\nimport matplotlib\nmatplotlib.use('WXAgg')\n\n# wx\nimport wx\n\n# matplotlib\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.backends.backend_wx import NavigationToolbar2Wx\n\n# Traits\nfrom traitsui.wx.editor import Editor\nfrom traitsui.basic_editor_factory import BasicEditorFactory\n\nclass _MPLFigureEditor(Editor):\n \n scrollable = True\n \n def init(self, parent):\n self.control = self._create_canvas(parent)\n self.set_tooltip()\n \n \n def update_editor(self):\n pass\n \n \n def _create_canvas(self, parent):\n \"\"\" Create the MPL canvas. \"\"\"\n # The panel lets us add additional controls.\n panel = wx.Panel(parent, -1, style=wx.CLIP_CHILDREN)\n sizer = wx.BoxSizer(wx.VERTICAL)\n panel.SetSizer(sizer)\n # matplotlib commands to create a canvas\n mpl_control = FigureCanvas(panel, -1, self.value)\n sizer.Add(mpl_control, 1, wx.LEFT | wx.TOP | wx.GROW)\n toolbar = NavigationToolbar2Wx(mpl_control)\n sizer.Add(toolbar, 0, wx.EXPAND)\n self.value.canvas.SetMinSize((10,10))\n return panel\n \n\n\nclass MPLFigureEditor(BasicEditorFactory):\n klass = _MPLFigureEditor\n","repo_name":"yosefm/tracer","sub_path":"examples/embedded_figure.py","file_name":"embedded_figure.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"46"} +{"seq_id":"8600132898","text":"__copyright__ = 'Copyright(c) Gordon Elliott 2017'\n\n\"\"\" Reconcile transactions to statement items\n\"\"\"\n\nimport logging\n\nfrom a_tuin.db.session_scope import session_scope\nfrom glod.db.transaction_check import TransactionCheckQuery\n\n\nLOG = logging.getLogger(__file__)\n\n\ndef reconcile():\n try:\n with session_scope() as session:\n TransactionCheckQuery(session).reconcile()\n\n except Exception as ex:\n LOG.exception(ex)\n\n\nif __name__ == '__main__':\n reconcile()\n","repo_name":"gordon-elliott/glod","sub_path":"src/glod/scripts/reconcile.py","file_name":"reconcile.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"4728397149","text":"import pandas as pd\n\nnos = pd.read_csv('advent_data_1.csv')\n\n\n# This is very messy, could probably do this with transposed arrays, but meh.\n# Section 1\nfor number in nos.values:\n for number2 in nos.values:\n add = number+number2\n if add == 2020:\n print(number*number2)\n\n# Section 2\nfor number in nos.values:\n for number2 in nos.values:\n for number3 in nos.values:\n add = number+number2+number3\n if add == 2020:\n print(number*number2*number3)\n","repo_name":"stuartbman/github_advent","sub_path":"advent_1.py","file_name":"advent_1.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"38872731084","text":"import maya.cmds as cmds\n\n# show's lenses for Lenskit \nlensKit = [14,22,32,40,55,80,135,180,240] \n\n\n#Find all non default cameras in the scene\ndef findAllCameras():\n allCams = cmds.ls(type='camera')\n seqCams = []\n for cam in allCams:\n if cam.find('persp') != -1:\n pass\n elif cam.find('top') != -1:\n pass \n elif cam.find('front') != -1:\n pass\n elif cam.find('side') != -1:\n pass \n else:\n seqCams.append(cam) \n return(seqCams)\n\n#Build a lenskit and set focalLength to closet currently set focalLenght\n#Also sets all needed camera settings\ndef setupCamera(seqShots, image_path):\n #build focalLegnth lenskit\n lensKitString = ''\n lensKitString = str('')\n for lens in lensKit:\n lensKitString = lensKitString + (str(lens) + ':')\n \n lensKitString = lensKitString.rstrip(lensKitString[-1])\n print('Current lens kit : ' + lensKitString)\n for seqshot in seqShots:\n camTransform = cmds.listConnections( (\"{}.currentCamera\".format(seqshot)), d=False, s=True )\n #camTransform = cmds.listRelatives(cam, parent=True)\n cam = cmds.listRelatives(camTransform, shapes = True)\n animCurve = cmds.createNode('animCurveTL',n = (cam[0] + 'lensCurve'), ss=True)\n cmds.setKeyframe(animCurve, t=0, v=14, itt='linear', ott='linear')\n \n focal = getClosestFocal(cam[0])\n \n count = 0\n lensIndex = 0\n \n for lens in lensKit:\n cmds.setKeyframe(animCurve, t=count, v=lens, itt='linear', ott='linear')\n if lens == focal:\n lensIndex = count\n count = count +1\n try:\n cmds.addAttr(camTransform[0],ln = 'lensKit', at = 'enum', en = lensKitString)\n except:\n print(\"could not create Lenskit attribute for {} .. It may already exist\".format(camTransform[0]))\n cmds.setAttr ((camTransform[0] + '.lensKit'),e = True, keyable = True)\n cmds.setAttr ((camTransform[0] + '.lensKit'), lensIndex)\n \n try:\n cmds.connectAttr((camTransform[0] + '.lensKit'),(animCurve + '.input'))\n except:\n print(\"{} Lenskit already connected\".format(camTransform[0]))\n try:\n cmds.connectAttr((animCurve + '.output'),(cam[0] + '.focalLength'))\n except:\n print(\"{} Focal length already connected\".format(cam[0]))\n \n #set camera filmback and gate masks\n cmds.setAttr ((camTransform[0] + '.verticalFilmAperture'), 0.79725)\n cmds.setAttr ((camTransform[0] + '.displayFilmGate'), 1)\n cmds.setAttr ((camTransform[0] + '.displayGateMask'), 1)\n cmds.setAttr ((camTransform[0] + '.displaySafeAction'), 1)\n \n #set far clip plane\n cmds.setAttr ((cam[0] + '.nearClipPlane'), 1)\n cmds.setAttr ((cam[0] + '.farClipPlane'), 1000000)\n #set the camera locator scale to make it appear larger in view\n cmds.setAttr ((cam[0] + '.locatorScale'), 10)\n \n #Create imageplane on currentCamera and place in corner\n ip = cmds.imagePlane(camera=cam[0],w = 16, h = 9, lt = True, sia = False)\n ipsx = cmds.getAttr(ip[1] + '.sizeX')\n ipsy = cmds.getAttr(ip[1] + '.sizeY')\n cmds.setAttr((ip[1] + '.depth'), 10)\n cmds.setAttr((ip[1] + '.offsetX'), -0.46)\n cmds.setAttr((ip[1] + '.offsetY'), 0.25)\n cmds.setAttr((ip[1] + '.sizeX'), (ipsx * 0.3))\n cmds.setAttr((ip[1] + '.sizeY'), (ipsy * 0.3))\n cmds.setAttr((ip[1] + '.alphaGain'), 0.5)\n\n \n assign_image_to_imageplane(ip[1],seqshot)\n cmds.setAttr((ip[1] + \".useFrameExtension\"), 1)\n\n #parent camera to CAMERAS group\n try:\n cmds.parent( camTransform[0], \"|CAMERAS\" )\n except:\n print(\"could not parent {} to CAMERAS group\".format(camTransform[0]))\n \ndef assign_image_to_imageplane(imageplane,seqshot):\n start_frame = cmds.getAttr(\"{}.startFrame\".format(seqshot)) # Query shot's start frame.\n end_frame = end_frame = cmds.getAttr(\"{}.endFrame\".format(seqshot)) # Query shot's end frame.\n cmds.setAttr((imageplane + \".imageName\"),image_path ,type = \"string\" )\n cmds.currentTime(start_frame)\n cmds.setAttr(imageplane + \".frameExtension\", 0)\n cmds.setKeyframe(imageplane + \".fe\", inTangentType = \"linear\", outTangentType = \"linear\")\n cmds.currentTime(end_frame)\n cmds.setAttr(imageplane + \".frameExtension\", (end_frame - start_frame))\n cmds.setKeyframe(imageplane + \".fe\", inTangentType = \"linear\", outTangentType = \"linear\")\n cmds.selectKey(imageplane, at = \"fe\", r = True, k = True, time = (start_frame , end_frame))\n cmds.keyTangent(itt = \"linear\", ott = \"linear\") \n \n \n#function to get the closets focalLenth available in the lenskit\ndef getClosestFocal(seqCam): \n focal = cmds.getAttr(str(seqCam) + '.focalLength')\n return lensKit[min(range(len(lensKit)), key = lambda i: abs(lensKit[i]-focal))]\n\n#create layout groups\ndef createGroups():\n cmds.createNode('transform' , name = 'CAMERAS')\n cmds.createNode('transform' , name = 'ENVIRONMENT')\n cmds.createNode('transform' , name = 'PROPS')\n cmds.createNode('transform' , name = 'PROXY')\n \n#Sets the scene settings like fps etc.\ndef setScene():\n cmds.currentUnit( time='pal' )\n cmds.setAttr('defaultResolution.width',1920)\n cmds.setAttr('defaultResolution.height',1080)\n\n\n#Main execution part \n# get all sequencer shot nodes to set camera settings on \nseqShots = cmds.ls(type = \"shot\") \n\n#localization\nimage_path = (\"Z:/productions/wotw/witw_post/master_output/witw_129cmn/old_exports/exports/witw_129cmn_sc010_sh030/images/witw_129cmn_sc010_sh030.0000.jpg\")\n#start and end frame - get these from sequencer node\n\ncreateGroups()\nsetupCamera(seqShots, image_path)\nsetScene()\n","repo_name":"wildchild-animation/swing","sub_path":"module/wildchildanimation/maya/layout_camera_setup_v0_7.py","file_name":"layout_camera_setup_v0_7.py","file_ext":"py","file_size_in_byte":5901,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"46"} +{"seq_id":"14983804109","text":"from tornado.ncss import Server, ncssbook_log\nimport user\nfrom datetime import datetime\nfrom db import Category, Meme, Person, Upvote\nimport base64\nfrom template import render_file\nimport os\n\n\ndef format_time(date):\n from datetime import datetime, timedelta\n import dateutil.parser\n\n try:\n date = dateutil.parser.parse(date) # get ISO 8601 as a datetime object\n date += timedelta(hours = 11) # add 11 hours\n cur_time = datetime.utcnow()\n cur_time += timedelta(hours = 11)\n if abs(cur_time.hour - date.hour) <= 1:\n return \"Less than 1 hour ago\"\n else:\n return date.strftime('%I:%M:%S %d/%m/%Y')\n except ValueError:\n return date\n\ndef get_user_from_cookie(response):\n cookie = response.get_secure_cookie('loggedin')\n if cookie:\n cookie = cookie.decode('UTF-8')\n cookie_split = str(cookie).split(',')\n return cookie_split[1]\n else:\n return 'Username not defined in cookie'\n\ndef nearby_handler(response):\n dp = 'fixme'\n photo_list = Meme.get_memes_for_category(3)\n rendered = render_file(\"pages/nearby.html\", {\n \"dp\": dp,\n \"photo_list\": photo_list,\n })\n response.write(rendered)\n\ndef photo_save(user: str, caption: str, lat: str, long: str, base64blob):\n \"This function will take information about a photo and save it to a location.\"\n\n\n current_time = datetime.utcnow().isoformat()\n Meme.create_meme_post(base64blob, caption, lat, long, user, current_time, 3)\n\ndef login_handler(response):\n user.login_handler(response)\n\ndef logout_handler(response):\n user.logout_handler(response)\n\ndef requires_login(handler):\n def handler_(response, *args, **kwargs):\n cookie = response.get_secure_cookie('loggedin')\n if cookie:\n cookie = cookie.decode('UTF-8')\n cookie_split = str(cookie).split(',')\n if cookie_split[0] == 'True':\n handler(response, *args, **kwargs)\n else:\n response.redirect('/login')\n else:\n response.redirect('/login')\n return handler_\n\ndef index_handler(response):\n response.redirect('/feed')\n\n@requires_login\ndef profile_handler(response, user):\n profile_picture = '/static/test.png'\n person = Person.get_user_by_username(user)\n if not person:\n response.write('No user found with that name')\n return\n\n var_dict = {\n 'person': person\n }\n rendered = render_file(os.path.join('pages', 'profile.html'), var_dict)\n response.write(rendered)\n\n\ndef signup_handler(response):\n user.signup_handler(response)\n#------------------\n\ndef meme_image(response, filename):\n response.set_header('Content-Type', 'image/png')\n f = open('files/' + filename, 'rb')\n photo = f.read()\n response.write(photo)\n\n\ndef template_example(response):\n \"\"\"An unused endpoint giving a demo of the template engine.\"\"\"\n variables = {\n 'title': 'A template example',\n 'friends': ['Bella', 'Joel', 'Jaxon', 'Owen']\n }\n rendered = render_file('pages/example_body.html', variables)\n response.write(rendered)\n\n@requires_login\ndef upload_handler(response):\n \"\"\"Handles displaying the upload form, as well as recieving the data and\n entering it into the database.\"\"\"\n if response.get_field(\"caption\"):\n # The \"username\" field is not empty, so we are recieving data\n username = get_user_from_cookie(response)\n caption = response.get_field('caption')\n latitude = response.get_field('lat')\n longitude = response.get_field('long')\n if response.get_field('resized_image'):\n base64blob = response.get_field('resized_image')\n print(\"Got resized meme photo, of %d bytes in base64\" % len(base64blob))\n else:\n filename, content_type, photo_blob = response.get_file('photo')\n base64blob = \"data:{};base64,\".format(content_type) + base64.b64encode(photo_blob).decode('ascii')\n print(\"Got non-resized meme photo, of %d bytes in base64\" % len(base64blob))\n\n # Save to the database.\n photo_save(username, caption, latitude, longitude, base64blob)\n # Redirect to the feed, where they should see their new photo!\n response.redirect('/feed')\n else:\n # We need to display an upload form.\n variables = {\n 'meme_of_week_img': '/static/memeOTW.jpg'\n }\n rendered = render_file('pages/upload.html', variables)\n response.write(rendered)\n\ndef index_example(response):\n response.write(render_file('pages/index.html', {}))\n\ndef nearby_handler(response):\n dp = 'https://www.transparenthands.org/wp-content/themes/transparenthands/images/donor-icon.png'\n photo_list = Meme.get_memes_for_category(3)\n rendered = render_file(\"pages/nearby.html\", {\n \"dp\": dp,\n \"photo_list\": photo_list\n })\n response.write(rendered)\n\n# imgsrc = 'http://i0.kym-cdn.com/entries/icons/mobile/000/006/199/responsibility12(alternate).jpg'\n\ndef feed_handler(response):\n dp = 'http://i0.kym-cdn.com/profiles/icons/big/000/132/880/awesome%20face%20shrug.jpg'\n photo_list = Meme.get_memes_for_category(3)\n check_upvotes_l = lambda x: check_upvote_l(x)\n imglink = \"/post\"\n time_func = lambda x: format_time(x)\n rendered = render_file(\"pages/feed.html\", {\n \"dp\": dp,\n \"photo_list\": photo_list,\n \"imglink\": imglink,\n \"time_format\": time_func,\n 'check_upvotes': check_upvotes_l\n })\n response.write(rendered)\n\ndef upvote_meme(response, memeid):\n Upvote.create_upvote(0, 0, int(memeid))\n response.write(\"Success!!\")\n\ndef check_upvote(response, memeid):\n upvote_data = Upvote.get_upvotes_for_memes(memeid)\n response.write(\"Yay!!\")\n response.write(str(len(upvote_data)))\n\ndef check_upvote_l(memeid):\n upvote_data = Upvote.get_upvotes_for_memes(memeid)\n return str(len(upvote_data))\n\ndef post_handler(response, i):\n dp = 'http://i0.kym-cdn.com/profiles/icons/big/000/132/880/awesome%20face%20shrug.jpg'\n rendered = render_file(\"pages/post.html\", {\n \"dp\": dp,\n \"meme\": Meme.get_meme_from_id(i)\n })\n response.write(rendered)\n\n\nserver = Server()\n\nserver.register('/', index_handler)\nserver.register('/feed', feed_handler)\nserver.register('/upload', upload_handler)\nserver.register('/login', login_handler)\nserver.register('/logout', logout_handler)\nserver.register('/signup', signup_handler)\nserver.register(r'/post/(.+)', post_handler)\n#---------------\nserver.register(r'/profile/(.+)', profile_handler)\nserver.register('/index_example', index_example)\nserver.register('/nearby', nearby_handler)\nserver.register(r'/upvote_meme/(.+)', upvote_meme)\nserver.register(r'/check_upvote/(.+)', check_upvote)\n\nif __name__ == \"__main__\":\n server.run()\n","repo_name":"ncss/projects-2018-4","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"46"} +{"seq_id":"25726243857","text":"\"\"\"\nAndrin Jenal, 2017\nETH Zurich\n\"\"\"\n\nimport os\nimport collections\nfrom scipy import misc\nimport numpy as np\nimport h5py\n\nfrom time import time\n\nDatasets = collections.namedtuple('Datasets', ['train', 'validation'])\n\n\n# Load images from data set\n# Assumes images have all same size\nclass HDF5_DataSet:\n def __init__(self, _hdf5_file, _images):\n self.hdf5_file = _hdf5_file\n self.images = np.array(_images)\n self.num_examples = len(self.images)\n # initial shuffle\n self.shuffle_data()\n\n def shuffle_data(self):\n perm = np.arange(self.num_examples)\n np.random.shuffle(perm)\n self.images = self.images[perm]\n\n def next_batch(self, batch_size):\n image_batch = []\n for img in self.images:\n image_batch.append(img)\n if len(image_batch) == batch_size:\n yield np.array(image_batch)\n image_batch = []\n if len(image_batch) > 0:\n yield np.array(image_batch)\n # all examples seen, shuffle data again\n self.shuffle_data()\n\n def get_batch(self, batch_size=200):\n image_batch = []\n for img in self.images:\n image_batch.append(img)\n if len(image_batch) == batch_size:\n return image_batch\n\n def length(self):\n return len(self.images)\n\n\ndef get_normalized_image_data(image, image_size, shape, target_range=(-1,1)):\n img = misc.imresize(image, (image_size, image_size))\n img = np.asarray(img, dtype=np.float32)\n img = img * (target_range[1] - target_range[0]) / 255.0 + target_range[0]\n img = np.reshape(img, shape)\n return img\n\n\ndef get_binarized_image_data(image, image_size, shape, target_range):\n img = misc.imresize(image, (image_size, image_size))\n img = np.asarray(img, dtype=np.float32)\n img *= 255.0 / img.max() # normalize between [0, 255]\n threshold = 255.0\n _true = img < threshold\n _false = img >= threshold\n img[_true] = target_range[1] # white tree\n img[_false] = target_range[0] # black background\n return np.reshape(img, shape)\n\n\ndef load_dataset(hdf5_file, image_size, shape, normalization, normalization_range):\n res = []\n with h5py.File(hdf5_file, 'r') as _file:\n for ds in _file[_file.name]:\n res.append(normalization(_file[ds].value, image_size=image_size, shape=shape, target_range=normalization_range))\n return np.array(res)\n\n\ndef load_dataset_list(hdf5_file):\n with h5py.File(hdf5_file, 'r') as _file:\n return [ds for ds in _file[_file.name]]\n\n\ndef read_data_set(train_dir, image_size=64, shape=(64, 64), normalization_range=(-1,1), validation=1000, binarized=False, logger=None):\n h5_file = find_file(train_dir, extensions=['.hdf5', '.h5'])\n if binarized and shape[-1] == 1:\n images = load_dataset(h5_file, image_size, shape, get_binarized_image_data, normalization_range)\n else:\n images = load_dataset(h5_file, image_size, shape, get_normalized_image_data, normalization_range)\n\n shuffle_index = np.arange(images.shape[0])\n np.random.shuffle(shuffle_index)\n\n validation_images = images[shuffle_index[:validation]]\n train_images = images[shuffle_index[validation:]]\n\n train = HDF5_DataSet(train_dir, train_images)\n validation = HDF5_DataSet(train_dir, validation_images)\n\n print('data set loaded:', h5_file)\n print('dataset size:', len(images))\n print('image size:', image_size)\n print('shape:', shape)\n print('image binarization:', binarized)\n\n if logger is not None:\n logger.info('==========================Training Data==========================')\n logger.info('data set loaded: ' + str(h5_file))\n logger.info('dataset size: ' + str(len(images)))\n logger.info('image size: ' + str(image_size))\n logger.info('shape: ' + str(shape))\n logger.info('image binarization: ' + str(binarized))\n\n return Datasets(train=train, validation=validation), train_images.shape[1:]\n\n\ndef find_file(data_path, extensions):\n _file = None\n # assuming data path is a directory\n if os.path.isdir(data_path):\n for file in os.listdir(data_path):\n if file.endswith(tuple(extensions)):\n _file = os.path.join(data_path, file)\n break\n if _file:\n return _file\n else:\n print('no', extensions, 'file found in', data_path)\n\n # assuming data path is a file\n if os.path.isfile(data_path) and data_path.endswith(tuple(extensions)):\n return data_path\n else:\n print('No valid path or file:', data_path)\n raise IOError\n\n\ndef test_load_dataset():\n print('load dataset')\n start_time = time()\n data_set = read_data_set('/home/ajenal/Documents/masterthesis/project/tbone/tree_skel_all_15k_1k_1v_64x64.h5', image_size=64, shape=(64,64))\n end_time = time()\n elapsed_time = '%.3f' % (end_time - start_time)\n print('Elapsed time: ' + elapsed_time + ' seconds\\n')\n\n print('process', data_set.train.length(), 'images')\n start_time = time()\n all_train_images = []\n for train in data_set.train.next_batch(13000):\n for t in train:\n all_train_images.append(t)\n print(len(all_train_images))\n end_time = time()\n elapsed_time = '%.3f' % (end_time - start_time)\n print('Elapsed time: ' + elapsed_time + ' seconds\\n')\n\nif __name__ == '__main__':\n test_load_dataset()\n print(find_file('/home/ajenal/Documents/masterthesis/project/tbone/'))\n","repo_name":"visionen/dcgan","sub_path":"hdf5_dataset.py","file_name":"hdf5_dataset.py","file_ext":"py","file_size_in_byte":5493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"17394851176","text":"\"\"\"initial\n\nRevision ID: c17c12f7fa53\nRevises: \nCreate Date: 2022-07-05 16:18:29.683054\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = 'c17c12f7fa53'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('jokes')\n # ### end Alembic commands ###\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('jokes',\n sa.Column('id', sa.INTEGER(), autoincrement=True, nullable=False),\n sa.Column('created_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n sa.Column('updated_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n sa.Column('deleted_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True),\n sa.Column('number', sa.VARCHAR(length=256), autoincrement=False, nullable=False),\n sa.Column('value', sa.TEXT(), autoincrement=False, nullable=False),\n sa.Column('joke_from', postgresql.ENUM('dad', 'chuck', name='jokeformat'), autoincrement=False, nullable=True),\n sa.PrimaryKeyConstraint('id', name='jokes_pkey')\n )\n # ### end Alembic commands ###\n","repo_name":"Nort007/squadmakers","sub_path":"alembic/versions/c17c12f7fa53_initial.py","file_name":"c17c12f7fa53_initial.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"38893672734","text":"import json\nimport os\nimport string\nimport time\nimport random\nimport pymysql.cursors\n\n\nsql_syntax = [\"(\", \")\", \"select\", \"from\",\"where\",\"as\",\"join\", \"create\"]\nsql_join = [\"natural\", \"inner\", \"outer\", \"left\", \"right\"]\nsql_conditions = [\"=\", \">\", \"<\", \">=\", \"=<\", \"like\"]\nsql_create = [\"view\", \"table\",\"database\"]\n\ndef initiateSQL() :\n connection = pymysql.connect(host='localhost',user = 'root',password = '', db = 'Dictionary')\n return(connection)\n\ndef getSQLResult(sq,connection, All = False):\n with connection.cursor() as cursor :\n cursor.execute(sq)\n if(not All):\n result = cursor.fetchone()\n else :\n result = cursor.fetchall()\n connection.commit()\n return(result)\n\ndef constructSelect(table, col = \"*\", cond = \"\\0\", groupby = \"\\0\", orderby = \"\\0\", order = True, nested = False):\n sq =\"select \" + col + \" from \" + table\n if(cond != \"\\0\") :\n sq += \" where \" + cond\n if(groupby != \"\\0\") :\n sq += \" group by \" + groupby\n if(orderby != \"\\0\") :\n sq += \" order by \" + orderby\n if(order) :\n sq += \" asc\"\n sq += \";\"\n return(sq)\n\nsq = initiateSQL();\n\nselectStr = constructSelect(\"account\", col = \"name count()\", groupby=\"id\")\nprint(selectStr)","repo_name":"wildansupernova/DJASA","sub_path":"ConstructSQL.py","file_name":"ConstructSQL.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"73988152780","text":"from gene import Gene\nimport numpy as np\n\n\nclass Indivisual:\n def __init__(self, init_status):\n self.max_genes = 100\n self.status = []\n self.genes = []\n self.min_fitness = self.max_genes + 64\n self.fitness = 0\n gene = Gene()\n gene.setGene(init_status)\n self.genes.append(gene)\n # init run\n for i in range(self.max_genes):\n self.genes.append(self.genes[-1].actGene(np.random.choice(self.genes[-1].action)))\n\n def eval(self, correct_status):\n # if correct\n for i in self.genes:\n if i == correct_status:\n self.fitness = self.min_fitness - self.genes.index(i)\n return self.fitness\n # if not correct\n self.fitness = self.min_fitness - (self.max_genes + self.distance())\n return self.fitness\n\n def distance(self):\n gene = self.genes[-1]\n distance = 0\n for i in range(1,16+1):\n distance += abs(int(i / 4) - gene.gene.index(i)) + abs((i % 4) - gene.gene.index(i) % 4)\n return distance\n\n def cross_over(self):\n pass\n","repo_name":"LCTO-TLCO/FifteenPazzleGA","sub_path":"indivisual.py","file_name":"indivisual.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"20942482440","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import models, migrations\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [('wagtailcore', '0040_page_draft_title')]\n\n operations = [\n migrations.CreateModel(\n name='HomePage',\n fields=[\n ('page_ptr',\n models.OneToOneField(\n parent_link=True,\n auto_created=True,\n primary_key=True,\n serialize=False,\n to='wagtailcore.Page',\n on_delete=django.db.models.deletion.SET_NULL)),\n ],\n options={\n 'abstract': False,\n },\n bases=('wagtailcore.page',),\n ),\n ]\n","repo_name":"fecgov/fec-cms","sub_path":"fec/home/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":88,"dataset":"github-code","pt":"46"} +{"seq_id":"22367407572","text":"\n\n\n#original string and the string to replace it with\npattern = 'original'\nreplace = 'replacement'\n\n#paths of txt file that is opened and created\nfileread = 'Untitled.txt'\nfilewrite = 'filewrite.txt' \n\n#function that opens text file, finds a defined string, and creates a new txt file with the found string replaced with a new one\ndef sed(pattern, replace, source, dest):\n \n txt1 = open(fileread, 'r')\n txt2 = open(filewrite,'w' )\n\n for string in txt1:\n string = string.replace(pattern, replace)\n txt2.write(string)\n \n #properly closes txt files\n txt1.close()\n txt2.close()\n\n#calls the function\nsed(pattern, replace, fileread, filewrite)\n\n\n\n\n\n","repo_name":"Tliss1984/GIS-Programming","sub_path":"14.1.py","file_name":"14.1.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"10049125535","text":"import math\n\n\ndef time_to_minutes(time):\n time = time.split(\":\")\n\n return int(time[0]) * 60 + int(time[1])\n\n\ndef solution(fees, records):\n status = {}\n result = {}\n\n for r in records:\n time, car, state = r.split() # 시간, 차량번호, 상태\n\n if state == 'IN':\n status[car] = time\n else:\n in_time = status.pop(car)\n in_time = time_to_minutes(in_time)\n out_time = time_to_minutes(time)\n\n if car not in result:\n result[car] = 0\n\n result[car] += out_time - in_time\n\n if status:\n for car in status:\n in_time = status[car]\n in_time = time_to_minutes(in_time)\n\n if car not in result:\n result[car] = 0\n\n result[car] += 1439 - in_time # '23:59': 1439분\n\n answer = []\n\n for car in sorted(result.keys()):\n usage = result[car] # 총 사용 시간\n total_cost = fees[1] + math.ceil(max(0, usage - fees[0]) / fees[2]) * fees[\n 3] # fees >> 기본 시간(분), 기본 요금(원), 단위 시간(분), 단위 요금(원)\n answer.append(total_cost)\n\n return answer\n","repo_name":"SmilingSammy/TIL","sub_path":"Algorithm/coding-test/programmers/Lv2/parking.py","file_name":"parking.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"71061415820","text":"mySet = {\"webbtelescope\", 123, True} # Sets are made\n# similarly to lists but they can be any types of values and are unordered\nthisdict = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 2021,\n \"color\": [\"Twister Orange\", \"Yellow Peel\", \"Lucid Red Pearl\", \"Velocity Blue\", \"Ford Performance Blue\", \"Absolute Black\", \"Antimatter Blue\", \"Iconic Silver Metallic\", \"Carbonized Gray Metallic\", \"Fighter Jet Gray\", \"Race Red\", \"Oxford White\"]\n}\nprint(thisdict)\nx = 1324865823465\nif x > 0:\n print(x, \" is a positive number\")\nelif x == 0:\n print(x,\" = 0\")\nelse:\n print(x,\" is a negative number\")\na = 330\nb = 330\nprint(\"A\") if a > b else print(a,\"=\",b) if a == b else print(\"B\")\na = 2\nb = 10\nprint(a) if a < b else print(b)\nif b > a:\n pass\n#while b > a:\n# if b == 5:\n# continue\n# print(b)\n# b = b-1\n#i = 0\n#while i < 6:\n# i += 1\n# if i == 3:\n# continue\n# print(i)\nfor z in mySet: # this prints mySet\n print(z)\nfor x in range(6):\n print(x)\nelse:\n print(\"Finally finished!\")\n\ndict1 = {1: \"Bitcoin\", 2: \"Ethereum\"}\nfor key, value in dict1.items():\n print(f\"Key {key} has value {value}\")","repo_name":"astro648/FirstSeleniumProject","sub_path":"intermediate1.py","file_name":"intermediate1.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"14892546008","text":"fav_songs = {\"Ария\": [\"Возьми мое сердце\",\"Свет былой любви\"],\n \"Би-2\": [\"Философский камень\",\"Молитва\", \"Черное солнце\"],\n \"Bon Jovi\": \"It's my life\",\n \"LOUNA\": [\"Мама\",\"Моя оборона\", \"Штурмуя небеса\"],\n \"Lumen\": [\"Гореть\", \"Игра\"]\n }\n\nprint(fav_songs)\n\n\n","repo_name":"fox67rus/the_self_taught_programmer","sub_path":"chap05/chap5_challenge5.py","file_name":"chap5_challenge5.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"72267435020","text":"#QCheckBox_1.py\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n\nform_class = uic.loadUiType(\"QCheckBox_1.ui\")[0]\n\nclass WindowClass(QMainWindow, form_class):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n\n self.checkBox.stateChanged.connect(self.chkFunc) #stateChanged 시그널 \n self.checkBox_2.stateChanged.connect(self.chkFunc)\n self.checkBox_3.stateChanged.connect(self.chkFunc)\n\n self.label.setText(\"Vacation to Korea!\") #Display-QLabel 위젯 \n \n \n def chkFunc(self):\n if self.checkBox.isChecked(): print(\"부산 Checked\") #isChecked()로 확\n if self.checkBox_2.isChecked(): print(\"제주도 Checked\")\n if self.checkBox_3.isChecked(): print(\"서울 Checked\")\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n myWindow = WindowClass()\n myWindow.show()\n app.exec_()\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":"ektmf7890/2020-1-FORIF-Python-Study","sub_path":"forif/pyqt/QCheckBox_1.py","file_name":"QCheckBox_1.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"18409489519","text":"import folium\nfrom folium import IFrame\nimport base64\n\nmap = folium.Map(location=[10.803489489100986,\n 76.81870306540125], zoom_start=15)\n\nhtml = ''.format\n\npicture_tom = base64.b64encode(open(\"./tom.jpg\", 'rb').read()).decode()\niframe_tom = IFrame(html(picture_tom), width=327+20, height=160+20)\npopup_tom = folium.Popup(iframe_tom, max_width=650)\nricon_tom = folium.features.CustomIcon('img.png', icon_size=(40, 40))\nfolium.Marker(location=[10.799134430915721, 76.81813182028293],\n tooltip=\"Taste of Malabar\", popup=popup_tom, icon=ricon_tom).add_to(map)\n\nmap.save(\"tom.html\")\n","repo_name":"jack-yeager/interactive-map-iitpkd-w10","sub_path":"tom.py","file_name":"tom.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"33288024775","text":"from __future__ import unicode_literals\nimport frappe\nfrom frappe import utils\nfrom frappe.utils import getdate\nfrom frappe.model.document import Document\nimport datetime\n\nclass EntregayPagodeMineral(Document):\n\t\n\tdef validate(self):\n\t\t\n\t\tes_activo = frappe.db.get_value(\"Minero Artesanal\", {\"name\": self.minero_artesanal}, \"es_activo\")\n\t\tfecha_salida = frappe.db.get_value(\"Minero Artesanal\", {\"name\": self.minero_artesanal}, \"fecha_salida\")\n\t\tfecha_ingreso = frappe.db.get_value(\"Minero Artesanal\", {\"name\": self.minero_artesanal}, \"fecha_ingreso\")\n\t\tfecha_constitucion = frappe.db.get_single_value('Cooperativa de Mineria Artesanal', 'fecha_constitucion')\n\t\t\n\t\t\n\t\tfecha_entrega = getdate(self.fecha_entrega)\n\t\t\n\t\ttoday = getdate(utils.today())\n\t\tif fecha_entrega > today:\n\t\t\tfrappe.throw(\"La fecha de entrega ({0}) no puede ser mayor al dia de hoy ({1})\".format(fecha_entrega, today),title=\"Fecha Inválida\")\n\t\t\n\t\t#if fecha_salida:\n\t\t\t#if not es_activo and fecha_salida <= fecha_entrega:\n\t\t\t\t#frappe.throw(\"El socio {0} no se encuentra activo, verifique su estatus con la Cooperativa.\".format(self.nombre_minero_artesanal))\n\t\t\n\t\tif not es_activo:\n\t\t\tfrappe.throw(\"El socio {0} no se encuentra activo, verifique su estatus con la Cooperativa.\".format(self.nombre_minero_artesanal))\n\t\t\t\n\t\t#if fecha_ingreso:\n\t\t\t#if fecha_entrega < fecha_ingreso:\n\t\t\t\t#frappe.throw(\"La fecha de entrega ({0}) es menor a la fecha de ingreso ({1}) del socio {2} a la #Cooperativa.\".format(fecha_entrega,fecha_ingreso, self.nombre_minero_artesanal),title=\"Fecha Inválida\")\t\t\n\t\t\t\n\t\t\n\t\t#if fecha_constitucion:\n\t\t\t#fc = getdate(fecha_constitucion)\n\t\t\t#if fecha_entrega < fc:\n\t\t\t\t#frappe.throw(\"La fecha de entrega ({0}) es menor a la fecha de constitución ({1}) de la cooperativa.\".format(fecha_entrega,fc),title=\"Fecha #Inválida\")\n\t\t\n\t\t\n\t\tif self.tiene_colilla:\n\t\t\t\n\t\t\tif self.toneladas_aceptadas > self.toneladas_entregadas:\n\t\t\t\tfrappe.throw(\"Las toneladas aceptadas ({0} Ton) no pueden ser mayor a las toneladas entregadas ({1} Ton)\".format(self.toneladas_aceptadas,self.toneladas_entregadas),title=\"Datos Inválidos\")\n\t\t\t\t\n\t\t\tif self.fecha_pago:\n\t\t\t\tfecha_pago = getdate(self.fecha_pago)\n\t\t\t\t\n\t\t\t\tif fecha_pago < fecha_entrega:\n\t\t\t\t\tfrappe.throw(\"La fecha de pago ({0}) no puede ser menor a la fecha de entrega ({1})\".format(fecha_pago,fecha_entrega),title=\"Fecha Inválida\")\t\t\n\t\t\t\n\t\t\t\t\n\t\t\t\tif not self.fecha_pago or not self.toneladas_aceptadas or not self.ley or not self.onzas_oro or not self.tipo_de_cambio or not self.precio_internacional_oro or not self.precio_internacional_plata:\n\t\t\t\t\tfrappe.throw(\"Debe llenar todos los campos requeridos del comprobante de pago\",title=\"Completar datos\")\n","repo_name":"ernestoruiz89/sig_mineros","sub_path":"sig_mineros/sig_mineros/doctype/entrega_y_pago_de_mineral/entrega_y_pago_de_mineral.py","file_name":"entrega_y_pago_de_mineral.py","file_ext":"py","file_size_in_byte":2733,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"42285695557","text":"import pandas as pd\nfrom IPython.display import display\n\ndf = pd.read_csv(\n \"/home/hanzala/Development/Python_the_ultimate_course_2023/22. Pandas and Tabular Data Processing/datafarm_basics.csv\")\n\n\npd.set_option(\"display.max_rows\", None) # showall\n\ndisplay(df)\n\nprint('--------------------------------')\n\nageTotal = df['age'].sum()\n\nprint(\"Total age of filter items:\", ageTotal)\n","repo_name":"MHanzzala/Python_the_ultimate_course_2023","sub_path":"22. Pandas and Tabular Data Processing/4_SumData.py","file_name":"4_SumData.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"40983797355","text":"\"\"\"sec URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom .views import *\n\n\nurlpatterns = [\n path('administrativo/', administrativo, name= 'administrativo'),\n path('beneficios/', beneficios),\n path('contacto/', contacto, name= 'contacto'),\n path('gimnasio/', gimnasio),\n path('', home, name= 'home'),\n path('personas/', include('apps.personas.urls')),\n path('listadoPendientes/', listadoDePendientes, name='pendientes'),\n path('listadoAfiliados/', include('apps.afiliados.urls')),\n path('listadoSalones/', listadoSalones, name='listadoSalones'),\n path('listadoAlumnos/', listadoAlumnos, name='listadoAlumnos'),\n path('listadoAlquileres/', listadoAlquileres, name='listadoAlquileres'),\n path('listadoCursos/', include('apps.cursos.urls')),\n path('login/', login, name= 'login'),\n path('usuario/', usuario),\n path('admin/', admin.site.urls),\n path('registro/', registro, name= 'registro'),\n path('verAlumno/', verAlumno, name='verAlumno'),\n path('verAlquiler/', verAlquiler, name='verAlquiler'),\n path('verProfesor/', verProfesor, name='verProfesor'),\n path('verCurso/', verCurso, name='verCurso'),\n path('verSalon/', verSalon, name='verSalon'),\n path('verAfiliado/', verAfiliado, name='verAfiliado'),\n path('salones/', include('apps.salones.urls')),\n path('afiliados/', include('apps.afiliados.urls')),\n path('cursos/', include('apps.cursos.urls')),\n path(\"select2/\", include(\"django_select2.urls\")),\n]\n","repo_name":"UNPSJB/Sec1","sub_path":"sources/sec/sec/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"38343503324","text":"import os \nfrom librosa.feature import melspectrogram\nfrom scipy.io import wavfile as w\n\nfilelist = os.listdir(os.curdir)\ndirlist = [i for i in filelist if os.path.isdir(os.path.join(os.curdir,i))]\nfor dirname in dirlist:\n\tl = os.listdir(dirname)\n\ti = 1\n\tfor filename in l:\n\t\tif(filename.endswith('.wav')):\n\t\t\tfs,d = w.read(os.path.join(dirname,filename))\n\t\t\td = np.array(d,dtype = float)\n\t\t\td /= 32,767\n\t\t\tm = melspectrogram(d,fs,n_mels = 80,n_fft = 400,hop_length = 160,fmax = 8000)\n\t\t\tfspec = io.open(dirname+'spec','w')\n\t\t\tfor row in m:\n\t\t\t\tfor j in row:\n\t\t\t\t\tfspec.write(str(j))\n\t\t\t\tfspec.write('\\n')\n\t\t\ti = i+1\n","repo_name":"Gadamsetty/ML_practise","sub_path":"gen_melspec.py","file_name":"gen_melspec.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"17856487454","text":"from django.http import HttpResponse, HttpResponseForbidden\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom django.utils import timezone, html\nfrom django.core.paginator import (Paginator, EmptyPage, PageNotAnInteger,)\nfrom django.core.management import call_command\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import TemplateView, FormView\nfrom django.views.generic.detail import SingleObjectMixin\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.contrib import messages as djmessages\nfrom django.views import generic, View\nfrom django.urls import reverse, reverse_lazy\nfrom _keenthemes.__init__ import KTLayout\nfrom _keenthemes.libs.theme import KTTheme\n\nfrom ranker.models import Domain, KeywordFile, Conversation, Template, TemplateItem, Message, Project, ProjectUser, ProjectDomain, AIModel\nfrom ranker.forms import KeywordFileForm, TemplateItemForm, MessageForm, TemplateForm\nfrom ranker.tasks import save_message_response, call_openai\nfrom celery import chain\n\nimport csv\nimport os\nimport openai\nimport markdown\nimport json\n\n\n@login_required\ndef conversation_detail(request, conversation_id):\n conversation = get_object_or_404(Conversation, pk=conversation_id)\n chat_messages = conversation.message_set.filter(visible=True).order_by('order')\n \n default_page = 1\n page_number = request.GET.get('page', default_page)\n\n # Paginate items\n items_per_page = 1\n paginator = Paginator(chat_messages, items_per_page)\n\n try:\n page_obj = paginator.get_page(page_number)\n except PageNotAnInteger:\n page_obj = paginator.get_page(default_page)\n except EmptyPage:\n page_obj = paginator.get_page(paginator.num_pages)\n return render(request, 'ranker/conversation_detail.html', {'conversation': conversation, 'chat_messages': chat_messages, 'page_obj': page_obj})\n\n@login_required\ndef conversation_add(request, template_id, domain_id, ai_model_id):\n template = get_object_or_404(Template, pk=template_id)\n domain = get_object_or_404(Domain, pk=domain_id)\n ai_model = get_object_or_404(AIModel, pk=ai_model_id)\n if Conversation.objects.filter(template_id__exact=template.id).filter(domain_id__exact=domain.id).filter(ai_model_id__exact=ai_model.id).filter(project_id__isnull=True).count() == 0:\n conversation = Conversation(domain=domain, template=template, ai_model=ai_model)\n conversation.save()\n template_items = template.templateitem_set.all()\n for template_item in template_items:\n m = Message(\n prompt = template_item.prompt1, #TODO: Add logic that uses tokens and concatenates with other parts of prompt\n title = template_item.title,\n visible = template_item.visible,\n order = template_item.order,\n conversation = conversation,\n template_item = template_item,\n )\n m.prompt = m.prompt.replace(\"@currentDomain\", conversation.domain.domain)\n m.save()\n else:\n conversation = Conversation.objects.get(template=template, domain=domain, ai_model=ai_model, project=None)\n #TODO: Add combined unique requirement on conversation(template, domain) and figure out how to do this better\n return redirect('conversation_edit', conversation_id=conversation.id)\n\n@login_required\ndef conversation_edit(request, conversation_id):\n conversation = get_object_or_404(Conversation, pk=conversation_id)\n chat_messages = conversation.message_set.all().order_by('order')\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n form = MessageForm(request.POST)\n # check whether it's valid:\n if form.is_valid():\n message = form.save(commit=False)\n message.conversation = conversation\n message.order = 100\n message.save()\n djmessages.success(request, \"Message updated.\")\n\n # if a GET (or any other method) we'll create a blank form\n else:\n form = MessageForm()\n return render(request, 'ranker/conversation_edit.html', {'chat_messages': chat_messages, 'conversation': conversation, 'form': form})\n\n@login_required\ndef conversation_update_order(request, conversation_id):\n conversation = get_object_or_404(Conversation, pk=conversation_id)\n chat_messages = conversation.message_set.all().order_by('order')\n\n if request.method == 'POST':\n # create a form instance and populate it with data from the request:\n message_ids = json.loads(request.body) \n index = 0\n while index < len(message_ids):\n message = get_object_or_404(Message, pk=int(message_ids[index]))\n message.order = index\n message.save()\n index += 1\n\n form = MessageForm()\n #Note that we are calling these \"chat_messages\" this is to namespace them from django 'messages' which we also want to use\n return render(request, 'ranker/conversation_edit.html', {'conversation': conversation, 'chat_messages': chat_messages, 'form': form})\n\n@login_required\ndef conversation_get_responses(request, conversation_id):\n conversation = get_object_or_404(Conversation, pk=conversation_id)\n\n if request.method == 'POST':\n djmessages.info(request, \"Requesting responses.\")\n conversation.requested_at = timezone.now()\n conversation.save()\n for message in conversation.message_set.filter(requested_at=None):\n message.requested_at = timezone.now()\n message.save()\n call_openai.apply_async( (message.prompt,), link=save_message_response.s(message.id)) #note the comma in arguments, critical to imply tuple, otherwise thinks array\n return redirect('conversation_detail', conversation_id=conversation.id)\n\n@login_required\ndef message_delete(request, message_id):\n message = get_object_or_404(Message, pk=message_id)\n conversation = message.conversation\n\n if request.method == 'POST':\n message.delete()\n djmessages.error(request, \"Message deleted.\")\n \n return redirect('conversation_edit', conversation_id=conversation.id)","repo_name":"adalyuf/topranks","sub_path":"ranker/conversations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"43415530524","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport json\nimport time\n\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseBadRequest\nfrom django.core import serializers\nfrom django.contrib.auth.decorators import login_required\nfrom django.conf import settings\n\nfrom .models import Contact, RequestsStore\nfrom .decorator import not_record_request\nfrom .forms import ContactForm\n\n\ndef home_page(request):\n context = {}\n person = Contact.objects.first()\n context['person'] = person\n return render(request, 'home.html', context)\n\n\ndef request_view(request):\n return render(request, 'requests.html')\n\n\n@not_record_request\ndef request_ajax(request):\n if request.is_ajax():\n if request.method == 'POST':\n path = request.POST['path']\n priority = request.POST['priority']\n if int(priority) >= 0:\n RequestsStore.objects.filter(path=path)\\\n .update(priority=priority)\n return HttpResponse(json.dumps({'response': 'ok'}),\n content_type='application/json')\n\n viewed = request.GET.get('viewed')\n if viewed == 'yes':\n RequestsStore.objects.filter(new_request=1).update(new_request=0)\n\n new_request = RequestsStore.objects.filter(new_request=1).count()\n request_list = RequestsStore.objects.all()[:10]\n request_list = list(request_list)\n request_list.sort(key=lambda a: a.path)\n list_req = serializers.serialize(\"json\", request_list)\n data = json.dumps((new_request, list_req))\n return HttpResponse(data, content_type=\"application/json\")\n\n return HttpResponseBadRequest('Error request')\n\n\n@login_required(login_url='/login/')\ndef form_page(request):\n person = Contact.objects.first()\n\n if request.method == 'POST':\n form = ContactForm(request.POST, request.FILES, instance=person)\n\n if form.is_valid():\n new_person = form.save(commit=False)\n\n if request.POST.get('image-clear') is None:\n if new_person.image is None:\n new_person.image = person.image\n new_person.save()\n\n if request.is_ajax():\n if getattr(settings, 'DEBUG', False):\n time.sleep(3)\n\n list_pers = serializers.serialize(\"json\", [person, ])\n return HttpResponse(json.dumps(list_pers),\n content_type=\"application/json\")\n else:\n return redirect('hello:home')\n else:\n if request.is_ajax():\n if getattr(settings, 'DEBUG', False):\n time.sleep(2)\n errors_dict = {}\n\n if form.errors:\n for error in form.errors:\n e = form.errors[error]\n errors_dict[error] = unicode(e)\n\n return HttpResponseBadRequest(json.dumps(errors_dict),\n content_type=\"application/json\")\n else:\n form = ContactForm(instance=person)\n\n return render(request, 'edit_form.html', {'form': form})\n","repo_name":"leksw/FortyTwoTestTask","sub_path":"apps/hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"46"} +{"seq_id":"29956790794","text":"import argparse\nimport logging\nimport os\nimport json\nfrom tqdm import tqdm\nimport numpy as np\nimport sys\nsys.path.append(\"../\") \n\nfrom utils import (\n evaluate,\n)\n\nfrom src.data_loader import (\n DictionaryDataset,\n QueryDataset,\n QueryDataset_custom,\n QueryDataset_COMETA,\n)\nfrom src.model_wrapper import (\n Model_Wrapper\n)\nLOGGER = logging.getLogger()\n\ndef parse_args():\n \"\"\"\n Parse input arguments\n \"\"\"\n parser = argparse.ArgumentParser(description='sapbert evaluation')\n\n # Required\n parser.add_argument('--model_dir', required=True, help='Directory for model')\n parser.add_argument('--dictionary_path', type=str, required=True, help='dictionary path')\n parser.add_argument('--data_dir', type=str, required=True, help='data set to evaluate')\n\n # Run settings\n parser.add_argument('--use_cuda', action=\"store_true\")\n parser.add_argument('--output_dir', type=str, default='./output/', help='Directory for output')\n parser.add_argument('--filter_composite', action=\"store_true\", help=\"filter out composite mention queries\")\n parser.add_argument('--filter_duplicate', action=\"store_true\", help=\"filter out duplicate queries\")\n parser.add_argument('--save_predictions', action=\"store_true\", help=\"whether to save predictions\")\n\n # Tokenizer settings\n parser.add_argument('--max_length', default=25, type=int)\n \n # options for COMETA\n parser.add_argument('--cometa', action=\"store_true\", \\\n help=\"whether to load full sentence from COMETA (or just use the mention)\")\n parser.add_argument('--medmentions', action=\"store_true\")\n parser.add_argument('--custom_query_loader', action=\"store_true\")\n #parser.add_argument('--cased', action=\"store_true\")\n\n parser.add_argument('--agg_mode', type=str, default=\"cls\", help=\"{cls|mean_pool|nospec}\")\n\n args = parser.parse_args()\n return args\n \ndef init_logging():\n LOGGER.setLevel(logging.INFO)\n fmt = logging.Formatter('%(asctime)s: [ %(message)s ]',\n '%m/%d/%Y %I:%M:%S %p')\n console = logging.StreamHandler()\n console.setFormatter(fmt)\n LOGGER.addHandler(console)\n\ndef load_dictionary(dictionary_path): \n dictionary = DictionaryDataset(\n dictionary_path = dictionary_path\n )\n return dictionary.data\n\ndef load_queries(data_dir, filter_composite, filter_duplicate):\n dataset = QueryDataset(\n data_dir=data_dir,\n filter_composite=filter_composite,\n filter_duplicate=filter_duplicate\n )\n return dataset.data\n\ndef load_queries_COMETA(data_dir, load_full_sentence, filter_duplicate):\n dataset = QueryDataset_COMETA(\n data_dir=data_dir,\n load_full_sentence=load_full_sentence,\n filter_duplicate=filter_duplicate\n )\n return dataset.data\n \ndef main(args):\n init_logging()\n print(args)\n\n # load dictionary and data\n eval_dictionary = load_dictionary(dictionary_path=args.dictionary_path)\n print (\"[reference dictionary loaded]\")\n #if \"chv-dev\" in args.data_dir:\n if args.cometa:\n print (\"[loading COMETA queries...]\")\n eval_queries = load_queries_COMETA( \n data_dir=args.data_dir,\n load_full_sentence=False,\n filter_duplicate=args.filter_duplicate\n )\n print (\"[COMETA queries loaded]\")\n elif args.custom_query_loader:\n print (\"[loading custom queries...]\")\n dataset = QueryDataset_custom(\n data_dir=args.data_dir,\n filter_duplicate=args.filter_duplicate\n )\n eval_queries = dataset.data\n print (\"[custom queries loaded]\")\n else:\n eval_queries = load_queries(\n data_dir=args.data_dir,\n filter_composite=args.filter_composite,\n filter_duplicate=args.filter_duplicate\n )\n\n model_wrapper = Model_Wrapper().load_model(\n path=args.model_dir,\n max_length=args.max_length,\n use_cuda=args.use_cuda,\n )\n \n print (\"[start evaluating...]\")\n result_evalset = evaluate(\n model_wrapper=model_wrapper,\n eval_dictionary=eval_dictionary,\n eval_queries=eval_queries,\n topk=10, # sort only the topk to save time\n cometa=args.cometa,\n medmentions=args.medmentions,\n agg_mode=args.agg_mode\n )\n \n LOGGER.info(\"acc@1={}\".format(result_evalset['acc1']))\n LOGGER.info(\"acc@5={}\".format(result_evalset['acc5']))\n #wandb.log({\"acc1\": result_evalset[\"acc1\"], \"acc5\": result_evalset[\"acc5\"]})\n \n if args.save_predictions:\n output_file = os.path.join(args.output_dir,\"predictions_eval.json\")\n with open(output_file, 'w') as f:\n json.dump(result_evalset, f, indent=2)\n\nif __name__ == '__main__':\n args = parse_args()\n main(args)\n","repo_name":"cambridgeltl/sapbert","sub_path":"evaluation/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"46"} +{"seq_id":"6886533035","text":"##kcharlesr\n\n#import modules\nimport os\nimport csv\n\n#csv path -- beginning in 'JHU_Git_Repo/Python' directory\ncsvpath = os.path.join(\"PyPoll\",\"Resources\",\"election_data.csv\")\n\n#read in csv file and skip header\nwith open(csvpath, newline='') as csvfile: \n csvreader = csv.reader(csvfile, delimiter=',')\n csv_header = next(csvreader)\n \n #Define variables and variable types\n candidates = []\n vote_count = []\n winner_count = 0\n total_votes = 0\n\n #Create loop to tally total vote counts and vote counts for each individual candidate\n for row in csvreader:\n total_votes += 1\n if(row[2] not in candidates):\n candidates.append(row[2])\n vote_count.append(0)\n candidateIndex = candidates.index(row[2])\n vote_count[candidateIndex] += 1\n\n \n #Create Loop and Print summary of results to terminal\n print(f'Election Results')\n print('-' * 25)\n print(f'Total Votes: {total_votes}')\n print('-' * 25)\n for x in range(len(candidates)):\n votePercent = round((vote_count[x]/total_votes)*100,3)\n print(f\"{candidates[x]}: {votePercent}% ({vote_count[x]})\")\n if (winner_count Deploying {NUM_SIGNING_ACCOUNTS} accounts...')\n for i in range(NUM_SIGNING_ACCOUNTS):\n signer = Signer(DUMMY_PRIVATE + i)\n account = await starknet.deploy(\n \"contracts/libs/Account.cairo\",\n constructor_calldata=[signer.public_key]\n )\n await account.initialize(account.contract_address).invoke()\n users.append({\n 'signer' : signer,\n 'account' : account\n })\n\n LOGGER.info(f'> Account {i} is: {account.contract_address}')\n LOGGER.info('')\n\n return accounts\n\n@pytest.fixture\nasync def block_info_mock(starknet):\n class Mock:\n def __init__(self, current_block_info):\n self.block_info = current_block_info\n\n def update(self, block_number, block_timestamp):\n starknet.state.state.block_info = BlockInfo(\n block_number, block_timestamp,\n self.block_info.gas_price,\n self.block_info.sequencer_address\n )\n\n def reset(self):\n starknet.state.state.block_info = self.block_info\n\n def set_block_number(self, block_number):\n starknet.state.state.block_info = BlockInfo(\n block_number, self.block_info.block_timestamp,\n self.block_info.gas_price,\n self.block_info.sequencer_address\n )\n\n def set_block_timestamp(self, block_timestamp):\n starknet.state.state.block_info = BlockInfo(\n self.block_info.block_number, block_timestamp,\n self.block_info.gas_price,\n self.block_info.sequencer_address\n )\n\n return Mock(starknet.state.state.block_info)\n\n@pytest.mark.asyncio\nasync def test_lobby (account_factory, starknet, block_info_mock):\n\n accounts = account_factory\n\n # Testing strategy\n # 0. deploy mock-universes and hook them up with lobby; deploy mock-dao and hook it up with lobby\n # 1. test players joining queue working fine\n # 2. test yagi proving can-dispatch and execute-dispatch\n # 3. check player addresses in activated mock-universe matching expected\n # 4. let mock-universe call lobby's `universe_report_play()`\n\n contract_universes = []\n for _ in range(UNIVERSE_COUNT):\n contract = await starknet.deploy (source = 'contracts/mocks/mock_skeletal_universe.cairo', constructor_calldata = [])\n contract_universes.append (contract)\n LOGGER.info (f'> {UNIVERSE_COUNT} universe contracts deployed')\n\n lobby_constructor_calldata = [UNIVERSE_COUNT] + [c.contract_address for c in contract_universes] # array length followed by array elements\n contract_lobby = await starknet.deploy (source = 'contracts/lobby/lobby.cairo', constructor_calldata = lobby_constructor_calldata)\n LOGGER.info (f'> Lobby contract deployed with universe addresses recorded at {contract_lobby.contract_address}')\n\n contract_dao = await starknet.deploy (source = 'contracts/mocks/mock_skeletal_dao.cairo', constructor_calldata = [])\n await contract_dao.set_subject_address_once(contract_lobby.contract_address).invoke()\n LOGGER.info (f'> DAO contract deployed at {contract_dao.contract_address}; lobby address registered as subject address')\n\n for contract in contract_universes:\n await contract.set_lobby_address_once(contract_lobby.contract_address).invoke()\n LOGGER.info (f'> Register lobby address in every universe contract.')\n\n await contract_lobby.set_dao_address_once(contract_dao.contract_address).invoke()\n LOGGER.info (f'> Register dao address in lobby contract.')\n LOGGER.info('')\n\n ## Test invoking anyone_ask_to_queue() from 0x0 address => should revert\n LOGGER.info(f'> Test 0: asking to join queue from 0x0 address should revert.')\n with pytest.raises(Exception) as e_info:\n await contract_lobby.anyone_ask_to_queue().invoke()\n\n ## can-dispatch should return false\n LOGGER.info(f'> Test 1: can-dispatch should return 0 at start.')\n ret = await contract_lobby.can_dispatch_player_to_universe().call()\n assert ret.result.bool == 0\n\n ## users[0] and users[1] join queue\n LOGGER.info(f'> Test 2: Two players join queue; can-dispatch should still return 0.')\n for player in users[0:2]:\n await player['signer'].send_transaction(\n account = player['account'], to = contract_lobby.contract_address,\n selector_name = 'anyone_ask_to_queue',\n calldata=[]\n )\n\n ret = await contract_lobby.can_dispatch_player_to_universe().call()\n assert ret.result.bool == 0\n\n ## users[1] attempts joining the queue again => should fail\n LOGGER.info(f'> Test 3: A player attempts to rejoin queue => tx should fail.')\n with pytest.raises(Exception) as e_info:\n await users[1]['signer'].send_transaction(\n account = users[1]['account'], to = contract_lobby.contract_address,\n selector_name = 'anyone_ask_to_queue',\n calldata=[]\n )\n\n ## confirm storage `queue_address_to_index`, `queue_head_index` and `queue_tail_index` match expected\n LOGGER.info(f'> Test 4: Confirm queue address=>index, head index, and tail index all match expected.')\n ret = await contract_lobby.queue_address_to_index_read(users[0]['account'].contract_address).call()\n users0_idx = ret.result.idx\n ret = await contract_lobby.queue_address_to_index_read(users[1]['account'].contract_address).call()\n users1_idx = ret.result.idx\n assert (users0_idx, users1_idx) == (1, 2) # queue idx starts from 1; 0 is reserved from not-in-queue\n\n ret = await contract_lobby.queue_head_index_read().call()\n head_idx = ret.result.head_idx\n ret = await contract_lobby.queue_tail_index_read().call()\n tail_idx = ret.result.tail_idx\n assert (head_idx, tail_idx) == (0, 2)\n\n ## users[2] joins queue\n LOGGER.info(f'> Test 5: The 3rd player joins queue; can-dispatch should return 1 now.')\n await users[2]['signer'].send_transaction(\n account = users[2]['account'], to = contract_lobby.contract_address,\n selector_name = 'anyone_ask_to_queue',\n calldata=[]\n )\n ret = await contract_lobby.can_dispatch_player_to_universe().call()\n assert ret.result.bool == 1\n\n ## users[3] and users[4] join queue\n LOGGER.info(f'> Test 6: The 4th and 5th player join queue; can-dispatch should still return 1; check queue head & tail')\n for user in users[3:5]:\n await user['signer'].send_transaction(\n account = user['account'], to = contract_lobby.contract_address,\n selector_name = 'anyone_ask_to_queue',\n calldata=[]\n )\n ret = await contract_lobby.can_dispatch_player_to_universe().call()\n assert ret.result.bool == 1\n\n ret = await contract_lobby.queue_head_index_read().call()\n head_idx = ret.result.head_idx\n ret = await contract_lobby.queue_tail_index_read().call()\n tail_idx = ret.result.tail_idx\n assert (head_idx, tail_idx) == (0, 5)\n\n ## set l2 block\n block_info_mock.set_block_number(345)\n\n ## dispatch players to universe\n LOGGER.info(f\"> Test 7: Invoke dispatch function once; check queue head & tail; check universe-0's civilization addresses, civ index, genesis block\")\n ret_dispatch = await contract_lobby.anyone_dispatch_player_to_universe().invoke()\n # LOGGER.info(f\"-- events: {ret_dispatch.main_call_events}\")\n\n ret = await contract_lobby.queue_head_index_read().call()\n head_idx = ret.result.head_idx\n ret = await contract_lobby.queue_tail_index_read().call()\n tail_idx = ret.result.tail_idx\n assert (head_idx, tail_idx) == (3, 5)\n\n ret = await contract_universes[0].civilization_index_read().call()\n assert ret.result.civ_idx == 1\n\n ret = await contract_universes[0].l2_block_at_genesis_read().call()\n assert ret.result.number == 345\n\n ret = await contract_lobby.universe_active_read(UNIVERSE_INDEX_OFFSET + 0).call()\n assert ret.result.is_active == 1\n ret = await contract_lobby.universe_active_read(UNIVERSE_INDEX_OFFSET + 1).call()\n assert ret.result.is_active == 0\n ret = await contract_lobby.universe_active_read(UNIVERSE_INDEX_OFFSET + 2).call()\n assert ret.result.is_active == 0\n\n for i in range(3):\n ret = await contract_universes[0].civilization_player_idx_to_address_read(i).call()\n LOGGER.info(f' universe 0: player address at idx {i} = {ret.result.address}')\n assert ret.result.address == users[i]['account'].contract_address\n\n ret = await contract_universes[0].civilization_player_address_to_bool_read(users[i]['account'].contract_address).call()\n assert ret.result.bool == 1 # active\n\n ## check the other universe\n LOGGER.info(f\"> Test 8: Make sure universe-1's status is unchanged\")\n\n ret = await contract_universes[1].civilization_index_read().call()\n assert ret.result.civ_idx == 0\n\n ret = await contract_universes[1].l2_block_at_genesis_read().call()\n assert ret.result.number == 0\n\n for i in range(3):\n ret = await contract_universes[1].civilization_player_idx_to_address_read(i).call()\n assert ret.result.address == 0\n\n ## prepare universe 0 - give the second player has-launch-ndpe\n await contract_universes[0].test_write_civilization_player_address_to_has_launched_ndpe(\n users[1]['account'].contract_address,\n 1\n ).invoke()\n\n ## terminate universe, which should notify lobby; check accordingly\n LOGGER.info(f\"> Test 9: Given users[1] launched ndpe, terminate universe; check universe civ empty; check dao votes against expected\")\n ret = await contract_universes[0].test_terminate_universe_and_notify_lobby(\n bool_universe_escape_condition_met = 1\n ).invoke()\n\n for i in range(3):\n ret = await contract_universes[0].civilization_player_idx_to_address_read(i).call()\n assert ret.result.address == 0 # cleared\n\n ret = await contract_universes[0].civilization_player_address_to_bool_read(users[i]['account'].contract_address).call()\n assert ret.result.bool == 0 # inactive\n\n player_adr = users[0]['account'].contract_address\n ret = await contract_dao.view_player_votes_available(player_adr).call()\n LOGGER.info(f' dao: player {player_adr} has {ret.result.votes} votes')\n assert ret.result.votes == 7\n\n player_adr = users[1]['account'].contract_address\n ret = await contract_dao.view_player_votes_available(player_adr).call()\n LOGGER.info(f' dao: player {player_adr} has {ret.result.votes} votes')\n assert ret.result.votes == 25\n\n player_adr = users[2]['account'].contract_address\n ret = await contract_dao.view_player_votes_available(player_adr).call()\n LOGGER.info(f' dao: player {player_adr} has {ret.result.votes} votes')\n assert ret.result.votes == 7\n\n player_adr = users[3]['account'].contract_address\n ret = await contract_dao.view_player_votes_available(player_adr).call()\n LOGGER.info(f' dao: player {player_adr} has {ret.result.votes} votes')\n assert ret.result.votes == 0\n\n player_adr = users[4]['account'].contract_address\n ret = await contract_dao.view_player_votes_available(player_adr).call()\n LOGGER.info(f' dao: player {player_adr} has {ret.result.votes} votes')\n assert ret.result.votes == 0","repo_name":"topology-gg/isaac","sub_path":"core/tests/test_lobby_outdated.py","file_name":"test_lobby_outdated.py","file_ext":"py","file_size_in_byte":12186,"program_lang":"python","lang":"en","doc_type":"code","stars":86,"dataset":"github-code","pt":"46"} +{"seq_id":"10665512205","text":"import pandas as pd\nfrom lcs.metrics import population_metrics\n\n\ndef common_metrics(agent, env):\n metrics = {}\n\n pop = agent.get_population()\n agent_name = agent.__class__.__name__\n\n if hasattr(agent, 'rho'):\n metrics['rho'] = agent.rho\n agent_name += \"_v\" + agent.cfg.rho_update_version\n else:\n metrics['rho'] = 0\n\n metrics['agent'] = agent_name\n metrics['reliable'] = len([cl for cl in pop if cl.is_reliable()])\n\n metrics.update(population_metrics(pop, env))\n\n return metrics\n\n\ndef parse_metrics(metrics):\n # idx = [d['agent'] for d in metrics]\n\n data = [[\n d['agent'],\n d['trial'],\n d['steps_in_trial'],\n d['rho'],\n d['population'],\n d['reliable']] for d in metrics]\n\n df = pd.DataFrame(\n data,\n columns=['agent', 'trial', 'steps_in_trial', 'rho', 'population', 'reliable'],\n # index=idx\n )\n\n # It is used in alternating explore-exploit mode\n df['phase'] = df.trial.map(\n lambda t: \"explore\" if t % 2 == 0 else \"exploit\")\n\n return df\n","repo_name":"Sandalas98/fuzzy_pyalcs_experiments","sub_path":"notebooks/publications/2021_anticipatory-classifier-system-with-average-reward-criterion-in-discretized-multi-step-environments/utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"29522038292","text":"import pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport cv2\nemo_dict = {0: 'Surprise',\n 1: 'Fear',\n 2: 'Disgust',\n 3: 'Happy',\n 4: 'Sad',\n 5: 'Angry',\n 6: 'Neutral'}\nraf_path = r'D:\\datasets\\RafDB'\nbase_dataset = pd.read_csv(os.path.join(raf_path, 'list_patition_label.txt'),\n sep=' ', header=None,\n names=['img', 'label'])\nadd_align = lambda x: str(x).split('.')[0] + '_aligned.jpg'\nbase_dataset['img'] = base_dataset['img'].apply(add_align)\nbase_dataset['label'] = base_dataset['label'] - 1\ntrain = base_dataset[base_dataset['img'].str.startswith('train')]\nprint(f'Number of train images: {len(train)}')\ntest = base_dataset[base_dataset['img'].str.startswith('test')]\nprint(f'Number of test images: {len(test)}')\nemotions = list(emo_dict.values())\n\nlabels_train = train.groupby('label').count().to_dict()['img']\nemo_count = labels_train.values()\nplt.figure()\nplt.bar(emotions, emo_count)\nplt.title('Train dataset emotion distribution')\n\nlabels_test = test.groupby('label').count().to_dict()['img']\nemo_count = labels_test.values()\nplt.figure()\nplt.bar(emotions, emo_count)\nplt.title('Test dataset emotion distribution')\n\ndata = base_dataset.values.tolist()[:20]\nplt.figure()\nfor i, (img_name, target) in enumerate(data):\n img_path = os.path.join(raf_path, 'rafdb/aligned', img_name)\n img = cv2.imread(img_path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n plt.subplot(5, 4, i + 1), plt.imshow(img), plt.title(f'{emo_dict[target]}'),\n plt.axis('off')\nplt.show()\n\n\n","repo_name":"Zagreus98/emo_mix_match","sub_path":"dataset_stats.py","file_name":"dataset_stats.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"74753877900","text":"import os\nimport subprocess\nimport shutil\n\nimport logging\n\n\n# if using from tester.py uncoment that:\n# create logger that child of tester loger\nlogger = logging.getLogger('tests.tester.fiocr_main')\n\n# if using directly uncoment that:\n'''\n# create logger\nlog_level = logging.DEBUG # logging.DEBUG\nlogging.basicConfig(level=log_level)\nlogger = logging.getLogger('fiocr_main')\nlogger.setLevel(level=log_level)\n'''\n\n\nclass Fiocr():\n\n '''File Input Output Compilation Routine'''\n\n def create_out(self, out_path, userfuncs, rm=True):\n\n '''Create folder for out. Cleare if exist.\n Copy userfuncs.h here.\n\n INPUTS:\n\n - ``out_path`` -- path out be generated to\n\n :param str out_path: path out be generated to\n\n :param str userfuncs: path to userfuncs.h\n (default is ``hd/gens/hs/src``)\n '''\n\n folder = out_path\n if not os.path.exists(folder):\n os.makedirs(folder)\n else:\n if rm:\n shutil.rmtree(folder)\n os.makedirs(folder)\n\n # pathFrom = os.path.join('tests', 'src', 'libs', 'libuserfuncs.so')\n # shutil.copy2(pathFrom, folder)\n\n shutil.copy2(userfuncs, folder)\n\n def to_file(self, out, fileName, ext='.cpp', rm=True):\n\n '''fileName Used to create folder in\n ``tests/src`` folder and put output here\n\n (ex: out.cpp)'''\n\n with open(fileName, 'w') as f:\n f.write(out)\n\n def make_gcc_so(self, cpp_file, so_file, _stderr=None):\n '''\n DESCRIPTION::\n\n Generate ``libuserfuncs.so`` file by gcc.\n cpp and ``userfuncs.h`` files needed.\n '''\n logger.debug(\"FROM make_gcc_so\")\n # curDir = os.getcwd()\n\n # assuming that this file launched from hybriddomain\n '''\n folderName = fileName.split('.')[0]\n path = os.path.join(curDir, 'tests', 'src',\n 'generated', folderName)\n cpp = os.path.join(path, fileName)\n lib = os.path.join(path, 'libuserfuncs.so')\n '''\n\n # change bad path\n '''\n f = open(cpp)\n data = f.read()\n f.close()\n data = data.replace(\"prepr_folder_path/doc/userfuncs.h\", \"userfuncs.h\")\n f = open(cpp, 'w')\n f.write(data)\n f.close()\n '''\n\n # call gcc\n cmd = ['gcc', cpp_file, '-shared', '-O3', '-o',\n so_file, '-fPIC']\n logger.debug(\"cmd = %s\" % str(cmd))\n\n '''\n stdout and stderr PIPE means\n that new child stream will be created\n so standart output will be unused.\n See:\n https://docs.python.org/2.7/library/subprocess.html#frequently-used-arguments\n https://docs.python.org/2.7/library/subprocess.html#subprocess.Popen.communicate\n '''\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n out, err = p.communicate()\n\n # byte to str:\n out = out.decode(\"utf-8\")\n err = err.decode(\"utf-8\")\n\n if (err is not None and len(err) > 0):\n if _stderr is None:\n raise(GccException(err))\n else:\n return(err)\n\n if _stderr is not None:\n logger.info(\"out\")\n logger.info(out)\n logger.info(\"err\")\n logger.info(err)\n if err is None or len(err) == 0:\n return(True)\n\n\nclass GccException(Exception):\n '''\n DESCRIPTION::\n\n For cathing error of gcc.\n For tests cases in tester.py.\n '''\n def __init__(self, err):\n self.err = err\n logger.error(self.err)\n\n \n","repo_name":"dglyzin/tracer","sub_path":"gens/hs/fiocr/fiocr_main.py","file_name":"fiocr_main.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"8176317946","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 17 16:28:12 2020\n\n@author: batuhankuru\n\"\"\"\n\na=600851475143;\nx=2;\nliste=[];\nwhile(1):\n if(a%x==0):\n liste.append(x);\n a=a/x;\n print(liste);\n else:\n x=x+1;\n if(a==1):\n break\nprint(liste);\n","repo_name":"batuhankuru94/Euler-Project-Turkiye","sub_path":"PythonCode/euler3.py","file_name":"euler3.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"46"} +{"seq_id":"9519009993","text":"from bs4 import BeautifulSoup\nfrom scrape import simple_get\nfrom requests import post\nfrom adventcode_sessiondata import cookie\n\nraw_html = simple_get('https://adventofcode.com/2018/day/1/input', cookie)\nhtml = BeautifulSoup(raw_html, 'html.parser')\n\nstripped_html = html.text.split('\\n')\nnew_html = []\n\n# This actually achieves what I wanted buy by error. It strips the asci + from the strings,\n# but leaves the \"-\" when converting to int.\n\ntry:\n for item in stripped_html:\n new_html.append(int(item))\nexcept ValueError:\n print('valuerror')\n\ndict_count = {}\ncounter = 0\n\n\ndef count(num):\n global counter\n i = 0\n\n while i < num:\n\n for item in new_html:\n counter += item\n if counter in dict_count:\n print(\"Here!!!!\", counter)\n break\n else:\n dict_count[counter] = 1\n\n if counter in dict_count:\n break\n i += 1\n\n\ncount(500)\nprint(counter)\n","repo_name":"muffinsofgreg/adventcode2018","sub_path":"day1/day1_2.py","file_name":"day1_2.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"30241839258","text":"import threading\nimport socketserver\nfrom metodat import *\n### Teksti qe shfaqet ne startim te scriptes\nprint(\"\"\"\n:::::::::::::::::::::::::::::::::::::::'########:'####:'########:'##:::'##::::::::::::::::::::::::::::::::::::::::\n::::::::::::::::::::::::::::::::::::::: ##.....::. ##:: ##.....:: ##::'##:::::::::::::::::::::::::::::::::::::::::\n::::::::::::::::::::::::::::::::::::::: ##:::::::: ##:: ##::::::: ##:'##::::::::::::::::::::::::::::::::::::::::::\n::::::::::::::::::::::::::::::::::::::: ######:::: ##:: ######::: #####:::::::::::::::::::::::::::::::::::::::::::\n::::::::::::::::::::::::::::::::::::::: ##...::::: ##:: ##...:::: ##. ##::::::::::::::::::::::::::::::::::::::::::\n::::::::::::::::::::::::::::::::::::::: ##:::::::: ##:: ##::::::: ##:. ##:::::::::::::::::::::::::::::::::::::::::\n::::::::::::::::::::::::::::::::::::::: ##:::::::'####: ########: ##::. ##::::::::::::::::::::::::::::::::::::::::\n:::::::::::::::::::::::::::::::::::::::..::::::::....::........::..::::..:::::::::::::::::::::::::::::::::::::::::\n:::'##::::'##:'########::'########::::::::::::'######::'########:'########::'##::::'##:'########:'########::'####:\n::: ##:::: ##: ##.... ##: ##.... ##::::::::::'##... ##: ##.....:: ##.... ##: ##:::: ##: ##.....:: ##.... ##:. ##::\n::: ##:::: ##: ##:::: ##: ##:::: ##:::::::::: ##:::..:: ##::::::: ##:::: ##: ##:::: ##: ##::::::: ##:::: ##:: ##::\n::: ##:::: ##: ##:::: ##: ########::'#######:. ######:: ######::: ########:: ##:::: ##: ######::: ########::: ##::\n::: ##:::: ##: ##:::: ##: ##.....:::........::..... ##: ##...:::: ##.. ##:::. ##:: ##:: ##...:::: ##.. ##:::: ##::\n::: ##:::: ##: ##:::: ##: ##:::::::::::::::::'##::: ##: ##::::::: ##::. ##:::. ## ##::: ##::::::: ##::. ##::: ##::\n:::. #######:: ########:: ##:::::::::::::::::. ######:: ########: ##:::. ##:::. ###:::: ########: ##:::. ##:'####:\n::::.......:::........:::..:::::::::::::::::::......:::........::..:::::..:::::...:::::........::..:::::..::....::\n\"\"\")\n\n\nclass ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):\n\n def handle(self):\n data = self.request[0].strip().decode().upper()\n data = data.split(\" \",1)\n\t\t###Ruajme portin e klientit ne variablen port\n port = self.client_address[1]\n\t\t### Ruajme socketin e nevojshem per komunikim ne variablen socket\n socket = self.request[1]\n\t\t### Ruajme adresen e klientit ne variablen client_address\n client_address = (self.client_address[0])\n print(\"Eshte kyqur klienti: %s:%s\" %(client_address, port))\n welcome = \"\"\"Zgjedhni njerin nga Operacionet \n (IPADRESA, NUMRIIPORTIT, BASHKETINGELLORE, \n PRINTIMI, EMRIIKOMPJUTERIT, KOHA, LOJA,\n FIBONACCI, KONVERTIMI)? \"\"\" \n socket.sendto(welcome.encode(), self.client_address)\n # data = self.request[0].strip().decode().upper()\n data = socket.recvfrom(1024)[0].decode() \n data = data.split(\" \",1)\n data[0] = data[0].upper()\n print(data[0])\n ### Testojme kerkesen\n if len(data) == 1:\n print(\"Klienti %s:%s kerkoi: %s\" %(client_address, port, data[0]))\n else: \n print(\"Klienti %s:%s kerkoi: %s %s\" %(client_address, port, data[0], data[1]))\n\t\t\n if data[0] == \"IPADRESA\":\n MESSAGE = IPADRESA(client_address)\n\n elif data[0] == \"NUMRIIPORTIT\":\n MESSAGE = NUMRIIPORTIT(port)\n\n elif data[0] == \"BASHKETINGELLORE\": \n if len(data) == 1:\n MESSAGE = \"Ju duhet te shtypni Bashketingellore {hapsire} teskti.\"\n else: \n MESSAGE = BASHKETINGELLORE(data[1])\n \n elif data[0] == \"PRINTIMI\":\n if len(data) != 2:\n MESSAGE = \"Ju duhet te shtypni Printimi {hapsire} teskti.\"\n else: \n MESSAGE = PRINTIMI(data[1])\n\n elif data[0] == \"EMRIIKOMPJUTERIT\":\n MESSAGE = EMRIKOMPJUTERIT(socket) \n\n elif data[0] == \"KOHA\":\n MESSAGE = KOHA() \n\n elif data[0] == \"LOJA\":\n MESSAGE = LOJA() \n \n elif data[0] == \"KONTROLLOPORTIN\":\n host_port = data[1].split(\" \",1)\n if len(host_port) != 2:\n MESSAGE = \"Ju duhet te shtypni kontrollohostin {hapsire} hosti {hapsire} porti.\"\n else: \n MESSAGE = KONTROLLOPORTIN(host_port[0], host_port[1])\n \n elif data[0] == \"PASSWORDGEN\":\n MESSAGE = PASSWORDGEN()\n\n elif data[0] == \"FIBONACCI\":\n if len(data) != 2:\n MESSAGE = \"Ju duhet te shtypni Fibonacci {hapsire} numer.\"\n else: \n if not data[1].isdigit(): \n MESSAGE = \"Ju duhet te shtypni Fibonacci {hapsire} numer.\"\n else:\n MESSAGE = str(Fibonacci(int(data[1]))) \n \n elif data[0] == \"KONVERTIMI\":\n if len(data) != 2:\n MESSAGE = \"Ju duhet te shtypni Konvertimi {hapsire} opcioni {hapsire} sasia.\" \n else: \n opcioni = data[1].split(\" \",1)\n if len(opcioni) != 2:\n MESSAGE = \"Ju duhet te shtypni Konvertimi {hapsire} opcioni {hapsire} sasia.\"\n else:\n if not opcioni[1].isdigit():\n MESSAGE = \"Ju duhet te shtypni Konvertimi {hapsire} opcioni {hapsire} sasia.\" \n else: \n MESSAGE = KONVERTIMI(opcioni[0].upper(), float(opcioni[1]))\n elif data[0] == 'EXIT' or data[0] == 'ProcessTerminatedByUser'.upper():\n MESSAGE = 'Klienti nderpreu lidhjen\\n'\n \n else: \n try:\n MESSAGE = \"Ju nuk keni zgjedhur asnje nga opcionet e mesiperme.\"\n ### Kontrolli per gabime \n except socket.error:\n print(\"Lidhja u ndepre\")\n \n \n \n socket.sendto(MESSAGE.encode(), self.client_address) \nclass ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):\n pass\n\n### Fillimi i scriptes\nif __name__ == \"__main__\":\n host, port = \"localhost\", 12000\n try:\n ### Krijojm serverin me ane te Klases ThreadUDPServer ne portin 12000 \n server = ThreadedUDPServer((host, port), ThreadedUDPRequestHandler) \n ip, port = server.server_address\n print(\"Startoi serveri ne %s:%s.\" %(ip, port))\n print(\"Ne pritje te kerkesave.\")\n ### Presim klientet\n server.serve_forever()\n ### Krijojme nje thread per cdo klient qe lidhet me serverin.\n ### Me pas ai thread krijon nga nje thread per cdo kerkese qe behet\n server_thread = threading.Thread(target=server.serve_forever)\n ### Fillon threadin\n server_thread.daemon = True\n server_thread.start()\n ### Mbyll te gjite thread-at ne lidhje me klientin ne momentin qe klienti shkeputet\n server.shutdown()\n ### Kontrolli per gabime\n except KeyboardInterrupt:\n print(\"\\nJu e ndalet serverin\") \n except OSError:\n print(\"Porti eshte i nxene\") ","repo_name":"JetmirAv/Socket-Programming-With-Python","sub_path":"UDPv2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":7183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"3680539782","text":"import random\nimport math\nimport scipy.stats as ss\n\n\ndef random_select(belief):\n \"\"\"Select objects randomly.\"\"\"\n return random.randint(0, len(belief) - 1)\n\n\ndef strategy_entropy(belief):\n \"\"\"Select the object with the highest entropy.\"\"\"\n # select max entropy door\n max_ent = -999999\n for i, door in enumerate(belief):\n ent = door.entropy()\n if ent > max_ent:\n max_ent = ent\n idx = i\n return idx\n\n\ndef strategy_expected_change_of_entropy(belief):\n \"\"\"Select the object with the highest expected change of entropy.\"\"\"\n max_diff = -999999\n for i, bel in enumerate(belief):\n H = bel.entropy()\n # prob for outcome a\n P_a = bel.mean()\n # entropy for outcome a\n H_a = ss.beta.entropy(bel.opened + 1, bel.closed)\n # prob for outcome b\n P_b = 1 - P_a\n # entropy for outcome b\n H_b = ss.beta.entropy(bel.opened, bel.closed + 1)\n # new estimated entropy\n H_est = (P_a * H_a + P_b * H_b)\n # change of H\n diff = H - H_est\n\n if False:\n print(\"=================================\")\n print(\"H: \", H)\n print(\"P_a: \", P_a)\n print(\"H_a: \", H_a)\n print(\"P_b: \", P_b)\n print(\"H_b: \", H_b)\n print(\"H_est:\", H_est)\n print(\"diff: \", diff)\n\n if diff > max_diff:\n max_diff = diff\n idx = i\n return idx\n\n\nclass strategy_sequential(object):\n def __init__(self):\n self.last_selection = -1\n\n def __call__(self, belief):\n self.last_selection = (self.last_selection + 1) % len(belief)\n return self.last_selection\n\n\nclass StrategyUCB(object):\n \"\"\"Upper Confident Bound strategy.\n\n See Marc's lecture on \"Bandits, Global Optimization, AL and Bayesian RL\"\n\n \"\"\"\n def __init__(self, not_pushed_yet):\n self.not_pushed_yet = not_pushed_yet\n\n def __call__(self, belief):\n # we push every object once to estimate the reward\n if self.not_pushed_yet:\n choice = random.choice(self.not_pushed_yet)\n self.not_pushed_yet -= choice\n return choice\n\n # push the \"best\" door\n else:\n # play machine i that maximizes: rewarad_i + srqt(2 * ln n / n_i)\n # reward = average reward of machine i\n\n # n = number of total rounds\n n = sum(bel.opened + bel.closed - 2 for bel in belief)\n ucb_score = []\n for bel in belief:\n # we could use the expected change of entropy here\n reward = bel.entropy()\n # n_i = how often did we push door i\n n_i = bel.opened + bel.closed - 2\n score = reward + math.sqrt(2 * math.log(n) / n_i)\n ucb_score.append(score)\n print(ucb_score)\n max(ucb_score)\n","repo_name":"cambyse/PO-LGP","sub_path":"share/projects/exploration_comparison/strategies.py","file_name":"strategies.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"9385817416","text":"A = [222,34,45,45,78,67,1,43,54,656]\nprint(A)\nfor current in range(0, len(A)):\n #print(current)\n minIndex = current\n for i in range(current + 1, len(A)):\n print(A[i], A[minIndex])\n if A[i] < A[minIndex]:\n minIndex = i\n temp = A[current]\n A[current] = A[minIndex]\n A[minIndex] = temp\n print(A)\n print()\n","repo_name":"a2zlondon/selection-sort","sub_path":"simple-example.py","file_name":"simple-example.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"22701279612","text":"import CSVTable\nimport CSVCatalog\nimport json\nimport csv\nimport time\n\n#Must clear out all tables in CSV Catalog schema before using if there are any present\n#Please change the path name to be whatever the path to the CSV files are\n#First methods set up metadata!! Very important that all of these be run properly\n\n# Only need to run these if you made the tables already in your CSV Catalog tests\n# You will not need to include the output in your submission as executing this is not required\n# Implementation is provided\ndef drop_tables_for_prep():\n cat = CSVCatalog.CSVCatalog()\n cat.drop_table(\"people\")\n cat.drop_table(\"batting\")\n cat.drop_table(\"appearances\")\n\n#drop_tables_for_prep()\n\n# Implementation is provided\n# You will need to update these with the correct path\ndef create_lahman_tables():\n people_columns = [\"playerID\", \"birthYear\", \"birthMonth\", \"birthDay\", \"birthCountry\", \"birthState\", \"birthCity\",\n \t\"deathYear\", \"deathMonth\", \"deathDay\", \"deathCountry\", \"deathState\", \"deathCity\", \"nameFirst\",\n \"nameLast\", \"nameGiven\", \"weight\", \"height\", \"bats\", \"throws\", \"debut\", \"finalGame\", \"retroID\", \"bbrefID\"]\n batting_columns = [\"playerID\", \"yearID\", \"stint\", \"teamID\", \"lgID\", \"G\", \"AB\", \"R\", \"H\", \"2B\", \"3B\", \"HR\", \"RBI\",\n \"SB\", \"CS\", \"BB\", \"SO\", \"IBB\", \"HBP\", \"SH\", \"SF\", \"GIDP\"]\n appearances_columns = [\"yearID\", \"teamID\", \"lgID\", \"playerID\", \"G_all\", \"GS\", \"G_batting\", \"G_defense\", \"G_p\", \"G_c\", \n \"G_1b\", \"G_2b\", \"G_3b\", \"G_ss\", \"G_lf\", \"G_cf\", \"G_rf\", \"G_of\", \"G_dh\", \"G_ph\", \"G_pr\"]\n cat = CSVCatalog.CSVCatalog()\n cat.create_table(\"people\", \"NewPeople.csv\", people_columns)\n cat.create_table(\"batting\",\"NewBatting.csv\", batting_columns)\n cat.create_table(\"appearances\", \"NewAppearances.csv\", appearances_columns)\n\n#create_lahman_tables()\n\n# Note: You can default all column types to text\ndef update_people_columns():\n # ************************ TO DO ***************************\n table = CSVTable.CSVTable(\"people\")\n print('All columns loaded into table')\n\n#update_people_columns()\n\ndef update_appearances_columns():\n # ************************ TO DO ***************************\n table = CSVTable.CSVTable(\"appearances\")\n print('All columns loaded into table')\n\n#update_appearances_columns()\n\ndef update_batting_columns():\n # ************************ TO DO ***************************\n table = CSVTable.CSVTable(\"batting\")\n print('All columns loaded into table')\n\n#update_batting_columns()\n\n#Add primary key indexes for people, batting, and appearances in this test\ndef add_index_definitions():\n # ************************ TO DO ***************************\n table1 = CSVTable.CSVTable(\"people\")\n table1.__description__.define_index(\"playerID\", [\"playerID\"], \"PRIMARY\")\n table1.__load__()\n print()\n\n table2 = CSVTable.CSVTable(\"batting\")\n table2.__description__.define_index(\"playerID_yearID_teamID\", [\"playerID\", \"yearID\", \"teamID\"], \"PRIMARY\")\n table2.__load__()\n print()\n\n table3 = CSVTable.CSVTable(\"appearances\")\n table3.__description__.define_index(\"yearID_teamID_playerID\", [\"yearID\", \"teamID\", \"playerID\"], \"PRIMARY\")\n table3.__load__()\n\n#add_index_definitions()\n\n\ndef test_load_info():\n table = CSVTable.CSVTable(\"people\")\n print(table.__description__.file_name)\n\n#test_load_info()\n\ndef test_get_col_names():\n table = CSVTable.CSVTable(\"people\")\n names = table.__get_column_names__()\n print(names)\n\n#test_get_col_names()\n\ndef add_other_indexes():\n \"\"\"\n We want to add indexes for common user stories\n People: nameLast, nameFirst\n Batting: teamID\n Appearances: None that are too important right now\n :return:\n \"\"\"\n # ************************ TO DO ***************************\n table1 = CSVTable.CSVTable(\"people\")\n table1.__description__.define_index(\"nameLast_nameFirst\", [\"nameLast\", \"nameFirst\"], \"INDEX\")\n table1.__load__()\n print()\n\n # Ed #570 Use another column\n table2 = CSVTable.CSVTable(\"batting\")\n table2.__description__.define_index(\"G\", [\"G\"], \"INDEX\")\n table2.__load__()\n\n#add_other_indexes()\n\ndef load_test():\n batting_table = CSVTable.CSVTable(\"batting\")\n print(batting_table)\n\n#load_test()\n\n\ndef dumb_join_test():\n batting_table = CSVTable.CSVTable(\"batting\")\n appearances_table = CSVTable.CSVTable(\"appearances\")\n t1 = time.time()\n result = batting_table.dumb_join(appearances_table, [\"playerID\", \"yearID\"], {\"playerID\": \"baxtemi01\"},\n [\"playerID\", \"yearID\", \"teamID\", \"AB\", \"H\", \"G_all\", \"G_batting\"])\n t2 = time.time()\n print(result)\n print('Time spent for dumb_join: %fs.'%(t2 - t1))\n\n\n#dumb_join_test()\n\n\ndef get_access_path_test():\n people_table = CSVTable.CSVTable(\"people\")\n template = [\"teamID\", \"playerID\", \"yearID\"]\n index_result, count = people_table.__get_access_path__(template)\n print(index_result)\n print(count)\n\n#get_access_path_test()\n\ndef sub_where_template_test():\n # ************************ TO DO ***************************\n batting_table = CSVTable.CSVTable(\"batting\")\n where_template = {\"teamID\":\"CHN\", \"playerID\":\"aardsda01\", \"food\":\"chips\"}\n sub_template = batting_table.__get_sub_where_template__(where_template)\n print(\"sub_template is\", sub_template)\n print()\n\n people_table = CSVTable.CSVTable(\"people\")\n where_template = {\"birthCity\":\"Denver\", \"food\":\"chips\"}\n sub_template = people_table.__get_sub_where_template__(where_template)\n print(\"sub_template is\", sub_template)\n\n#sub_where_template_test()\n\n\ndef test_find_by_template_index():\n # ************************ TO DO ***************************\n batting_table = CSVTable.CSVTable(\"batting\")\n template = {\"teamID\":\"CHN\", \"playerID\":\"aardsda01\"}\n result_rows = batting_table.__find_by_template__(template, fields=[\"playerID\", \"teamID\", \"lgID\"])\n print(\"result rows are\", result_rows)\n print()\n\n appearances_table = CSVTable.CSVTable(\"appearances\")\n template = {\"teamID\":\"CHN\", \"G_all\":\"45\"}\n result_rows = appearances_table.__find_by_template__(template, fields=[\"teamID\", \"playerID\", \"G_all\"])\n print(\"result rows are\", result_rows)\n\n\n#test_find_by_template_index()\n\ndef smart_join_test():\n # ************************ TO DO ***************************\n batting_table = CSVTable.CSVTable(\"batting\")\n appearances_table = CSVTable.CSVTable(\"appearances\")\n t1 = time.time()\n result = batting_table.__smart_join__(appearances_table, [\"playerID\", \"yearID\"], {\"playerID\": \"baxtemi01\"},\n [\"playerID\", \"yearID\", \"teamID\", \"AB\", \"H\", \"G_all\", \"G_batting\"])\n t2 = time.time()\n print(result)\n print('Time spent for smart_join: %fs.'%(t2 - t1))\n\n#smart_join_test()\n","repo_name":"yaoReadingCode/Database_2021_fall_HW2","sub_path":"unit_test_csv_table.py","file_name":"unit_test_csv_table.py","file_ext":"py","file_size_in_byte":6816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"32756152597","text":"\"\"\"Deployment tests for ipmi driver.\n\nThese require an actual HIL setup with a real node, and are\nsomewhat particular to the MOC's development environment. They may be\ndifficult to run in other contexts.\n\"\"\"\n\nfrom hil.test_common import config_testsuite, fresh_database, \\\n fail_on_log_warnings, with_request_context, site_layout, server_init\nfrom hil.model import Node\nfrom hil import config, api\nimport pytest\n\n\n@pytest.fixture\ndef configure():\n \"\"\"Configure HIL\"\"\"\n config_testsuite()\n config.load_extensions()\n\n\nfail_on_log_warnings = pytest.fixture(autouse=True)(fail_on_log_warnings)\nfresh_database = pytest.fixture(fresh_database)\nserver_init = pytest.fixture(server_init)\n\n\nwith_request_context = pytest.yield_fixture(with_request_context)\nsite_layout = pytest.fixture(site_layout)\n\npytestmark = pytest.mark.usefixtures('configure',\n 'server_init',\n 'fresh_database',\n 'with_request_context',\n 'site_layout')\n\n\nclass TestIpmi():\n \"\"\" Test IPMI driver calls using functions included in the IPMI driver. \"\"\"\n\n def collect_nodes(self):\n \"\"\"Collects nodes in the free list.\"\"\"\n free_nodes = Node.query.filter_by(project_id=None).all()\n return free_nodes\n\n def test_node_power_cycle(self):\n \"\"\"Test power cycling nodes.\"\"\"\n nodes = self.collect_nodes()\n for node in nodes:\n api.node_power_cycle(node.label)\n\n def test_node_power_force(self):\n \"\"\"Test power cycling nodes, with force=True.\"\"\"\n nodes = self.collect_nodes()\n for node in nodes:\n api.node_power_cycle(node.label, True)\n\n def test_node_power_off(self):\n \"\"\"Test shutting down nodes properly\"\"\"\n nodes = self.collect_nodes()\n for node in nodes:\n api.node_power_off(node.label)\n\n def test_node_set_bootdev(self):\n \"\"\"Test setting the boot device.\"\"\"\n nodes = self.collect_nodes()\n for node in nodes:\n # change a node's bootdevice to a valid boot device\n api.node_set_bootdev(node.label, 'pxe')\n api.node_set_bootdev(node.label, 'disk')\n api.node_set_bootdev(node.label, 'none')\n # set the bootdevice to something invalid\n with pytest.raises(api.BadArgumentError):\n api.node_set_bootdev(node.label, 'invalid-device')\n\n # register a node with erroneous ipmi details to raise OBMError\n # XXX: In theory, this could actually be a real node; we should take\n # some measure to ensure this never collides with something actually\n # in our test setup.\n api.node_register('node-99-z4qa63', obm={\n \"type\": \"http://schema.massopencloud.org/haas/v0/obm/ipmi\",\n \"host\": \"ipmihost\",\n \"user\": \"root\",\n \"password\": \"tapeworm\"})\n with pytest.raises(api.OBMError):\n api.node_set_bootdev('node-99-z4qa63', 'none')\n","repo_name":"markcxli/Auditing_service_for_HIL","sub_path":"hilOVS/tests/deployment/ipmi.py","file_name":"ipmi.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"} +{"seq_id":"27273800791","text":"from django.shortcuts import render\nfrom .models import *\nimport time\n\n\n# Create your views here.\ndef submit_account(request):\n obj = Account()\n obj.first_name = request.GET['Имя']\n obj.second_name = request.GET['Фамилия']\n obj.position = request.GET['Должность']\n obj.date = time.strftime('%d.%m.%Y %X')\n obj.title = request.GET['Заголовок публикации']\n obj.content = request.GET['Публикация']\n obj.save()\n return render(request, 'Main/main_page.html')\n","repo_name":"Mirrexi/Practice","sub_path":"MEDAN/account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"31466163096","text":"#!/usr/bin/env python3\n\n#import the dependencies\n \nimport rospy\nfrom geometry_msgs.msg import Twist, PoseWithCovarianceStamped\nfrom apriltag_ros.msg import AprilTagDetection, AprilTagDetectionArray\nimport numpy as np\nimport tf2_ros\nimport tf.transformations \nimport tf2_geometry_msgs\nimport transformation_utilities as tu\n\n\nclass PID:\n\tdef __init__(self, Kp=0, Ki=0, Kd=0):\n\t\t'''\n\t\t'''\n\t\tself.Kp = Kp\n\t\tself.Ki = Ki\n\t\tself.Kd = Kd\n\n\tdef proportional_control(self, error):\n\t\treturn self.Kp * error\n\n\tdef integral_control(self, error, dt):\n\t\treturn self.Ki * error * dt\n\n\tdef derivative_control(self, error, previous_error, dt):\n\t\treturn self.Kd * (error - previous_error)/dt\n\n\n\nclass Jackal:\n\tdef __init__(self):\n\t\tself.pub=rospy.Publisher('/cmd_vel',Twist,queue_size=1)\n\t\tself.sub_img_detec = rospy.Subscriber(\"/tag_detections\", AprilTagDetectionArray, self.detection_callback)\n\t\t\t\n\t\tself.spin = True\n\t\tself.move = False\n\t\tself.vel = Twist()\n\t\tself.prev_error = 0\n\t\tself.tfBuffer = tf2_ros.Buffer()\n\t\tself.listener = tf2_ros.TransformListener(self.tfBuffer)\n\t\tself.saved_time = rospy.Time.now()\n\t\tself.detected = False\n\t\tself.dist_to_tag = 0\n\t\tself.ap_in_baselink = None\n\n\t\t# pid parameters\n\t\tkp = rospy.get_param(\"/gain/kp\")\n\t\tki = rospy.get_param(\"/gain/ki\")\n\t\tkd = rospy.get_param(\"/gain/kp\")\n\t\tself.controller = PID(kp,kd,ki)\n\t\t# source_frame = \"front_realsense_gazebo\"\n\t\t# \t# print(msg)\n\t\t# transform = self.tfBuffer.lookup_transform(\"base_link\", source_frame, rospy.Time(0), rospy.Duration(1.0))\n\t\t# self.transform_matrix = tu.msg_to_se3(transform)\n\t\t\n\tdef update_status(self):\n\t\t# print(\"dist_to_tag\", self.dist_to_tag)\n\t\tif not self.detected :\n\t\t\tself.move = False\n\t\t\tself.spin = True \n\t\telif self.detected and self.dist_to_tag < 1.5: # limit set baseed on trials\n\t\t\tself.move = False\n\t\t\tself.spin = True\n\t\telse:\n\t\t\tself.spin = False\n\t\t\tself.move = True\n\t\t\t\n\n\tdef on_apriltag_detection(self):\n\t\tif self.ap_in_baselink[0,3] is not None and self.ap_in_baselink[1,3] is not None and self.ap_in_baselink[2,3] is not None:\n\t\t\tself.dist_to_tag = self.get_dist() \n\n\tdef detection_callback(self,msg):\n\t\tif msg.detections:\n\t\t\ttransform_gazebo_to_cam = self.tfBuffer.lookup_transform(\"front_realsense\", \"front_realsense_gazebo\", rospy.Time(0), rospy.Duration(1.0))\n\t\t\t# print('gatofro',tu.msg_to_se3(transform_gazebo_to_cam))\n\t\t\t# transform_cam_to_bl = self.tfBuffer.lookup_transform(\"base_link\",\"front_realsense\", rospy.Time(0), rospy.Duration(1.0))\n\t\t\ttransform_cam_to_bl = np.array([[1,0,0,-0.035],[0,1,0,0],[0,0,1,0.414],[0,0,0,1]])\n\t\t\t# print('frtobl',tu.msg_to_se3(transform_cam_to_bl))\n\t\t\tself.ap_in_baselink = np.dot(transform_cam_to_bl,tu.msg_to_se3(transform_gazebo_to_cam))\n\t\t\t# np.array([[0, 0, 1, -0.035],[-1,0,0,0],[0, -1, 0, 0.414],[ 0,0,0,1]]) \n\t\t\t# print('tra',self.ap_in_baselink)\n\t\t\tself.ap_in_baselink = np.dot(self.ap_in_baselink, tu.msg_to_se3(msg.detections[0].pose.pose.pose))\n\t\t\t# print('2',self.ap_in_baselink)\n\t\t\tself.detected = True\n\t\t\tself.on_apriltag_detection()\n\t\telse:\n\t\t\tself.ap_in_baselink = None\n\t\t\tself.detected = False\n\n\tdef spinning(self):\n\t\t# adjust the velocity message\n\t\tself.vel.angular.z = 0.5\n\t\tself.vel.linear.x = 0\n\t\t#publish it\n\t\tself.pub.publish(self.vel)\n\n\tdef velocity_control(self, error, dt, prev_error):\n\t\tmax_vel = 4\n\t\tmv_p = self.controller.proportional_control(error)\n\t\tmv_i = self.controller.integral_control(error, dt)\n\t\tmv_d = self.controller.derivative_control(error, prev_error, dt)\n\t\n\t\tdesired_vel = np.clip( mv_p + mv_i + mv_d, -max_vel, max_vel)\n\t\treturn desired_vel\n\t\n\t\t\t\t\n\tdef get_dist(self):\n\t\tdist = np.linalg.norm([self.ap_in_baselink[0,3], self.ap_in_baselink[1,3],self.ap_in_baselink[2,3]])\n\t\t# dist2 = np.linalg.norm([self.ap_in_baselink[0,3], self.ap_in_baselink[1,3]])\n\t\tprint('dist',dist)\n\t\treturn dist\n\n\tdef move_towards_tag(self):\n\t\tcurrent_error = self.ap_in_baselink[1,3]\n\t\tprint(\"current_error\",current_error)\n\t\tif current_error is not None:\n\t\t\tself.vel.linear.x = 1\n\t\t\tcurrent_time = rospy.Time.now()\n\t\t\tdt = (current_time - self.saved_time).to_sec()\n\t\t\tpid_output = self.velocity_control(current_error, dt, self.prev_error)\n\t\t\t# print(\"pid_output \", pid_output)\n\t\t\tself.vel.angular.z = pid_output \n\t\t\tself.saved_time = current_time\n\n\t\t\tself.pub.publish(self.vel)\n\t\t\tself.prev_error = current_error\n\n\nif __name__==\"__main__\":\n \n\t#initialise the node\n\trospy.init_node(\"ap_tag\", anonymous=True)\n\tjack = Jackal()\n\t#while the node is still on\n\tr = rospy.Rate(10)\n\twhile not rospy.is_shutdown():\n\t\tjack.update_status()\n\t\tif jack.spin:\n\t\t\tjack.spinning()\n\t\telif jack.move:\n\t\t\tjack.move_towards_tag()\n\t\tr.sleep()\n\n\t\n\n\t","repo_name":"johnbaillieul/ROS-Jackal","sub_path":"robots/jackal/pid_apriltag/nodes/detec.py","file_name":"detec.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"2307703656","text":"import json\nimport os\nimport sys\nos.chdir(sys.path[0])\n\ndef get_source_code_v8():\n root_dir = \"..\\\\..\\\\contracts\\\\v0.8.x\\\\erc721\"\n sub_dirs = os.listdir(root_dir)\n for sub_dir in sub_dirs:\n files = os.listdir(os.path.join(root_dir, sub_dir))\n for file in files:\n file_path = os.path.join(root_dir, sub_dir, file)\n save_path = os.path.join(root_dir, sub_dir, file[:-5])\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n with open(file_path, encoding='utf-8') as fp:\n content = json.loads(fp.read())\n contracts = content['sources']\n for contr in contracts:\n print(contr)\n content = contracts[contr]['content']\n print(content)\n name = contr.split('/')[-1]\n save_file = os.path.join(save_path, name)\n # code_path = os.path.join(root_save_dir, sub_dir, path, name)\n with open(save_file, 'w', encoding='utf-8') as fd:\n fd.write(content)\n\ndef main():\n get_source_code_v8()\n\nif __name__ == \"__main__\":\n main()\n\n ","repo_name":"shiningdai/eth-contracts-analysis","sub_path":"analysis/scripts-win/parse_sourcecode_v8_3.py","file_name":"parse_sourcecode_v8_3.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"46"} +{"seq_id":"28401047979","text":"from model.old import common\n\nimport torch.nn as nn\nfrom model.merge_net import MergeNet\nimport math\nfrom model.GReccR2b_random_adp_thd3 import RR\n# from model.GReccR2b import RR\ndef weights_init_kaiming(m):\n classname = m.__class__.__name__\n # if classname.find('Conv') != -1:\n # nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n # elif classname.find('Linear') != -1:\n # nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n # elif classname.find('BatchNorm') != -1:\n # # nn.init.uniform(m.weight.data, 1.0, 0.02)\n # m.weight.data.normal_(mean=0, std=math.sqrt(2./9./64.)).clamp_(-0.025,0.025)\n # nn.init.constant_(m.bias.data, 0.0)\n\n if type(m) == nn.Conv2d:\n nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif type(m) == nn.Linear:\n nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif type(m) == nn.BatchNorm2d or type(m) == nn.BatchNorm1d:\n # nn.init.uniform(m.weight.data, 1.0, 0.02)\n m.weight.data.normal_(mean=0, std=math.sqrt(2./9./64.)).clamp_(-0.025,0.025)\n nn.init.constant_(m.bias.data, 0.0)\ndef make_model(args, parent=False):\n # net = MergeNet(in_channels=1,intermediate_channels=64,vector_length=32,use_multiple_size=True,dncnn_depth=6,num_merge_block=4,use_topk=False)\n # net.apply(weights_init_kaiming)\n return RR(args)#RNAN(args)#RR(args)#RNAN(args)#RR(args)\n\n\n\n### RNAN\n### residual attention + downscale upscale + denoising\nclass _ResGroup(nn.Module):\n def __init__(self, conv, n_feats, kernel_size, act, res_scale):\n super(_ResGroup, self).__init__()\n modules_body = []\n modules_body.append(common.ResAttModuleDownUpPlus(conv, n_feats, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1))\n modules_body.append(conv(n_feats, n_feats, kernel_size))\n self.body = nn.Sequential(*modules_body)\n\n def forward(self, x):\n res = self.body(x)\n\n return res\n\n### nonlocal residual attention + downscale upscale + denoising\nclass _NLResGroup(nn.Module):\n def __init__(self, conv, n_feats, kernel_size, act, res_scale):\n super(_NLResGroup, self).__init__()\n modules_body = []\n\n modules_body.append(common.NLResAttModuleDownUpPlus(conv, n_feats, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1))\n # if we don't use group residual, donot remove the following conv\n modules_body.append(conv(n_feats, n_feats, kernel_size))\n self.body = nn.Sequential(*modules_body)\n\n def forward(self, x):\n res = self.body(x)\n #res += x\n return res\n\nclass RNAN(nn.Module):\n def __init__(self, args, conv=common.default_conv):\n super(RNAN, self).__init__()\n \n n_resgroup = args.n_resgroups\n n_resblock = args.n_resblocks\n n_feats = args.n_feats\n kernel_size = 3\n reduction = args.reduction \n scale = args.scale[0]\n act = nn.ReLU(True)\n \n\n # define head module\n modules_head = [conv(args.n_colors, n_feats, kernel_size)]\n\n # define body module\n\n modules_body_nl_low = [\n _NLResGroup(\n conv, n_feats, kernel_size, act=act, res_scale=args.res_scale)]\n modules_body = [\n _ResGroup(\n conv, n_feats, kernel_size, act=act, res_scale=args.res_scale) \\\n for _ in range(n_resgroup - 2)]\n modules_body_nl_high = [\n _NLResGroup(\n conv, n_feats, kernel_size, act=act, res_scale=args.res_scale)]\n modules_body.append(conv(n_feats, n_feats, kernel_size))\n\n # define tail module\n modules_tail = [\n conv(n_feats, args.n_colors, kernel_size)]\n\n self.head = nn.Sequential(*modules_head)\n self.body_nl_low = nn.Sequential(*modules_body_nl_low)\n self.body = nn.Sequential(*modules_body)\n self.body_nl_high = nn.Sequential(*modules_body_nl_high)\n self.tail = nn.Sequential(*modules_tail)\n\n def forward(self, x):\n\n feats_shallow = self.head(x)\n\n res = self.body_nl_low(feats_shallow)\n res = self.body(res)\n res = self.body_nl_high(res)\n\n\n res_main = self.tail(res)\n\n res_clean = x + res_main\n\n\n return res_clean \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","repo_name":"jianzhangcs/DAGL","sub_path":"Demosaic/model/.ipynb_checkpoints/rnan-checkpoint.py","file_name":"rnan-checkpoint.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","stars":90,"dataset":"github-code","pt":"46"} +{"seq_id":"1824547531","text":"import base64\nimport json\nimport os\nimport shutil\n\nfrom ghapi.all import GhApi, paged\n\nfrom config import Config\n\n\ndef fetch(root):\n config = Config(root)\n dat = fetch_all(config)\n write_data(dat, os.path.join(root, \"data\"))\n\n\ndef write_data(dat, dest):\n if os.path.exists(dest):\n shutil.rmtree(dest)\n os.makedirs(dest)\n for k in dat.keys():\n d = dat[k]\n p = os.path.join(dest, k)\n os.makedirs(p, exist_ok = True)\n for name, content in d[\"metadata\"].items():\n with open(os.path.join(p, name), \"w\") as f:\n f.write(content)\n metadata = {x: d[x] for x in d if x != \"metadata\"}\n with open(os.path.join(p, \"metadata.json\"), \"w\") as f:\n f.write(json.dumps(metadata))\n\n\ndef fetch_all(config):\n api = GhApi(token=os.environ[\"GITHUB_TOKEN\"])\n dat = []\n for org_name in config.orgs:\n print(f\"Fetching {org_name}\")\n dat += fetch_org(api, org_name, config)\n print(f\"Fetching extras\")\n for name in config.extra:\n dat.append(fetch_single(api, name, config))\n return {x[\"full_name\"]: x for x in dat}\n\n\ndef fetch_org(api, org_name, config):\n ret = []\n pages = paged(api.repos.list_for_org, per_page=100, org=org_name)\n for page in pages:\n for repo_data in page:\n try:\n dat = fetch_repo(api, org_name, repo_data, config)\n if dat:\n ret.append(dat)\n except Exception as e:\n print(f\"ERROR on {org_name}/{repo_data.name}: {str(e)}\")\n return ret\n\n\ndef fetch_single(api, name, config):\n org_name, repo_name = name.split(\"/\")\n repo_data = api.repos.get(org_name, repo_name)\n return fetch_repo(api, org_name, repo_data, config)\n\n\ndef fetch_repo(api, org_name, repo_data, config):\n repo_name = repo_data.name\n full_name = f\"{org_name}/{repo_name}\"\n if full_name in config.exclude:\n return\n if repo_data[\"archived\"] or repo_data[\"fork\"] or repo_data[\"private\"]:\n return\n print(f\" - {full_name}\")\n\n copy = [\"created_at\", \"updated_at\", \"pushed_at\",\n \"stargazers_count\", \"homepage\",\n \"language\", \"description\"]\n ret = {nm: repo_data[nm] for nm in copy}\n ret[\"org\"] = org_name\n ret[\"repo\"] = repo_name\n ret[\"full_name\"] = full_name\n # This comes out in some crazy format:\n ret[\"topics\"] = [x for x in repo_data[\"topics\"]]\n # We're going to overwrite this later if we can pull better data\n # from the language-specific files, so duplicate the field.\n ret[\"language_github\"] = repo_data[\"language\"]\n ret[\"description_github\"] = repo_data[\"description\"]\n\n branch = repo_data.default_branch\n tree = api.git.get_tree(org_name, repo_name, branch)[\"tree\"]\n\n language, metadata_files = detect_language(api, org_name, repo_name,\n branch, config)\n\n ret[\"language\"] = language\n ret[\"metadata\"] = get_metadata(api, org_name, repo_name, metadata_files)\n ret[\"contributors\"] = get_contributors(api, org_name, repo_name)\n\n return ret\n\n\ndef get_content_string(encoded):\n return base64.b64decode(encoded[\"content\"]).decode(\"utf-8\")\n\n\ndef detect_language(api, org_name, repo_name, branch, config):\n full_name = f\"{org_name}/{repo_name}\"\n tree = api.git.get_tree(org_name, repo_name, branch)[\"tree\"]\n\n language = set()\n paths = [t[\"path\"] for t in tree]\n metadata = []\n for k in config.sentinals.keys():\n if k in paths:\n language.add(config.sentinals[k])\n metadata.append(k)\n\n override = config.language.get(full_name, None)\n if override:\n language = set([override])\n\n if len(language) > 1:\n raise Exception(\"more than one possible langauge for {full_name}\")\n if len(language) == 0:\n return (None, metadata)\n return (list(language)[0], metadata)\n\n\ndef get_metadata(api, org_name, repo_name, files):\n ret = {}\n for f in files:\n ret[f] = get_content_string(\n api.repos.get_content(org_name, repo_name, f))\n return ret\n\n\ndef get_contributors(api, org_name, repo_name):\n data = api.repos.get_contributors_stats(org_name, repo_name)\n ret = [{\"user\": el[\"author\"][\"login\"], \"count\": el[\"total\"]} for el in data]\n ret.sort(key=lambda x: x[\"count\"], reverse=True)\n return ret\n","repo_name":"mrc-ide/mrc-ide.github.io","sub_path":"scripts/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"46"}