\n\"\"\"\nk = int(sys.argv[1])\nversion = sys.argv[2]\n\nif version == 'sample':\n\tsample_name = sys.argv[3]\n\tfilename = 'samples/%s.txt' % sample_name\n\tsample_kmers = kmer_store()\n\twith open(filename) as f:\n\t\tfor read in f:\n\t\t\tread_kmers = kmers(read.strip(), k)\n\t\t\tfor kmer in read_kmers:\n\t\t\t\tsample_kmers.update(kmer)\n\n\toutput_filename = 'pickles/%s_kmers_%d.pickle' % (os.path.basename(os.path.normpath(filename)).replace('.txt',''), k)\n\twith open(output_filename, 'w') as f:\n\t\tcPickle.dump(sample_kmers.kmers, f)\n\nelif version =='genomes':\n\tfull = True if (len(sys.argv) == 4 and sys.argv[3] == 'full') else False\n\tkmer_spectra = defaultdict(lambda:[0]*20)\n\tfor index, genome_filename in enumerate(progress(filter(lambda x: x.endswith('.fna'), os.listdir('genomes')))):\n\t\tkmer_spectrum = {} if full else kmer_store()\n\t\tfor kmer in kmers(nucleotides_fna('genomes/'+genome_filename), k):\n\t\t\tif full:\n\t\t\t\tkmer_spectrum[kmer] = kmer_spectrum[kmer]+1 if kmer in kmer_spectrum else 1\n\t\t\telse:\n\t\t\t\tkmer_spectrum.update(kmer)\n\t\tfor kmer in kmer_spectrum:\n\t\t\tkmer_spectra[kmer][index] = kmer_spectrum[kmer]\n\n\tfull_string = 'full_' if full else ''\n\twith open('pickles/%skmer_spectra_%d.pickle' % (full_string, k), 'w') as f:\n\t\tcPickle.dump(dict(kmer_spectra), f)\n\n","sub_path":"gen_kmers.py","file_name":"gen_kmers.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"547090527","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport aifc\nfrom scipy import signal\nfrom torch.utils import data\nfrom torchvision import transforms\nimport os\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nimport glob\nimport parameters\n\nfrom utils import set_seed\n\nNoise_Stats_Directory = \"../elephant_dataset/eleph_dataset/Noise_Stats/\"\n\ndef get_loader(data_dir,\n batch_size,\n random_seed=8,\n norm=\"norm\",\n scale=False,\n augment=False,\n shuffle=True,\n num_workers=16,\n pin_memory=False):\n \"\"\"\n Utility function for loading and returning train and valid\n multi-process iterators.\n If using CUDA, num_workers should be set to 1 and pin_memory to True.\n Params\n ------\n - data_dir: path directory to the dataset.\n - batch_size: how many samples per batch to load.\n - random_seed: fix seed for reproducibility.\n - augment: whether data augmentation scheme. Only applied on the train split.\n - valid_size: percentage split of the training set used for\n the validation set. Should be a float in the range [0, 1].\n - shuffle: whether to shuffle the train/validation indices.\n - num_workers: number of subprocesses to use when loading the dataset.\n - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to\n True if using GPU.\n - data_file_paths: If you know what particular data file names you want to load, \n pass them in as a list of strings.\n Returns\n -------\n - train_loader: training set iterator.\n - valid_loader: validation set iterator.\n \"\"\"\n # Note here we could do some data preprocessing!\n # define transform\n # Set the dataloader seed\n set_seed(parameters.DATA_LOADER_SEED)\n\n dataset = ElephantDataset(data_dir, preprocess=norm, scale=scale)\n \n print('Size of dataset at {} is {} samples'.format(data_dir, len(dataset)))\n\n # Set the data_loader random seed for reproducibility.\n # Should do some checks on this\n def _init_fn(worker_id):\n # We probably do not want every worker to have \n # the same random seed or else they may do the same \n # thing?\n np.random.seed(int(random_seed) + worker_id)\n\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, \n shuffle=shuffle, num_workers=num_workers, pin_memory=pin_memory, worker_init_fn=_init_fn)\n\n return data_loader\n\ndef get_loader_fuzzy(data_dir,\n batch_size,\n random_seed=8,\n norm=\"norm\",\n scale=False,\n include_boundaries=False,\n shift_windows=False,\n is_full_dataset=False,\n full_window_predict=False,\n augment=False,\n shuffle=True,\n num_workers=16,\n pin_memory=False):\n \"\"\"\n Utility function for loading and returning train and valid\n multi-process iterators.\n If using CUDA, num_workers should be set to 1 and pin_memory to True.\n Params\n ------\n - data_dir: path directory to the dataset.\n - batch_size: how many samples per batch to load.\n - random_seed: fix seed for reproducibility.\n - augment: whether data augmentation scheme. Only applied on the train split.\n - valid_size: percentage split of the training set used for\n the validation set. Should be a float in the range [0, 1].\n - shuffle: whether to shuffle the train/validation indices.\n - num_workers: number of subprocesses to use when loading the dataset.\n - pin_memory: whether to copy tensors into CUDA pinned memory. Set it to\n True if using GPU.\n - data_file_paths: If you know what particular data file names you want to load, \n pass them in as a list of strings.\n\n -is_full_dataset: Is important for when we are shifting the windows, because\n when using the full 24 hr dataset for adversarial discover we always want to \n use the middle of the oversized window!\n \n -fixed_repeat: Used for training the second model in a heirarchical setting.\n Repeat sliding windows but save fixed random slices for each window\n\n Returns\n -------\n - train_loader: training set iterator.\n - valid_loader: validation set iterator.\n\n \"\"\"\n # Note here we could do some data preprocessing!\n # define transform\n # Set the dataloader seed\n print (\"DataLoader Seed:\", parameters.DATA_LOADER_SEED)\n set_seed(parameters.DATA_LOADER_SEED)\n\n dataset = ElephantDatasetFuzzy(data_dir, preprocess=norm, scale=scale, include_boundaries=include_boundaries, \n shift_windows=shift_windows, is_full_dataset=is_full_dataset, \n full_window_predict=full_window_predict)\n \n print('Size of dataset at {} is {} samples'.format(data_dir, len(dataset)))\n\n # Set the data_loader random seed for reproducibility.\n # Should do some checks on this\n def _init_fn(worker_id):\n # Assign each worker its own seed\n np.random.seed(int(random_seed) + worker_id)\n # Is this bad??\n # This seems bad as each epoch will be the same order of data! \n #torch.manual_seed(int(random_seed) + worker_id)\n\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, \n shuffle=shuffle, num_workers=num_workers, pin_memory=pin_memory, worker_init_fn=_init_fn)\n\n return data_loader\n\n\nclass ElephantDatasetFuzzy(data.Dataset):\n def __init__(self, data_path, preprocess=\"norm\", scale=False, transform=None, include_boundaries=False, \n shift_windows=False, is_full_dataset=False, full_window_predict=False):\n # Plan: Load in all feature and label names to create a list\n self.data_path = data_path\n self.user_transforms = transform\n self.preprocess = preprocess\n self.scale = scale\n self.include_boundaries = include_boundaries\n self.shift_windows = shift_windows\n self.is_full_dataset = is_full_dataset\n self.full_window_predict = full_window_predict\n # This is only used if we want to generate fixed repeated\n # windows during hierarchical training\n self.fixed_indeces = None\n # By default this is False \n # and only True for the special case where\n # we incorperate model_0 predictions into \n # the 2-stage model \n self.model_0_feature = False\n\n '''\n self.features = glob.glob(data_path + \"/\" + \"*features*\", recursive=True)\n self.initialize_labels()\n '''\n\n self.pos_features = glob.glob(data_path + \"/\" + \"*_features_*\", recursive=True)\n self.neg_features = glob.glob(data_path + \"/\" + \"*_neg-features_*\", recursive=True)\n self.intialize_data(init_pos=True, init_neg=True)\n\n assert len(self.features) == len(self.labels)\n if self.include_boundaries:\n assert len(self.features) == len(self.boundary_masks)\n\n print(\"ElephantDataset number of features {} and number of labels {}\".format(len(self.features), len(self.labels)))\n print('Normalizing with {} and scaling {}'.format(preprocess, scale))\n\n def initialize_labels(self):\n self.labels = []\n self.boundary_masks = []\n for feature_path in self.features:\n feature_parts = feature_path.split(\"features\")\n self.labels.append(glob.glob(feature_parts[0] + \"labels\" + feature_parts[1])[0])\n if self.include_boundaries:\n self.boundary_masks.append(glob.glob(feature_parts[0] + \"boundary-masks\" + feature_parts[1])[0])\n\n\n def set_pos_features(self, pos_features):\n print(\"Length of pos_features was {} and is now {} \".format(len(self.pos_features), len(pos_features)))\n self.pos_features = pos_features\n self.intialize_data(init_pos=True, init_neg=False)\n\n def set_neg_features(self, neg_features):\n print(\"Length of neg_features was {} and is now {} \".format(len(self.neg_features), len(neg_features)))\n self.neg_features = neg_features\n self.intialize_data(init_pos=False, init_neg=True)\n\n def add_neg_features(self, neg_features):\n print(\"Length of neg_features was {} and grew to {} \".format(len(self.neg_features), len(neg_features) + len(self.neg_features)))\n self.neg_features += neg_features\n self.intialize_data(init_pos=False, init_neg=True)\n\n def set_featues(self, pos_features, neg_features):\n print(\"Length of pos_features was {} and is now {} \".format(len(self.pos_features), len(pos_features)))\n print(\"Length of neg_features was {} and is now {} \".format(len(self.neg_features), len(neg_features)))\n self.pos_features = pos_features\n self.neg_features = neg_features\n self.intialize_data(init_pos=True, init_neg=True)\n\n def scale_features(self, pos_factor, neg_factor):\n print(\"Length of pos_features was {} and is now {} \".format(len(self.pos_features), int(pos_factor * len(self.pos_features))))\n print(\"Length of neg_features was {} and is now {} \".format(len(self.neg_features), int(neg_factor * len(self.neg_features))))\n # Add in a feature to undersample as well!\n # Could consider also giving hardness to these to help with selection.\n # Let us do random for now\n if pos_factor < 1:\n indeces = np.arange(len(self.pos_features))\n pos_inds = np.random.choice(indeces, int(indeces.shape[0] * pos_factor))\n self.pos_features = list(np.array(self.pos_features)[pos_inds])\n self.pos_labels = list(np.array(self.pos_labels)[pos_inds])\n else:\n self.pos_features *= pos_factor\n self.pos_labels *= pos_factor\n\n if neg_factor < 1:\n indeces = np.arange(len(self.neg_features))\n neg_inds = np.random.choice(indeces, int(indeces.shape[0] * neg_factor))\n self.neg_features = list(np.array(self.neg_features)[neg_inds])\n self.neg_labels = list(np.array(self.neg_labels)[neg_inds])\n else:\n self.neg_features *= neg_factor\n self.neg_labels *= neg_factor\n\n # Re-form the feature and data set\n self.features = self.pos_features + self.neg_features\n self.labels = self.pos_labels + self.neg_labels\n\n def update_labels(self, new_pos_labels_dir, new_neg_labels_dir):\n \"\"\"\n Kinda an adhoc method, but currently we are using this in\n the new 3rd label dataset. For the given features / windows\n in the dataset, replace the corresponding labels with the\n new 3 class labels. \n Implemenation: Since the new label names should match the\n training example names, go through each training example\n and get the new label path from either pos/neg label dir.\n\n @ Params\n @ new_pos_labels_dir - The folder that contains the new positive window labels\n @ new_neg_labels_dir - The folder that contains the new negative window labels\n \"\"\"\n # Replace the labels for the positive examples\n new_pos_labels = []\n for pos_feat in self.pos_features:\n data_id = pos_feat.split('/')[-1]\n new_pos_label = os.path.join(new_pos_labels_dir, data_id.replace('features', 'labels'))\n new_pos_labels.append(new_pos_label)\n\n self.pos_labels = new_pos_labels\n\n # Replace the labels for the negative examples\n new_neg_labels = []\n for neg_feat in self.neg_features:\n data_id = neg_feat.split('/')[-1]\n new_neg_label = os.path.join(new_neg_labels_dir, data_id.replace('features', 'labels'))\n new_neg_labels.append(new_neg_label)\n\n self.neg_labels = new_neg_labels\n\n # Re-set self.labels\n self.labels = self.pos_labels + self.neg_labels\n\n def add_model_0_preds(self, model_0_pos_dir, model_0_neg_dir):\n \"\"\"\n Add the additional feature of the model_0 predictions for\n each training window. \n Implemenation: Since the new label names should match the\n training example names, go through each training example\n and get the new label path from either pos/neg label dir.\n\n @ Params\n @ model_0_pos_dir - The folder that contains the model_0 positive window preds\n @ model_0_neg_dir - The folder that contains the model_0 negative window preds\n \"\"\"\n # Replace the labels for the positive examples\n self.model_0_pos_preds = []\n for pos_feat in self.pos_features:\n data_id = pos_feat.split('/')[-1]\n new_pos_label = os.path.join(model_0_pos_dir, data_id.replace('features', 'labels'))\n self.model_0_pos_preds.append(new_pos_label)\n\n # Replace the labels for the negative examples\n self.model_0_neg_preds = []\n for neg_feat in self.neg_features:\n data_id = neg_feat.split('/')[-1]\n new_neg_label = os.path.join(model_0_neg_dir, data_id.replace('features', 'labels'))\n self.model_0_neg_preds.append(new_neg_label)\n\n # Re-set self.labels\n self.model_0_preds = self.model_0_pos_preds + self.model_0_neg_preds\n self.model_0_feature = True\n\n\n def create_fixed_windows(self):\n self.fixed_indeces = []\n\n # Generate the fixed indeces\n for i in range(len(self.features)):\n feature = np.load(self.features[i])\n label = np.load(self.labels[i])\n\n # Sample a random start index to save\n call_length = -(label.shape[0] - 2 * parameters.CHUNK_SIZE)\n # Use torch.randint because of weird numpy seeding issues\n start_slice = torch.randint(0, parameters.CHUNK_SIZE - call_length, (1,))[0].item()\n self.fixed_indeces.append(start_slice)\n\n def intialize_data(self, init_pos=True, init_neg=True):\n \"\"\"\n Initialize both the positive and negative label and boundary\n mask data arrays if indicated by the initialization flags \n 'init_pos' and 'init_neg'. After initializing any necessary\n data, combine the positive and negative examples!\n \"\"\"\n # Initialize the positive examples\n if init_pos:\n self.pos_labels = []\n self.pos_boundary_masks = []\n for feature_path in self.pos_features:\n feature_parts = feature_path.split(\"features\")\n self.pos_labels.append(glob.glob(feature_parts[0] + \"labels\" + feature_parts[1])[0])\n if self.include_boundaries:\n self.pos_boundary_masks.append(glob.glob(feature_parts[0] + \"boundary-masks\" + feature_parts[1])[0])\n\n\n # Initialize the negative examples\n if init_neg:\n self.neg_labels = []\n self.neg_boundary_masks = []\n for feature_path in self.neg_features:\n feature_parts = feature_path.split(\"features\")\n self.neg_labels.append(glob.glob(feature_parts[0] + \"labels\" + feature_parts[1])[0])\n if self.include_boundaries:\n self.neg_boundary_masks.append(glob.glob(feature_parts[0] + \"boundary-masks\" + feature_parts[1])[0])\n\n # Combine the positive and negative examples!\n self.features = self.pos_features + self.neg_features\n self.labels = self.pos_labels + self.neg_labels\n if self.include_boundaries:\n self.boundary_masks = self.pos_boundary_masks + self.neg_boundary_masks\n\n print (\"Len Pos Features:\", len(self.pos_features))\n print (\"Len Neg Features:\", len(self.neg_features))\n\n\n def __len__(self):\n return len(self.features)\n\n \"\"\"\n Return a single element at provided index\n \"\"\"\n def __getitem__(self, index):\n feature = np.load(self.features[index])\n label = np.load(self.labels[index])\n\n # Load the model_0 predictions and incorperate\n # them into the data transform\n if self.model_0_feature:\n model_0_pred = np.load(self.model_0_preds[index])\n feature = self.apply_transforms(feature, model_0_pred)\n else:\n feature = self.apply_transforms(feature)\n\n if self.shift_windows:\n feature, label = self.sample_chunk(feature, label)\n\n # Select fixed random crop\n if self.fixed_indeces is not None:\n start_index = self.fixed_indeces[index]\n feature = feature[start_index: start_index + parameters.CHUNK_SIZE, :]\n label = label[start_index: start_index + parameters.CHUNK_SIZE]\n\n if self.user_transforms:\n feature = self.user_transforms(feature)\n\n # Honestly may be worth pre-process this\n feature = torch.from_numpy(feature).float()\n if self.full_window_predict:\n # Make the label a binary 0/1 if an elephant \n # call is present (May be some weird boundary cases\n # with call being on the edge, but we'll cross that\n # bridge later).\n label = 1. if np.sum(label) > 0 else 0.\n else: \n label = torch.from_numpy(label).float()\n\n # Return the boundary masks\n if self.include_boundaries:\n masks = np.load(self.boundary_masks[index])\n # Cast to a bool tensor to allow for array masking\n masks = torch.from_numpy(masks) == 1\n\n return feature, label, masks, self.features[index]\n else:\n return feature, label, self.features[index] # Include the data file\n\n def sample_chunk(self, feature, label):\n \"\"\"\n Selected a random chunk within the oversized window.\n Figure out the call length as: -(window_size - 2*256).\n Then sample starting slice as rand in range [0, 256 - call_length].\n\n Note: if the flag 'is_full_dataset' is set then return the middle\n 256! This is for adversarial discovery mode\n \"\"\"\n if self.is_full_dataset:\n # The full test set window sizes are 2 * (256 / normal)\n start_slice = label.shape[0] // 4\n end_slice = start_slice + label.shape[0] // 2\n else:\n call_length = -(label.shape[0] - 2 * parameters.CHUNK_SIZE)\n # Draw this out but it should be correct!\n # Use torch.randint because of weird numpy seeding issues\n start_slice = torch.randint(0, parameters.CHUNK_SIZE - call_length, (1,))[0].item()\n end_slice = start_slice + parameters.CHUNK_SIZE\n\n return feature[start_slice : end_slice, :], label[start_slice : end_slice]\n\n def apply_transforms(self, data, model_0_pred=None):\n if self.scale:\n data = 10 * np.log10(data)\n\n # Normalize Features\n if self.preprocess == \"norm\":\n data = (data - np.mean(data)) / np.std(data)\n elif self.preprocess == \"globalnorm\":\n data = (data - 132.228) / 726.319 # Calculated these over the training dataset \n elif self.preprocess == \"feature\":\n data = (data - np.mean(data, axis=0)) / np.std(data, axis=0)\n\n # If model_0_pred is provided, then create a 3 channel\n # \"image\" where channels 1 and 2 are the spectrogram and \n # the 3rd channel is a (-1, 1) valued image of model_0 preds.\n # Specifically, create a column of '1' for '1' predictions and\n # a column of '-1' for '0' preds\n if model_0_pred is not None:\n # Expand the channel dim of the spectrogram\n data = np.expand_dims(data, axis=0)\n # Create the prediction mask. First convert '0'\n # to '-1' value\n model_0_pred[model_0_pred == 0] = -1\n # Repeat the pred values along the feature axis\n model_0_pred = np.expand_dims(model_0_pred, axis=1)\n model_0_pred = np.repeat(model_0_pred, data.shape[2], axis=1)\n # Consider normalizing this input!!\n model_0_pred = (model_0_pred - np.mean(model_0_pred)) / np.std(model_0_pred)\n\n # Repeat the spectrogram data to creat 3 channels and then\n # make the final channel by the model_0_pred\n data = np.repeat(data, 3, axis=0)\n data[2, :, :] = model_0_pred\n\n return data\n\n\"\"\"\n Notes\n - Preprocess = Norm, Scale = False ===> seems bad\n - Preprocess = Norm, Scale = True ===> Works well on small dataset!\n - Preprocess = Scale, Scale = False ===> Has quite a bit of trouble over fitting small dataset compared to other but eventually can\n - Preprocess = Scale, Scale = True ===> Has quite a bit of trouble over fitting small dataset compared to other and bad val acc!\n - Preprocess = ChunkNorm, Scale = False ===> Very slow and bad\n - Preprocess = ChunkNorm, Scale = True ===> Similar to Norm with scale\n - Preprocess = None, Scale = True ====> No worky\n - Preprocess = Scale range (-1, 1), Scale = True ===> Overfit but huge variance issue\n\"\"\"\nclass ElephantDataset(data.Dataset):\n def __init__(self, data_path, transform=None, preprocess=\"norm\", scale=False):\n # Plan: Load in all feature and label names to create a list\n self.data_path = data_path\n self.user_transforms = transform\n self.preprocess = preprocess\n self.scale = scale\n\n # Probably should not have + \"**/\" after data_path? It seems like \n # we are passing the exact datapths anyways! Also why recursive?\n self.features = glob.glob(data_path + \"/\" + \"*features*\", recursive=False)\n self.initialize_labels()\n\n assert len(self.features) == len(self.labels)\n\n print(\"Dataset from path {}\".format(data_path))\n print(\"ElephantDataset number of features {} and number of labels {}\".format(len(self.features), len(self.labels)))\n print('Normalizing with {} and scaling {}'.format(preprocess, scale))\n print(\"Shape of a feature is {} and a label is {}\".format(self[0][0].shape, self[0][1].shape))\n\n def initialize_labels(self):\n self.labels = []\n for feature_path in self.features:\n feature_parts = feature_path.split(\"features\")\n self.labels.append(glob.glob(feature_parts[0] + \"labels\" + feature_parts[1])[0])\n\n\n def __len__(self):\n return len(self.features)\n\n \"\"\"\n Return a single element at provided index\n \"\"\"\n def __getitem__(self, index):\n feature = np.load(self.features[index])\n label = np.load(self.labels[index])\n\n feature = self.apply_transforms(feature)\n if self.user_transforms:\n feature = self.user_transforms(feature)\n \n # Honestly may be worth pre-process this\n feature = torch.from_numpy(feature).float()\n label = torch.from_numpy(label).float()\n\n\n return feature, label, self.features[index] # Include the data file\n\n def apply_transforms(self, data):\n if self.scale:\n data = 10 * np.log10(data)\n\n # Normalize Features\n if self.preprocess == \"norm\":\n data = (data - np.mean(data)) / np.std(data)\n elif self.preprocess == \"globalnorm\":\n data = (data - 132.228) / 726.319 # Calculated these over the training dataset \n\n return data\n\n # elif self.preprocess == \"Scale\":\n # scaler = MinMaxScaler()\n # # Scale features for each training example\n # # to be within a certain range. Preserves the\n # # relative distribution of each feature. Here\n # # each feature is the different frequency band\n # for i in range(self.features.shape[0]):\n # self.features[i, :, :] = scaler.fit_transform(self.features[i,:,:].astype(np.float32))\n # #num_ex = self.features.shape[0]\n # #seq_len = self.features.shape[1]\n # #self.features = self.features.reshape(num_ex * seq_len, -1)\n # #self.features = scaler.fit_transform(self.features)\n # #self.features = self.features.reshape(num_ex, seq_len, -1)\n # elif self.preprocess == \"ChunkNorm\":\n # for i in range(self.features.shape[0]):\n # self.features[i, :, :] = (self.features[i, :, :] - np.mean(self.features[i, :, :])) / np.std(self.features[i, :, :])\n # elif self.preprocess == \"BackgroundS\":\n # # Load in the pre-calculated mean,std,etc.\n # if not scale:\n # mean_noise = np.load(Noise_Stats_Directory + \"mean.npy\")\n # std_noise = np.load(Noise_Stats_Directory + \"std.npy\")\n # else:\n # mean_noise = np.load(Noise_Stats_Directory + \"mean_log.npy\")\n # std_noise = np.load(Noise_Stats_Directory + \"std_log.npy\")\n\n # self.features = (self.features - mean_noise) / std_noise\n # elif self.preprocess == \"BackgroundM\":\n # # Load in the pre-calculated mean,std,etc.\n # if not scale:\n # mean_noise = np.load(Noise_Stats_Directory + \"mean.npy\")\n # median_noise = np.load(Noise_Stats_Directory + \"median.npy\")\n # else:\n # mean_noise = np.load(Noise_Stats_Directory + \"mean_log.npy\")\n # median_noise = np.load(Noise_Stats_Directory + \"median_log.npy\")\n\n # self.features = (self.features - mean_noise) / median_noise\n # elif self.preprocess == \"FeatureNorm\":\n # self.features = (self.features - np.mean(self.features, axis=(0, 1))) / np.std(self.features, axis=(0,1))\n\n\n\n\n\n\"\"\"\n Dataset for full test length audio\n NEED TO FIX THIS!!\n\"\"\"\nclass ElephantDatasetFull(data.Dataset):\n def __init__(self, spectrogram_files, label_files, gt_calls, preprocess=\"norm\", scale=True):\n\n self.specs = spectrogram_files\n self.labels = label_files\n self.gt_calls = gt_calls # This is the .txt file that contains start and end times of calls\n self.preprocess = preprocess\n self.scale = scale\n \n print('Normalizing with {} and scaling {}'.format(preprocess, scale))\n\n\n def __len__(self):\n return len(self.specs)\n\n\n def transform(self, spectrogram): # We need to fix this probably!!!\n # Potentially include other transforms\n if self.scale:\n spectrogram = 10 * np.log10(spectrogram)\n\n # Quite janky, but for now we will do the normalization \n # seperately!\n '''\n # Normalize Features\n if self.preprocess == \"norm\": # Only have one training example so is essentially chunk norm\n spectrogram = (spectrogram - np.mean(spectrogram)) / np.std(spectrogram)\n elif preprocess == \"Scale\":\n scaler = MinMaxScaler()\n # Scale features for each training example\n # to be within a certain range. Preserves the\n # relative distribution of each feature. Here\n # each feature is the different frequency band\n spectrogram = scaler.fit_transform(spectrogram.astype(np.float32))\n elif self.preprocess == \"ChunkNorm\":\n spectrogram = (spectrogram - np.mean(spectrogram)) / np.std(spectrogram)\n elif self.preprocess == \"BackgroundS\":\n # Load in the pre-calculated mean,std,etc.\n if not scale:\n mean_noise = np.load(Noise_Stats_Directory + \"mean.npy\")\n std_noise = np.load(Noise_Stats_Directory + \"std.npy\")\n else:\n mean_noise = np.load(Noise_Stats_Directory + \"mean_log.npy\")\n std_noise = np.load(Noise_Stats_Directory + \"std_log.npy\")\n\n spectrogram = (spectrogram - mean_noise) / std_noise\n elif self.preprocess == \"BackgroundM\":\n # Load in the pre-calculated mean,std,etc.\n if not scale:\n mean_noise = np.load(Noise_Stats_Directory + \"mean.npy\")\n median_noise = np.load(Noise_Stats_Directory + \"median.npy\")\n else:\n mean_noise = np.load(Noise_Stats_Directory + \"mean_log.npy\")\n median_noise = np.load(Noise_Stats_Directory + \"median_log.npy\")\n\n spectrogram = (spectrogram - mean_noise) / median_noise\n elif self.preprocess == \"FeatureNorm\":\n spectrogram = (spectrogram - np.mean(spectrogram, axis=1)) / np.std(spectrogram, axis=1)\n '''\n return spectrogram\n\n \"\"\"\n Return a single element at provided index\n \"\"\"\n def __getitem__(self, index):\n spectrogram_path = self.specs[index]\n label_path = self.labels[index]\n gt_call_path = self.gt_calls[index]\n\n spectrogram = np.load(spectrogram_path)\n label = np.load(label_path)\n\n spectrogram = self.transform(spectrogram)\n #spectrogram = np.expand_dims(spectrogram, axis=0) # Add the batch dimension so we can apply our lstm!\n \n # Honestly may be worth pre-process this\n #spectrogram = torch.from_numpy(spectrogram)\n #label = torch.from_numpy(label)\n\n return spectrogram, label, gt_call_path\n\n\n","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":29205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"213877969","text":"def back(k, sol, sol_max, spectacole):\n global maxim\n ok = False\n for x in spectacole:\n if k == 0 or x[0] >= sol[-1][1]:\n ok = True\n sol.append(x)\n back(k+1, sol, sol_max, spectacole)\n sol.pop()\n \n if ok == False: \n if (k > maxim):\n maxim = k\n sol_max.clear()\n sol_max.append(sol.copy())\n elif k == maxim:\n sol_max.append(sol.copy())\n \n \n\nf = open(\"/home/edi/Desktop/FMI/ProgAlgo/Laborator/Lab6/spectacole.txt\")\nspectacole = []\nfor line in f.read().splitlines():\n ora_inceput = line[:5]\n ora_sfarsit = line[6:11]\n nume_spectacol = line[12:]\n spectacole.append((ora_inceput, ora_sfarsit, nume_spectacol))\n\nsol = []\nsol_max = [None]\nmaxim = 0\nback(0, sol, sol_max, spectacole)\nfor x in sol_max:\n for y in x:\n print(y)\n print()","sub_path":"Sem_1/ProgAlgo/Laborator/Lab6/II_4.py","file_name":"II_4.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"479637293","text":"import tensorflow as tf\nimport math as m\n\nPI = tf.constant(m.pi)\n\na = tf.cos(PI/3.)\nb = tf.sin(PI/3.)\nc = 1.0/a # sec(60)\nd = 1.0/tf.tan(PI/3.) # cot(60)\n\n@tf.function\ndef math_values():\n print(\"a:\",a) \n print(\"b:\",b) \n print(\"c:\",c) \n print(\"d:\",d) \n\nmath_values()\n\n","sub_path":"books/Machine Learning/CompanionFiles/code/appendixb-tf2/tf2_trig_values.py","file_name":"tf2_trig_values.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"292047152","text":"import numpy as np\nimport cv2\nimport utils\n\n#webcam value when set to false, will use source image at path\nwebcam = False\n\n#Pass the path of source image\npath = '2.jpg'\n\nimgCapture = cv2.VideoCapture(0)\nimgCapture.set(10, 160)\nimgCapture.set(3, 1920)\nimgCapture.set(4, 1080)\n#define scale\nscale = 2\nwP = 210*scale\nhP = 297*scale\n\nwhile True:\n if webcam:\n success, img = imgCapture.read()\n else:\n img = cv2.imread(path)\n\n imgContours, Contours1 = utils.getContours(img, minArea=50000, filter=4)\n if len(Contours1) != 0:\n biggest = Contours1[0][2]\n # print(biggest)\n imgWarp = utils.warpImg(img, biggest, wP, hP)\n #cv2.imshow('A4', imgWarp)\n imgContours2, Contours2 = utils.getContours(imgWarp, minArea=2000, filter=4,\n cThresh=[50, 50], draw = False)\n if len(Contours1)!=0:\n for obj in Contours2:\n cv2.polylines(imgContours2, [obj[2]], True, (0,255,0), 2)\n newPoints = utils.reorder(obj[2])\n #Divide no of pixels by the scale value\n newWidth = round((utils.findDist(newPoints[0][0]//scale, newPoints[1][0]//scale)/10), 1)\n newHeight = round((utils.findDist(newPoints[0][0]//scale, newPoints[2][0]//scale)/10), 1)\n cv2.arrowedLine(imgContours2, (newPoints[0][0][0], newPoints[0][0][1]),\n (newPoints[1][0][0], newPoints[1][0][1]),\n (255, 0, 255), 3, 8, 0, 0.05)\n cv2.arrowedLine(imgContours2, (newPoints[0][0][0], newPoints[0][0][1]),\n (newPoints[2][0][0], newPoints[2][0][1]),\n (255, 0, 255), 3, 8, 0, 0.05)\n x, y, w, h = obj[3]\n cv2.putText(imgContours2, '{}cm'.format(newWidth), (x + 30, y - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,\n (255, 0, 255), 2)\n cv2.putText(imgContours2, '{}cm'.format(newHeight), (x - 70, y + h // 2), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,\n (255, 0, 255), 2)\n\n cv2.imshow('A4', imgContours2)\n\n img = cv2.resize(img, (0, 0), None, 0.5, 0.5)\n #Print original image\n cv2.imshow(\"Original\", img)\n cv2.waitKey(1)\n","sub_path":"objectMeasurement.py","file_name":"objectMeasurement.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"634865567","text":"from setuptools import setup\n\nDESCRIPTION = 'Storage utilities for the Rad-I/O project.'\nLONG_DESCR = DESCRIPTION\n\nsetup(\n name='radio_storage',\n version='0.0.1',\n description=DESCRIPTION,\n long_description=LONG_DESCR,\n url='https://gitlab.com/',\n author='Rad-I/O',\n author_email='a96tudor@gmail.com',\n license='GPLv3',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: End Users/Desktop',\n 'Topic :: Games/Entertainment',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Programming Language :: Python :: 3',\n ],\n keywords='Rad-I/O storage',\n packages=['storage', 'storage.drivers'],\n install_requires=[\n 'numpy', 'psycopg2', 'tensorflow', 'passlib',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"123501950","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport numpy as np\nfrom Func import write_data\n\n\ndata = np.zeros((512, 512))\ndata[143:399, 151] = 1\ndata[143:399, 406] = 1\ndata[143, 151:407] = 1\ndata[398, 151:407] = 1\nwrite_data('./extra/Frame.xlsx', data, sheetname='Frame')\n# 用于构造Frame并存在Excel表格中\n","sub_path":"Alpha/Frame_builder.py","file_name":"Frame_builder.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"472524993","text":"'''\nBST中的特定节点中序遍历后的下一个节点\n\n面试题 04.06. Successor LCCI\n'''\n\n\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n# 方法1 用stack进行中序遍历\nclass Solution:\n def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:\n if root == None:\n return None\n \n stack = []\n flag = False\n while stack or root:\n while root:\n stack.append(root)\n root = root.left\n \n curr = stack.pop()\n if flag:\n return curr\n \n if curr == p:\n flag = True\n \n if curr.right:\n root = curr.right\n return None\n\n# 用二分\nclass Solution:\n def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> TreeNode:\n if root == None:\n return None \n \n # if root == p:\n # return self.inorderSuccessor(root.right, p)\n # elif root.val < p.val:\n\n res = None\n curr = root\n\n while curr:\n if curr.val <= p.val:\n curr = curr.right\n else:\n res = curr\n curr = curr.left\n return res\n","sub_path":"Python/Binary Search Tree/285. Inorder Successor in BST.py","file_name":"285. Inorder Successor in BST.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"414840528","text":"# fibonacci_functions.py\r\n# Jan 2, 2016\r\n\r\n# Loop\r\ndef fib1(n):\r\n a, b = 0, 1\r\n for _ in range(n):\r\n c = b + a\r\n a, b = b, c\r\n return a\r\n\r\n# Recursion\r\ndef fib2(n):\r\n if n in (0,1):\r\n return n\r\n else:\r\n return fib2(n-1) + fib2(n-2)\r\n\r\n# Generator\r\ndef fib3(n):\r\n a, b = 0, 1\r\n for _ in range(n):\r\n yield a\r\n c = b + a\r\n a, b = b, c\r\n\r\n# Print results\r\nprint(\"Fibonacci Loop:\")\r\nfor i in range(8):\r\n print(fib1(i), end=', ')\r\nprint('\\n')\r\n\r\nprint(\"Fibonacci Recursion:\")\r\nfor i in range(8):\r\n print(fib2(i), end=', '),\r\nprint('\\n')\r\n\r\nprint(\"Fibonacci Generator:\")\r\nfor i in fib3(8):\r\n print(i, end=', '),\r\nprint('\\n')\r\n","sub_path":"fibonacci_generator.py","file_name":"fibonacci_generator.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"542566468","text":"import re\r\n\r\n# we don't care about case sensitivity and therefore use lower:\r\nabcfile = open(\"abc.txt\").read().lower()\r\n\r\nwords = re.findall(r\"\\b[\\w-]+\\b\", abcfile)\r\nprint(\"Myfile contains to total: \" + str(len(words)))\r\n\r\nfor x in [\"the\", \"of\", \"on\", \"to\", \"this\"]:\r\n print(x + \"' occurs \" + str(words.count(x)) + \" times\" )\r\n\r\n","sub_path":"readingile.py","file_name":"readingile.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"644550667","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 26 21:03:04 2017\n\nConduct erxperiment on IEMOCAP, three labels: \n \n 96001: emotion(0-4, 5 = other emotions)\n 96002: speaker(0-9)\n 96003: gender(male=0, female=1)\n \n\n@author: Kyle\n\"\"\"\n\nimport os\nfrom sys import argv\n_, newFolderName, gpuI = argv\n\nos.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpuI)\n\nimport sys\nsys.path.append(\"../../model/\")\nimport soundNet\nsys.path.append(\"../\")\nimport expUtil\nimport numpy as np\nimport tensorflow as tf\nfrom keras.utils import np_utils\nfrom tensorflow.python.platform import tf_logging as logging\nfrom keras import backend as K\nimport matplotlib.pyplot as plt\nfrom cleverhans.attacks import FastGradientMethod\nfrom cleverhans.utils_keras import KerasModelWrapper\nfrom keras.models import load_model\nfrom cleverhans.model import CallableModelWrapper\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nimport time\nimport shutil\n\n#%% creat folder to save model, the code, and model configuration \nwhile os.path.isdir( newFolderName ):\n newFolderName = newFolderName + '_1'\n print( 'exist' )\n\nos.mkdir( newFolderName )\nshutil.copy( 'emotionSoundNet.py', newFolderName )\nshutil.copy( '../../model/soundNet.py', newFolderName )\n\n#%% fix random seed and session\ntf.set_random_seed( 7 )\nsess = tf.Session( )\nK.set_session( sess )\n\n#%% load data, devide it into training/test set, and seperate out the laebls \n# normalize the feature to [0, 1]\n# for emotion tests, filter out value = 4 (other emotions)\n# folder list, i.e., IEMCOCAP has 5 sessions, speakers are independent between sessions, always use leave-one-session-out stragegy\nfolderList = [ 0, 1, 2, 3, 4 ]\ntestFolder = 4\n\ntrainFolderList = folderList.copy( )\ndel trainFolderList[ testFolder - 1 ]\n\nsampleRate = 16000\nprecision = 'original'\ndataFileFolder = '../../../processedData/waveform/' + str( sampleRate ) + '_' + precision + '/session_'\n\nfold = [ 0, 0, 0, 0, 0 ]\nfor i in folderList:\n fold[ i ] = eval( 'expUtil.iter_loadtxt( dataFileFolder + str(' + str( i + 1 ) + ') + \".csv\" )' )\n\n# seperate training and testing data\ntrainData = eval( 'np.concatenate( ( fold[ ' + str( trainFolderList[ 0 ] ) + \\\n ' ], fold[ ' + str( trainFolderList[ 1 ] ) + \\\n ' ], fold[ ' + str( trainFolderList[ 2 ] ) + \\\n ' ], fold[ ' + str( trainFolderList[ 3 ] ) + ' ] ), axis=0 )' )\ntestData = eval( 'fold[ ' + str( testFolder ) + ' ]' )\n\ntrainFeature, trainEmotionLabel = expUtil.processData( trainData, task = 'emotion' )\ntestFeature, testEmotionLabel = expUtil.processData( testData, task = 'emotion' )\n\n#%% define training parameters\nbatch_size = 32\nlearningRate = 0.0001\niterationNum = 100\n\n\"\"\"Trains the audio model.\n\n Args:\n feature: [ sample_size, audio_length ]\n label: one-hot style\n\"\"\"\n\ndef train( testFeature, testLabel, trainFeature, trainLabel, iteration_num = 100, lr_decay = 0.1 ):\n \n result = np.zeros( [ 2, iteration_num ] )\n class_num = testLabel.shape[ 1 ]\n train_datasize = trainFeature.shape[ 0 ]\n \n with tf.Session() as sess:\n \n # changable learning rate \n global_step = tf.Variable(0) \n learning_rate = tf.train.exponential_decay( learningRate, global_step, int( iteration_num *(train_datasize/batch_size) ), lr_decay, staircase=False) \n\n # fix random index for reproducing result \n tf.set_random_seed( 17 )\n input_x = tf.placeholder( tf.float32, shape = ( batch_size, 96000 ), name = 'inputx' )\n input_y = tf.placeholder( tf.float32, shape = ( batch_size, class_num ), name = 'inputy' )\n modelT = soundNet.soundNet\n \n # define a set of adversarials (adversarial stuffs)\n orderList = [ np.inf, 1, 2 ]\n advList = orderList.copy( )\n fgsmList = orderList.copy( )\n advOut = orderList.copy( )\n for epsIndex in range( 0, len( orderList ) ):\n fgsmList[ epsIndex ] = FastGradientMethod( modelT , sess = sess )\n fgsm_params = { 'eps': 1, 'y': input_y, 'ord': orderList[ epsIndex ] }\n advList[ epsIndex ] = fgsmList[ epsIndex ].generate( input_x, **fgsm_params )\n advOut[ epsIndex ] = tf.multiply( advList[ epsIndex ], 1, name = 'adv'+str( epsIndex ) )\n \n prediction = modelT( input_x, numClass = class_num )\n loss = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits( logits = prediction, labels= input_y ) )\n train_step = tf.train.AdamOptimizer( learning_rate ).minimize( loss, global_step = global_step )\n correct_prediction = tf.equal( tf.argmax( prediction, 1 ), tf.argmax( input_y, 1 ) )\n accuracy = tf.reduce_mean( tf.cast( correct_prediction, tf.float32 ), name=\"acc_restore\" )\n \n saver = tf.train.Saver()\n \n # initialize the data \n init_op = tf.global_variables_initializer( )\n sess.run( init_op )\n \n # number of iterations\n for iteration in range( 0, iteration_num ):\n # each batch\n for i in range( 0, 1 *int( train_datasize / batch_size ) ):\n \n start = ( i * batch_size ) % train_datasize\n end = min( start + batch_size, train_datasize )\n \n inputTrainFeature = trainFeature[ start: end ]\n inputTrainLabel = trainLabel[ start: end ]\n \n _, lossShow = sess.run( [ train_step, loss ], feed_dict = { input_x: inputTrainFeature, input_y: inputTrainLabel } )\n #print( 'loss = ' + str( lossShow ) )\n \n # get accuracy on a small subset of test data (just several epoch), a very fast approximation of the performance \n testBatchNum = 3\n testSubsetResult = [ None ] *( batch_size *testBatchNum )\n testSubsetLabel = [ None ] *( batch_size *testBatchNum )\n for testBatch in range( 0, testBatchNum ): # 3*32=96 test samples\n start = testBatch * batch_size \n end = start + batch_size\n inputTestFeature = testFeature[ start: end ]\n inputTestLabel = testLabel[ start: end ] \n tempTestResult, tempAccuracyTest = sess.run( [ prediction, accuracy ], feed_dict = { input_x: inputTestFeature, input_y: inputTestLabel } ) \n testSubsetLabel[ start :end ] = tf.argmax( inputTestLabel, 1 )\n testSubsetResult[ start :end ] = tf.argmax( tempTestResult, 1 ) \n #np.savetxt( newFolderName + '/testResult.csv', testResult, delimiter = ',' )\n #np.savetxt( newFolderName + '/testLabel.csv', inputTestLabel, delimiter = ',' )\n accuracyTest = accuracy_score( testSubsetLabel, testSubsetResult )\n print( confusion_matrix( testSubsetLabel, testSubsetResult ) )\n result[ 0, iteration ] = accuracyTest\n print( 'Epoch:' + str( iteration ) + ' result on test: ' + str( accuracyTest ) )\n \n # get accuracy on a small subset of training data (just one epoch), a very fast approximation of the training loss/ overfitting \n inputTestTrainFeature = trainFeature[ 0: batch_size, : ]\n inputTestTrainLabel = trainLabel[ 0: batch_size, : ]\n testTrainResult, accuracyTrain = sess.run( [ prediction, accuracy ], feed_dict = { input_x: inputTestTrainFeature, input_y: inputTestTrainLabel } ) \n print( 'Epoch:' + str( iteration ) + ' result on train: ' + str( accuracyTrain ) )\n #np.savetxt( newFolderName + '/testTrainResult.csv', testTrainResult, delimiter = ',' )\n #np.savetxt( newFolderName + '/testTrainLabel.csv', inputTestTrainLabel, delimiter = ',' )\n result[ 1, iteration ] = accuracyTrain\n print( '-----------------------------' )\n print( sess.run(global_step) ) \n print( sess.run(learning_rate) )\n # record the accuracy of both test/ training error approximation on the small subset\n np.savetxt( newFolderName + '/accuracy.csv', result, delimiter = ',' )\n \n # save model every 10 epoches\n if ( iteration + 1 )%10 == 0:\n save_path = saver.save( sess, newFolderName + '/model_' + str( iteration + 1 ) + '_.ckpt' )\n print(\"Model saved in file: %s\" % save_path)\n \n resultOnTest = result[ 0, : ]\n resultOnTrain = result[ 1, : ]\n plt.plot( list( range( iteration_num ) ), resultOnTrain )\n plt.plot( list( range( iteration_num ) ), resultOnTest )\n plt.savefig( newFolderName + '/accuracy.png' )\n \n #%% get adversarial samples\n# for epsIndex in range( 0, len( orderList ) ): \n# data_update = np.copy( feature[ train_datasize: whole_datasize, : ] )\n# # mini-batch generation on training data\n# for i in range( 0, int( ( whole_datasize - train_datasize ) / batch_size ) ):\n# start = i * batch_size\n# end = ( i + 1 ) * batch_size\n# data_update[ start:end, : ] = sess.run( advList[ epsIndex ], feed_dict = { input_x: feature[ train_datasize + start: train_datasize + end, : ], input_y: label[ train_datasize + start: train_datasize + end, : ] } ) \n# np.savetxt( newFolderName + '/adv'+str( orderList[ epsIndex ] ) + '.csv', data_update, delimiter = ',' )\n# return data_update\n#%% start test \ntrain( testFeature, testEmotionLabel, trainFeature, trainEmotionLabel )\n#np.savetxt( newFolderName + '/testSet.csv', dataSet[ train_datasize: whole_datasize, : ], delimiter = ',' )\n#np.savetxt( newFolderName + '/testFeature.csv', feature[ train_datasize: train_datasize + batch_size ], delimiter = ',' )\n#np.savetxt( newFolderName + '/testLabelGender.csv', genderLabel[ train_datasize: train_datasize + batch_size ], delimiter = ',' )\n\n\n","sub_path":"code/experiment/EmotionSoundNet/ex1_1_1_1_1_1_1_1_1/emotionSoundNet.py","file_name":"emotionSoundNet.py","file_ext":"py","file_size_in_byte":10069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"324500658","text":"\"\"\"\nCalculates class specific and over-all evaluation scores on the model\nScores: TP,FN,FP,precision,recall,f2score\n\"\"\"\n\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nimport random\nimport pprint\nimport sys\nimport time\nimport numpy as np\nimport pickle\nimport math\nimport cv2\nimport copy\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\nimport matplotlib.patches as patches\nimport tensorflow as tf\nimport pandas as pd\nimport os\nimport six\n\nfrom sklearn.metrics import average_precision_score\n\nfrom keras import backend as K\nfrom keras.optimizers import Adam, SGD, RMSprop\nfrom keras.layers import Flatten, Dense, Input, Conv2D, MaxPooling2D, Dropout\nfrom keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, TimeDistributed\nfrom keras.engine.topology import get_source_inputs\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.objectives import categorical_crossentropy\n\nfrom keras.models import Model\nfrom keras.utils import generic_utils\nfrom keras.engine import Layer, InputSpec\nfrom keras import initializers, regularizers\nimport argparse\nimport datetime\nfrom definitions import *\n\n#TODO: bbox_threshold needs to be defined\n\n\"\"\"Predict Classes\"\"\"\n\ndef predict(C,model_rpn, model_classifier_only, class_mapping,test_base_path,bbox_threshold):\n\n classes = pd.DataFrame(columns=['image','pred_classes'])\n\n img_names = os.listdir(test_base_path)\n\n for img_name in img_names:\n #print('Get classes of {}/{}'.format(idx, len(test_imgs)))\n #img_name = img_path.split('/')[-1]\n #print(image_data['bboxes'])\n\n if not img_name.lower().endswith(('.bmp', '.jpeg', '.jpg', '.png', '.tif', '.tiff')):\n continue\n #print(img_path)\n st = time.time()\n\n '''Predict'''\n img_path = os.path.join(test_base_path, img_name)\n img = cv2.imread(img_path)\n\n X, ratio = format_img(img,C) # X: normiertes Bild (kurze Seite 300 pixel), ratio = 300/Originallänge kurze Seite\n\n X = np.transpose(X, (0, 2, 3, 1))\n\n # get output layer Y1, Y2 from the RPN and the feature maps F\n # Y1: y_rpn_cls\n # Y2: y_rpn_regr\n [Y1, Y2, F] = model_rpn.predict(X)\n\n # Get bboxes by applying NMS\n # R.shape = (300, 4)\n R = rpn_to_roi(Y1, Y2, C, K.image_dim_ordering(), overlap_thresh=0.7)\n\n # convert from (x1,y1,x2,y2) to (x,y,w,h)\n R[:, 2] -= R[:, 0]\n R[:, 3] -= R[:, 1]\n\n # apply the spatial pyramid pooling to the proposed regions\n bboxes = {}\n probs = {}\n\n for jk in range(R.shape[0] // C.num_rois + 1):\n ROIs = np.expand_dims(R[C.num_rois * jk:C.num_rois * (jk + 1), :], axis=0) # num_rois Boxen auswählen\n if ROIs.shape[1] == 0: # wennn ROIs leer, fertig\n break\n\n if jk == R.shape[0] // C.num_rois: # wenn ROIs nicht ganz aufgefüllt, auffüllen\n # pad R\n curr_shape = ROIs.shape\n target_shape = (curr_shape[0], C.num_rois, curr_shape[2])\n ROIs_padded = np.zeros(target_shape).astype(ROIs.dtype)\n ROIs_padded[:, :curr_shape[1], :] = ROIs\n ROIs_padded[0, curr_shape[1]:, :] = ROIs[0, 0, :]\n ROIs = ROIs_padded\n\n [P_cls, P_regr] = model_classifier_only.predict([F, ROIs])\n\n # Calculate bboxes coordinates on resized image\n for ii in range(P_cls.shape[1]):\n\n cls_name = class_mapping[np.argmax(P_cls[0, ii, :])]\n\n # Ignore 'bg' class\n if np.max(P_cls[0, ii, :]) < bbox_threshold[cls_name] or np.argmax(P_cls[0, ii, :]) == (P_cls.shape[2] - 1):\n continue\n\n if cls_name not in bboxes:\n bboxes[cls_name] = []\n probs[cls_name] = []\n\n (x, y, w, h) = ROIs[0, ii, :]\n\n cls_num = np.argmax(P_cls[0, ii, :])\n try:\n (tx, ty, tw, th) = P_regr[0, ii, 4 * cls_num:4 * (cls_num + 1)]\n tx /= C.classifier_regr_std[0]\n ty /= C.classifier_regr_std[1]\n tw /= C.classifier_regr_std[2]\n th /= C.classifier_regr_std[3]\n x, y, w, h = apply_regr(x, y, w, h, tx, ty, tw, th)\n except:\n pass\n bboxes[cls_name].append(\n [C.rpn_stride * x, C.rpn_stride * y, C.rpn_stride * (x + w), C.rpn_stride * (y + h)])\n probs[cls_name].append(np.max(P_cls[0, ii, :]))\n\n\n pred_class_list = [] #contains all predicted class instances\n\n for key in bboxes:\n bbox = np.array(bboxes[key])\n\n new_boxes, new_probs = non_max_suppression_fast(bbox, np.array(probs[key]), overlap_thresh=0.2)\n\n for jk in range(new_boxes.shape[0]):\n pred_class_list.append(key)\n\n\n new_row = {'image': img_name, 'pred_classes': pred_class_list}\n classes = classes.append(new_row, ignore_index=True)\n\n return classes\n\n\n\n\n'''---------------------- main----------------------------'''\n\nif __name__ == '__main__':\n \"\"\"General settings\"\"\"\n parser = argparse.ArgumentParser(description='The following parameters can be assigned:')\n parser.add_argument('--session_name', required=True, type=str)\n parser.add_argument('--base_path', required=True, type=str)\n parser.add_argument('--test_base_path', required=True, type=str)\n parser.add_argument('--out_path', required=True, type=str)\n parser.add_argument('--threshold_path', required=False,default=None, type=str)\n args = parser.parse_args()\n\n base_path = args.base_path # path config and models are stored in\n test_base_path = args.test_base_path # directory containing the pictures that are to predict\n threshold_path = args.threshold_path # path to the thresholds (minimum probability for a class to be output)\n output_path = os.path.join(base_path, 'sessions', args.session_name)\n predict_store_path = os.path.join(args.out_path, \"Prediction on {}\".format(\n datetime.datetime.now().strftime(\"%A, %d %b %Y,%H %M\"))) # path to save output figures in\n classes_path = os.path.join(predict_store_path, 'predicted_classes.csv')\n\n\n print('This is a Prediction Session of ->{}<-.'.format(args.session_name))\n print('Base Path: {}'.format(base_path))\n print('Output: {}'.format(predict_store_path))\n\n\n\n '''Prepare Model'''\n \"\"\"Define Config\"\"\"\n config_output_filename = os.path.join(output_path, 'model', 'model_vgg_config.pickle')\n assert (os.path.exists(\n config_output_filename)), \"Config File {} missing, Check if training has been performed with given session name\".format(\n config_output_filename)\n os.makedirs(predict_store_path)\n\n with open(config_output_filename, 'rb') as f_in:\n C = pickle.load(f_in)\n\n # turn off any data augmentation at test time\n C.use_horizontal_flips = False\n C.use_vertical_flips = False\n C.rot_90 = False\n\n #Load thresholds\n threshold_df = pd.read_csv(threshold_path)\n print(threshold_df)\n threshold=threshold_df.to_dict('index')[0]\n\n print('Using Thresholds of file {}'.format(threshold_path))\n print('Thresholds{}'.format(threshold))\n\n\n # Load the records\n record_df = pd.read_csv(C.record_path)\n\n r_epochs = len(record_df)\n\n num_features = 512\n\n input_shape_img = (None, None, 3)\n input_shape_features = (None, None, num_features)\n\n img_input = Input(shape=input_shape_img)\n roi_input = Input(shape=(C.num_rois, 4))\n feature_map_input = Input(shape=input_shape_features)\n\n # define the base network (VGG here, can be Resnet50, Inception, etc)\n shared_layers = nn_base(img_input, trainable=True)\n\n # define the RPN, built on the base layers\n num_anchors = len(C.anchor_box_scales) * len(C.anchor_box_ratios)\n rpn_layers = rpn_layer(shared_layers, num_anchors)\n\n classifier = classifier_layer(feature_map_input, roi_input, C.num_rois, nb_classes=len(C.class_mapping))\n\n model_rpn = Model(img_input, rpn_layers)\n model_classifier_only = Model([feature_map_input, roi_input], classifier)\n\n model_classifier = Model([feature_map_input, roi_input], classifier)\n\n print('Loading weights from {}'.format(C.model_path))\n model_rpn.load_weights(C.model_path, by_name=True)\n model_classifier.load_weights(C.model_path, by_name=True)\n\n model_rpn.compile(optimizer='sgd', loss='mse')\n model_classifier.compile(optimizer='sgd', loss='mse')\n\n # Switch key value for class mapping\n class_mapping = C.class_mapping\n class_mapping = {v: k for k, v in class_mapping.items()}\n print(class_mapping)\n class_to_color = {class_mapping[v]: np.random.randint(0, 255, 3) for v in class_mapping}\n\n\n '''------------Predict-----------------'''\n\n classes = predict(C,model_rpn, model_classifier_only,class_mapping, test_base_path, threshold)\n classes.to_csv(classes_path,sep=';', index=0)\n\n\n","sub_path":"frcnn_predict.py","file_name":"frcnn_predict.py","file_ext":"py","file_size_in_byte":9096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"239669722","text":"\"\"\"\n优化的目标函数,返回多个目标函数值 \n\"\"\"\nimport numpy as np \n\ndef function(X):\n y1 = 1 - np.exp(-np.sum((X-1/np.sqrt(3))**2)) \n y2 = 1 - np.exp(-np.sum((X+1/np.sqrt(3))**2)) \n return y1, y2 \n\nif __name__ == \"__main__\":\n tX = np.array([-0.57735, -0.57735, -0.57735]) \n print(function(tX))","sub_path":"NSGA2算法python实现/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"180632147","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom pyarrow.compat import unittest\nimport pyarrow as arrow\n\nA = arrow\n\nimport pandas as pd\n\n\nclass TestColumn(unittest.TestCase):\n\n def test_basics(self):\n data = [\n A.from_pylist([-10, -5, 0, 5, 10])\n ]\n table = A.Table.from_arrays(('a'), data, 'table_name')\n column = table.column(0)\n assert column.name == 'a'\n assert column.length() == 5\n assert len(column) == 5\n assert column.shape == (5,)\n assert column.to_pylist() == [-10, -5, 0, 5, 10]\n\n def test_pandas(self):\n data = [\n A.from_pylist([-10, -5, 0, 5, 10])\n ]\n table = A.Table.from_arrays(('a'), data, 'table_name')\n column = table.column(0)\n series = column.to_pandas()\n assert series.name == 'a'\n assert series.shape == (5,)\n assert series.iloc[0] == -10\n\n","sub_path":"python/pyarrow/tests/test_column.py","file_name":"test_column.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"36163201","text":"# System libs\nimport os\nimport time\n# import math\nimport random\nimport argparse\n# Numerical libs\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom scipy.io import loadmat\nfrom scipy.misc import imresize, imsave\n# Our libs\nfrom dataset import GTA, CityScapes, BDD\nfrom models import ModelBuilder\nfrom utils import AverageMeter, colorEncode, accuracy, randomSampler, similiarityPenalty, make_variable, \\\n intersectionAndUnion\nimport hardmining\n\nimport matplotlib\n\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\n# todo: change to gta 2 bdd\n\n\ntrainID2Class = {\n 0: 'road',\n 1: 'sidewalk',\n 2: 'building',\n 3: 'wall',\n 4: 'fence',\n 5: 'pole',\n 6: 'traffic light',\n 7: 'traffic sign',\n 8: 'vegetation',\n 9: 'terrain',\n 10: 'sky',\n 11: 'person',\n 12: 'rider',\n 13: 'car',\n 14: 'truck',\n 15: 'bus',\n 16: 'train',\n 17: 'motorcycle',\n 18: 'bicycle'\n}\n\n\ndef forward_with_loss(nets, batch_data, args, is_train=True, is_adapt=False, epoch=0):\n (net_encoder, net_decoder_1, net_decoder_2, net_syn, crit) = nets\n (imgs, segs, infos) = batch_data\n\n # feed input data\n input_img = Variable(imgs, volatile=not is_train)\n label_seg = Variable(segs, volatile=not is_train)\n input_img = input_img.cuda()\n label_seg = label_seg.cuda()\n\n # forward\n pred_featuremap_1 = net_decoder_1(net_encoder(input_img))\n pred_featuremap_2 = net_decoder_2(net_encoder(input_img))\n pred_featuremap_syn = net_syn(pred_featuremap_1, pred_featuremap_2)\n\n weights1 = net_decoder_1.module.get_weights()\n weights2 = net_decoder_2.module.get_weights()\n\n if is_adapt:\n if args.source_only:\n # do nothing\n err_1 = 0\n err_2 = 0\n err_syn = 0\n else:\n if not args.easy_mining:\n _, pred_1 = torch.max(pred_featuremap_1, 1)\n _, pred_2 = torch.max(pred_featuremap_2, 1)\n _, pred_syn = torch.max(pred_featuremap_syn, 1)\n\n\n err_1 = crit(pred_featuremap_1, pred_syn)\n err_2 = crit(pred_featuremap_2, pred_syn)\n err_syn = 0\n else:\n\n _, pred_1 = torch.max(pred_featuremap_1, 1)\n _, pred_2 = torch.max(pred_featuremap_2, 1)\n _, pred_syn = torch.max(pred_featuremap_syn, 1)\n\n # reshape the feature map as class_num * (batch_size * h * w)\n pred_1 = pred_1.view(1, -1)\n pred_2 = pred_2.view(1, -1)\n pred_syn = pred_syn.view(1, -1)\n\n adapt_idx = (torch.eq(pred_1, pred_2)).squeeze()\n\n # all the rest are ignored indexes\n ignored_idx = (adapt_idx == 0).nonzero().squeeze()\n\n\n\n if len(ignored_idx.size()) > 0:\n pred_syn[..., ignored_idx] = -1\n\n # reshape back to use NLLLoss2d\n pred_syn = pred_syn.view(pred_featuremap_syn.size(0), pred_featuremap_syn.size(2), pred_featuremap_syn.size(3))\n\n if len(adapt_idx.size()) > 0:\n err_1 = crit(pred_featuremap_1, pred_syn)\n err_2 = crit(pred_featuremap_2, pred_syn)\n # err_syn = crit(pred_featuremap_syn, pred_syn)\n err_syn = 0\n else:\n err_1 = 0\n err_2 = 0\n err_syn = 0\n else:\n _, pred_1 = torch.max(pred_featuremap_1, 1)\n _, pred_2 = torch.max(pred_featuremap_2, 1)\n _, pred_syn = torch.max(pred_featuremap_syn, 1)\n\n # reshape the feature map as class_num * (batch_size * h * w)\n pred_1 = pred_1.view(1, -1)\n pred_2 = pred_2.view(1, -1)\n pred_syn = pred_syn.view(1, -1)\n\n label_seg = label_seg.view(1, -1)\n\n adapt_idx = (torch.eq(pred_1, pred_2)).squeeze()\n agreed_idx = (adapt_idx == 1).nonzero().squeeze()\n\n if not args.source_only and args.hard_prob_modifier_handle is not None:\n hard_prob = args.hard_prob_modifier_handle(epoch, args.hard_filtering_final_epoch)\n\n drop_num = int(agreed_idx.size(0) * hard_prob)\n\n if drop_num > 0:\n # randomly shuffle agreed_idx\n shuffle_idx = torch.randperm(agreed_idx.size(0))\n shuffle_idx = Variable(shuffle_idx.cuda(agreed_idx.get_device()))\n agreed_idx = agreed_idx[shuffle_idx]\n agreed_drop_idx = agreed_idx[0:drop_num]\n label_seg[..., agreed_drop_idx] = -1\n\n label_seg = label_seg.view(pred_featuremap_syn.size(0), pred_featuremap_syn.size(2), pred_featuremap_syn.size(3))\n err_1 = crit(pred_featuremap_1, label_seg)\n err_2 = crit(pred_featuremap_2, label_seg)\n err_syn = crit(pred_featuremap_syn, label_seg)\n\n err_sim = similiarityPenalty(weights1.squeeze(), weights2.squeeze())\n\n err = err_1 + err_2 + args.alpha * err_sim + args.beta * err_syn\n\n return pred_featuremap_syn, err\n\n\ndef visualize(batch_data, pred, args):\n colors = loadmat('../colormap.mat')['colors']\n (imgs, segs, infos) = batch_data\n for j in range(len(infos)):\n # get/recover image\n # img = imread(os.path.join(args.root_img, infos[j]))\n img = imgs[j].clone()\n for t, m, s in zip(img,\n [0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225]):\n t.mul_(s).add_(m)\n img = (img.numpy().transpose((1, 2, 0)) * 255).astype(np.uint8)\n\n # segmentation\n lab = segs[j].numpy()\n lab_color = colorEncode(lab, colors)\n\n # prediction\n pred_ = np.argmax(pred.data.cpu()[j].numpy(), axis=0)\n pred_color = colorEncode(pred_, colors)\n\n # aggregate images and save\n im_vis = np.concatenate((img, lab_color, pred_color),\n axis=1).astype(np.uint8)\n imsave(os.path.join(args.vis,\n infos[j].replace('/', '_')), im_vis)\n\n\n# train one epoch\ndef train(nets, loader, loader_adapt, optimizers, history, epoch, args):\n batch_time = AverageMeter()\n data_time = AverageMeter()\n\n # switch to train mode\n for net in nets:\n if not args.fix_bn:\n net.train()\n else:\n net.eval()\n\n # main loop\n tic = time.time()\n # for i, batch_data in enumerate(loader):\n for i in range(args.epoch_iters):\n batch_data, is_adapt = randomSampler(args.ratio_source_init, args.ratio_source_final, \\\n args.ratio_source_final_epoch, epoch, loader, loader_adapt)\n\n data_time.update(time.time() - tic)\n for net in nets:\n net.zero_grad()\n\n # forward pass\n pred, err = forward_with_loss(nets, batch_data, args, is_train=True, is_adapt=is_adapt, epoch=epoch)\n\n # Backward\n err.backward()\n\n for net in nets:\n nn.utils.clip_grad_norm(net.parameters(), 1)\n # for param in net.parameters():\n # print(param.grad.data.shape, param.grad.data.sum())\n\n for optimizer in optimizers:\n optimizer.step()\n\n # measure elapsed time\n batch_time.update(time.time() - tic)\n tic = time.time()\n\n # calculate accuracy, and display\n if i % args.disp_iter == 0:\n acc, _ = accuracy(batch_data, pred)\n\n print('Epoch: [{}][{}/{}], Time: {:.2f}, Data: {:.2f}, '\n 'lr_encoder: {}, lr_decoder: {}, '\n 'Accuracy: {:4.2f}%, Loss: {}'\n .format(epoch, i, args.epoch_iters,\n batch_time.average(), data_time.average(),\n args.lr_encoder, args.lr_decoder,\n acc * 100, err.data[0]))\n\n fractional_epoch = epoch - 1 + 1. * i / args.epoch_iters\n history['train']['epoch'].append(fractional_epoch)\n history['train']['err'].append(err.data[0])\n history['train']['acc'].append(acc)\n\n\ndef evaluate(nets, loader, history, epoch, args):\n print('Evaluating at {} epochs...'.format(epoch))\n loss_meter = AverageMeter()\n acc_meter = AverageMeter()\n intersection_meter = AverageMeter()\n union_meter = AverageMeter()\n\n # switch to eval mode\n for net in nets:\n net.eval()\n\n for i, batch_data in enumerate(loader):\n # forward pass\n torch.cuda.empty_cache()\n pred, err = forward_with_loss(nets, batch_data, args, is_train=False)\n loss_meter.update(err.data[0])\n print('[Eval] iter {}, loss: {}'.format(i, err.data[0]))\n\n # calculate accuracy\n acc, pix = accuracy(batch_data, pred)\n acc_meter.update(acc, pix)\n\n intersection, union = intersectionAndUnion(batch_data, pred,\n args.num_class)\n intersection_meter.update(intersection)\n union_meter.update(union)\n\n # visualization\n visualize(batch_data, pred, args)\n\n iou = intersection_meter.sum / (union_meter.sum + 1e-10)\n for i, _iou in enumerate(iou):\n print('class [{}], IoU: {}'.format(trainID2Class[i], _iou))\n\n print('[Eval Summary]:')\n print('Epoch: {}, Loss: {}, Mean IoU: {:.4}, Accurarcy: {:.2f}%'\n .format(epoch, loss_meter.average(), iou.mean(), acc_meter.average() * 100))\n\n history['val']['epoch'].append(epoch)\n history['val']['err'].append(loss_meter.average())\n history['val']['acc'].append(acc_meter.average())\n history['val']['mIoU'].append(iou.mean())\n\n # Plot figure\n if epoch > 0:\n print('Plotting loss figure...')\n fig = plt.figure()\n plt.plot(np.asarray(history['train']['epoch']),\n np.log(np.asarray(history['train']['err'])),\n color='b', label='training')\n plt.plot(np.asarray(history['val']['epoch']),\n np.log(np.asarray(history['val']['err'])),\n color='c', label='validation')\n plt.legend()\n plt.xlabel('Epoch')\n plt.ylabel('Log(loss)')\n fig.savefig('{}/loss.png'.format(args.ckpt), dpi=200)\n plt.close('all')\n\n fig = plt.figure()\n plt.plot(history['train']['epoch'], history['train']['acc'],\n color='b', label='training')\n plt.plot(history['val']['epoch'], history['val']['acc'],\n color='c', label='validation')\n plt.legend()\n plt.xlabel('Epoch')\n plt.ylabel('Accuracy')\n fig.savefig('{}/accuracy.png'.format(args.ckpt), dpi=200)\n plt.close('all')\n\n\ndef checkpoint(nets, history, args):\n print('Saving checkpoints...')\n (net_encoder, net_decoder_1, net_decoder_2, net_syn, crit) = nets\n suffix_latest = 'latest.pth'\n suffix_best_acc = 'best_acc.pth'\n suffix_best_mIoU = 'best_mIoU.pth'\n suffix_best_err = 'best_err.pth'\n\n if args.num_gpus > 1:\n dict_encoder = net_encoder.module.state_dict()\n dict_decoder_1 = net_decoder_1.module.state_dict()\n dict_decoder_2 = net_decoder_2.module.state_dict()\n dict_syn = net_syn.module.state_dict()\n else:\n dict_encoder = net_encoder.state_dict()\n dict_decoder_1 = net_decoder_1.state_dict()\n dict_decoder_2 = net_decoder_2.state_dict()\n dict_syn = net_syn.state_dict()\n\n torch.save(history,\n '{}/history_{}'.format(args.ckpt, suffix_latest))\n torch.save(dict_encoder,\n '{}/encoder_{}'.format(args.ckpt, suffix_latest))\n torch.save(dict_decoder_1,\n '{}/decoder_1_{}'.format(args.ckpt, suffix_latest))\n torch.save(dict_decoder_2,\n '{}/decoder_2_{}'.format(args.ckpt, suffix_latest))\n torch.save(dict_syn,\n '{}/syn_{}'.format(args.ckpt, suffix_latest))\n\n cur_err = history['val']['err'][-1]\n cur_acc = history['val']['acc'][-1]\n cur_mIoU = history['val']['mIoU'][-1]\n # if cur_err < args.best_err:\n if cur_acc > args.best_acc:\n # save best accuracy instead\n # args.best_err = cur_err\n args.best_acc = cur_acc\n torch.save(history,\n '{}/history_{}'.format(args.ckpt, suffix_best_acc))\n torch.save(dict_encoder,\n '{}/encoder_{}'.format(args.ckpt, suffix_best_acc))\n torch.save(dict_decoder_1,\n '{}/decoder_1_{}'.format(args.ckpt, suffix_best_acc))\n torch.save(dict_decoder_2,\n '{}/decoder_2_{}'.format(args.ckpt, suffix_best_acc))\n torch.save(dict_syn,\n '{}/syn_{}'.format(args.ckpt, suffix_best_acc))\n\n if cur_mIoU > args.best_mIoU:\n # save best accuracy instead\n # args.best_err = cur_err\n args.best_mIoU = cur_mIoU\n torch.save(history,\n '{}/history_{}'.format(args.ckpt, suffix_best_mIoU))\n torch.save(dict_encoder,\n '{}/encoder_{}'.format(args.ckpt, suffix_best_mIoU))\n torch.save(dict_decoder_1,\n '{}/decoder_1_{}'.format(args.ckpt, suffix_best_mIoU))\n torch.save(dict_decoder_2,\n '{}/decoder_2_{}'.format(args.ckpt, suffix_best_mIoU))\n torch.save(dict_syn,\n '{}/syn_{}'.format(args.ckpt, suffix_best_mIoU))\n\n if cur_err < args.best_err:\n args.best_err = cur_err\n torch.save(history,\n '{}/history_{}'.format(args.ckpt, suffix_best_err))\n torch.save(dict_encoder,\n '{}/encoder_{}'.format(args.ckpt, suffix_best_err))\n torch.save(dict_decoder_1,\n '{}/decoder_1_{}'.format(args.ckpt, suffix_best_err))\n torch.save(dict_decoder_2,\n '{}/decoder_2_{}'.format(args.ckpt, suffix_best_err))\n torch.save(dict_syn,\n '{}/syn_{}'.format(args.ckpt, suffix_best_err))\n\n\ndef create_optimizers(nets, args):\n (net_encoder, net_decoder_1, net_decoder_2, net_syn, crit) = nets\n optimizer_encoder = torch.optim.SGD(\n net_encoder.parameters(),\n lr=args.lr_encoder,\n momentum=args.beta1,\n weight_decay=args.weight_decay)\n optimizer_decoder_1 = torch.optim.SGD(\n net_decoder_1.parameters(),\n lr=args.lr_decoder,\n momentum=args.beta1,\n weight_decay=args.weight_decay)\n optimizer_decoder_2 = torch.optim.SGD(\n net_decoder_2.parameters(),\n lr=args.lr_decoder,\n momentum=args.beta1,\n weight_decay=args.weight_decay)\n optimizer_syn = torch.optim.SGD(\n net_syn.parameters(),\n lr=args.lr_decoder,\n momentum=args.beta1,\n weight_decay=args.weight_decay)\n return (optimizer_encoder, optimizer_decoder_1, optimizer_decoder_2, optimizer_syn)\n\n\ndef adjust_learning_rate(optimizers, epoch, args):\n drop_ratio = (1. * (args.num_epoch - epoch) / (args.num_epoch - epoch + 1)) \\\n ** args.lr_pow\n args.lr_encoder *= drop_ratio\n args.lr_decoder *= drop_ratio\n (optimizer_encoder, optimizer_decoder_1, optimizer_decoder_2, optimizer_syn) = optimizers\n for param_group in optimizer_encoder.param_groups:\n param_group['lr'] = args.lr_encoder\n for param_group in optimizer_decoder_1.param_groups:\n param_group['lr'] = args.lr_decoder\n for param_group in optimizer_decoder_2.param_groups:\n param_group['lr'] = args.lr_decoder\n for param_group in optimizer_syn.param_groups:\n param_group['lr'] = args.lr_decoder\n\n\ndef main(args):\n # Network Builders\n builder = ModelBuilder()\n net_encoder = builder.build_encoder(arch=args.arch_encoder,\n fc_dim=args.fc_dim,\n weights=args.weights_encoder)\n net_decoder_1 = builder.build_decoder(arch=args.arch_decoder,\n fc_dim=args.fc_dim,\n num_class=args.num_class,\n weights=args.weights_decoder)\n net_decoder_2 = builder.build_decoder(arch=args.arch_decoder,\n fc_dim=args.fc_dim,\n num_class=args.num_class,\n weights=args.weights_decoder)\n net_syn = builder.build_syn()\n\n if args.weighted_class:\n crit = nn.NLLLoss2d(ignore_index=-1, weight=args.class_weight)\n else:\n crit = nn.NLLLoss2d(ignore_index=-1)\n\n # Dataset and Loader\n dataset_train = CityScapes('train', root=args.root_labeled, cropSize=args.imgSize, is_train=1)\n dataset_adapt = BDD('train', root=args.root_unlabeled, cropSize=args.imgSize, is_train=1)\n dataset_val = BDD('val', root=args.root_unlabeled, cropSize=args.imgSize, max_sample=args.num_val,\n is_train=0)\n loader_train = torch.utils.data.DataLoader(\n dataset_train,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=int(args.workers),\n drop_last=True)\n loader_adapt = torch.utils.data.DataLoader(\n dataset_adapt,\n batch_size=args.batch_size,\n shuffle=True,\n num_workers=int(args.workers),\n drop_last=True)\n loader_val = torch.utils.data.DataLoader(\n dataset_val,\n batch_size=args.batch_size_eval,\n shuffle=False,\n num_workers=int(args.workers),\n drop_last=True)\n args.epoch_iters = int(len(dataset_train) / args.batch_size)\n print('1 Epoch = {} iters'.format(args.epoch_iters))\n\n # load nets into gpu\n if args.num_gpus > 1:\n net_encoder = nn.DataParallel(net_encoder,\n device_ids=range(args.num_gpus))\n net_decoder_1 = nn.DataParallel(net_decoder_1,\n device_ids=range(args.num_gpus))\n net_decoder_2 = nn.DataParallel(net_decoder_2,\n device_ids=range(args.num_gpus))\n net_syn = nn.DataParallel(net_syn,\n device_ids=range(args.num_gpus))\n\n nets = (net_encoder, net_decoder_1, net_decoder_2, net_syn, crit)\n for net in nets:\n net.cuda()\n\n # Set up optimizers\n optimizers = create_optimizers(nets, args)\n\n # Main loop\n history = {split: {'epoch': [], 'err': [], 'acc': [], 'mIoU': []}\n for split in ('train', 'val')}\n\n # optional initial eval\n # evaluate(nets, loader_val, history, 0, args)\n for epoch in range(1, args.num_epoch + 1):\n train(nets, loader_train, loader_adapt, optimizers, history, epoch, args)\n\n # Evaluation and visualization\n if epoch % args.eval_epoch == 0:\n evaluate(nets, loader_val, history, epoch, args)\n\n # checkpointing\n checkpoint(nets, history, args)\n\n # adjust learning rate\n adjust_learning_rate(optimizers, epoch, args)\n\n print('Training Done!')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n # Model related arguments\n parser.add_argument('--id', default='adapt',\n help=\"a name for identifying the model\")\n parser.add_argument('--arch_encoder', default='resnet34_dilated8',\n help=\"architecture of net_encoder\")\n parser.add_argument('--arch_decoder', default='psp_bilinear',\n help=\"architecture of net_decoder\")\n parser.add_argument('--weights_encoder',\n default='/home/selfdriving/kchitta/Domain-Adapatation/segmentation/pretrained/encoder_best.pth',\n help=\"weights to finetune net_encoder\")\n parser.add_argument('--weights_decoder',\n default='/home/selfdriving/kchitta/Domain-Adapatation/segmentation/pretrained/decoder_best.pth',\n help=\"weights to finetune net_decoder\")\n parser.add_argument('--fc_dim', default=512, type=int,\n help='number of features between encoder and decoder')\n\n # Path related arguments\n parser.add_argument('--root_unlabeled',\n default='/home/selfdriving/datasets/bdd100k')\n parser.add_argument('--root_labeled',\n default='/home/selfdriving/datasets/cityscapes_full')\n\n # optimization related arguments\n parser.add_argument('--num_gpus', default=3, type=int,\n help='number of gpus to use')\n parser.add_argument('--batch_size_per_gpu', default=2, type=int,\n help='input batch size')\n parser.add_argument('--batch_size_per_gpu_eval', default=1, type=int,\n help='eval batch size')\n parser.add_argument('--num_epoch', default=20, type=int,\n help='epochs to train for')\n parser.add_argument('--ratio_source_init', default=0.9, type=float,\n help='initial sampling ratio for source domain')\n parser.add_argument('--ratio_source_final', default=0.1, type=float,\n help='final sampling ratio for source domain')\n parser.add_argument('--ratio_source_final_epoch', default=10, type=int,\n help='epoch beyond which to maintain final ratio')\n\n parser.add_argument('--optim', default='SGD', help='optimizer')\n parser.add_argument('--lr_encoder', default=1e-3, type=float, help='LR')\n parser.add_argument('--lr_decoder', default=1e-2, type=float, help='LR')\n parser.add_argument('--lr_pow', default=0.9, type=float,\n help='power in poly to drop LR')\n parser.add_argument('--alpha', default=0.01, type=float,\n help='weight of similarity loss')\n parser.add_argument('--beta', default=1, type=float,\n help='weight of synthetic loss')\n parser.add_argument('--beta1', default=0.9, type=float,\n help='momentum for sgd, beta1 for adam')\n parser.add_argument('--weight_decay', default=1e-4, type=float,\n help='weights regularizer')\n parser.add_argument('--fix_bn', default=0, type=int,\n help='fix bn params')\n\n # Data related arguments\n parser.add_argument('--num_val', default=-1, type=int,\n help='number of images to evaluate')\n parser.add_argument('--num_class', default=19, type=int,\n help='number of classes')\n parser.add_argument('--workers', default=1, type=int,\n help='number of data loading workers')\n parser.add_argument('--imgSize', default=600, type=int,\n help='input image size')\n parser.add_argument('--segSize', default=600, type=int,\n help='output image size')\n\n # Misc arguments\n parser.add_argument('--seed', default=1337, type=int, help='manual seed')\n parser.add_argument('--ckpt', default='./city2bdd_ckpt',\n help='folder to output checkpoints')\n parser.add_argument('--vis', default='./vis',\n help='folder to output visualization during training')\n parser.add_argument('--disp_iter', type=int, default=20,\n help='frequency to display')\n parser.add_argument('--eval_epoch', type=int, default=1,\n help='frequency to evaluate')\n\n # Mode select\n parser.add_argument('--source_only', default=False, type=bool, help='set True to do source only training')\n parser.add_argument('--easy_mining', default=True, type=bool, help='set True to do easy mining')\n parser.add_argument('--hard_mining', default=True, type=bool, help='set True to do hard mining')\n parser.add_argument('--weighted_class', default=True, type=bool, help='set True to use weighted class')\n\n args = parser.parse_args()\n print(\"Input arguments:\")\n for key, val in vars(args).items():\n print(\"{:16} {}\".format(key, val))\n\n args.batch_size = args.num_gpus * args.batch_size_per_gpu\n args.batch_size_eval = args.batch_size_per_gpu_eval\n\n # Specify certain arguments\n if not args.source_only:\n if args.hard_mining:\n args.hard_filtering_init = 0\n args.hard_filtering_final = 1\n args.hard_filtering_final_epoch = 10\n # assign actual function handle\n args.hard_prob_modifier_handle = hardmining.linearModifier\n else:\n args.hard_prob_modifier_handle = None\n\n\n if args.weighted_class:\n args.enhanced_weight = 2.0\n args.class_weight = np.ones([19], dtype=np.float32)\n enhance_class = [1, 3, 4, 5, 6, 7, 12]\n args.class_weight[enhance_class] = args.enhanced_weight\n args.class_weight = torch.from_numpy(args.class_weight.astype(np.float32))\n\n\n\n\n args.id += '-' + str(args.arch_encoder)\n args.id += '-' + str(args.arch_decoder)\n args.id += '-ngpus' + str(args.num_gpus)\n args.id += '-batchSize' + str(args.batch_size)\n args.id += '-imgSize' + str(args.imgSize)\n args.id += '-lr_encoder' + str(args.lr_encoder)\n args.id += '-lr_decoder' + str(args.lr_decoder)\n args.id += '-epoch' + str(args.num_epoch)\n args.id += '-ratio' + str(args.ratio_source_init) + '-' + str(args.ratio_source_final) + '-' + str(\n args.ratio_source_final_epoch)\n args.id += '-alpha' + str(args.alpha)\n args.id += '-beta' + str(args.beta)\n args.id += '-decay' + str(args.weight_decay)\n if args.weighted_class:\n args.id += '-weighted' + str(args.enhanced_weight)\n if args.source_only:\n args.id += '-source_only'\n else:\n args.id += '-adapt'\n if args.easy_mining:\n args.id += '-easy_mining'\n if args.hard_mining:\n args.id += '-hard_mining'\n\n\n print('Model ID: {}'.format(args.id))\n\n args.ckpt = os.path.join(args.ckpt, args.id)\n args.vis = os.path.join(args.vis, args.id)\n if not os.path.isdir(args.ckpt):\n os.makedirs(args.ckpt)\n if not os.path.exists(args.vis):\n os.makedirs(args.vis)\n\n args.best_err = 2.e10 # initialize with a big number\n args.best_acc = 0\n args.best_mIoU = 0\n\n\n\n random.seed(args.seed)\n torch.manual_seed(args.seed)\n\n main(args)\n","sub_path":"segmentation/filtered-gradients/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":26200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"640524454","text":"\"\"\"\nService http://ad-social.org\nSupported targets: vk.com\n\"\"\"\nimport datetime\nimport re\nfrom bs4 import BeautifulSoup\nfrom .service import Service, ServiceError\n\n\nclass AdsocialService(Service):\n \"\"\" Service http://ad-social.org \"\"\"\n\n DOMAIN = 'ad-social.org'\n # Target dependant data.\n TDATA = {\n 'vk.com': {\n 'path': 'vkontakte',\n }\n }\n\n def login(self):\n \"\"\"\n Log in to service (using ulogin).\n \"\"\"\n # Get vk oauth form.\n url = 'https://ulogin.ru/auth.php?name=vkontakte&fields=photo_big'\n response = self.session.get(url)\n root = BeautifulSoup(response.text, 'lxml')\n form = root.find('form')\n\n # Post vk credentials and get ulogin token.\n url = form['action']\n data = {ninput.get('name', ''): ninput.get('value', '') for ninput in\n form.find_all('input')}\n data['email'] = self.username\n data['pass'] = self.password\n response = self.session.post(url, data=data)\n match = re.search(r'''token\\s*=\\s*['\"](\\w+)['\"]\\s*''', response.text)\n if match is None:\n raise ServiceError(\"Login failed: ulogin token is not found.\")\n token = match.group(1)\n self.logger.info('ulogin token = \"%s\"', token)\n\n # Log into service.\n url = 'http://ad-social.org/vk/social2/login'\n response = self.session.post(url,\n data={'token': token},\n allow_redirects=False)\n if response.status_code != 303:\n raise ServiceError(\"Incorrect status code.\")\n\n def get_tasks(self):\n \"\"\"Return list of available tasks.\"\"\"\n url = 'http://ad-social.org/vk/earn?type=like'\n response = self.session.get(url)\n root = BeautifulSoup(response.text, 'lxml')\n\n # Real id is fakeid / multiplier. Find multiplier.\n for script in root.find_all('script'):\n match = re.search(r'var id_2\\s*=\\s*id\\s*/\\s*(\\d+)\\s*;?\\s*if',\n script.text)\n if match is not None:\n multiplier = int(match.group(1))\n break\n else:\n raise ServiceError('Fakeid multiplier is not found.')\n\n # Get tasks.\n tasks = []\n trs = root.find_all(\n 'tr',\n {'class': lambda attr: attr.startswith('task')})\n for tr in trs:\n points = tr.find('span', {'class': 'label-primary'}).text\n points = int(points.split(maxsplit=1)[0])\n fakeid = int(tr['class'][0][4:])\n realid, remain = divmod(fakeid, multiplier)\n if remain != 0:\n raise ServiceError('Incorrect multiplier.')\n\n task = {\n '_id': realid,\n 'points': points,\n 'type': 'like',\n 'date': datetime.datetime.utcnow(),\n }\n tasks.append(task)\n return tasks\n\n def get_task_url(self, task):\n \"\"\"\n Return url at service domain, which leads to task at target domain.\n \"\"\"\n return 'http://ad-social.org/vk/earn/get/' + str(task['_id'])\n\n def check_task(self, task):\n \"\"\"\n Ask service to check the task.\n Return True if service confirmed task completion.\n \"\"\"\n url = 'http://ad-social.org/vk/earn/checkTask/' \\\n + str(task['_id']) + '/like'\n headers = {'X-Requested-With': 'XMLHttpRequest'}\n response = self.session.get(url, headers=headers)\n json_data = response.json()\n\n return json_data['status']\n","sub_path":"makepts/makeptslib/service/adsocial.py","file_name":"adsocial.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"581585971","text":"\"\"\" Integration and unit tests for the SR algorithm. \"\"\"\nfrom matching.games.stable_roommates import (\n first_phase,\n locate_all_or_nothing_cycle,\n second_phase,\n stable_roommates,\n)\n\nfrom .params import STABLE_ROOMMATES, make_players\n\n\n@STABLE_ROOMMATES\ndef test_first_phase(player_names, seed):\n \"\"\"Verify that the first phase of the algorithm produces a valid set of\n reduced preference players.\"\"\"\n\n players = make_players(player_names, seed)\n players = first_phase(players)\n\n for player in players:\n assert player.matching is None\n assert {p.name for p in player.prefs}.issubset(player.pref_names)\n\n\n@STABLE_ROOMMATES\ndef test_locate_all_or_nothing_cycle(player_names, seed):\n \"\"\"Verify that a cycle of (least-preferred, second-choice) players can be\n identified from a set of players.\"\"\"\n\n players = make_players(player_names, seed)\n player = players[-1]\n cycle = locate_all_or_nothing_cycle(player)\n\n for last, second in cycle:\n assert second.prefs.index(last) == len(second.prefs) - 1\n\n\n@STABLE_ROOMMATES\ndef test_second_phase(player_names, seed):\n \"\"\"Verify that the second phase of the algorithm produces a valid set of\n players with appropriate matches.\"\"\"\n\n players = make_players(player_names, seed)\n try:\n players = second_phase(players)\n\n for player in players:\n if player.prefs:\n assert player.prefs == [player.matching]\n else:\n assert player.matching is None\n except (IndexError, ValueError):\n pass\n\n\n@STABLE_ROOMMATES\ndef test_stable_roommates(player_names, seed):\n \"\"\" Verify that the algorithm can terminate with a valid matching. \"\"\"\n\n players = make_players(player_names, seed)\n matching = stable_roommates(players)\n\n for player, other in matching.items():\n if other is not None:\n assert player.prefs == [other]\n assert other.matching == player\n","sub_path":"tests/stable_roommates/test_algorithm.py","file_name":"test_algorithm.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"642406004","text":"from telegram.ext import Updater, PicklePersistence, messagequeue as mq\n# from telegram.utils.request import Request\n\nfrom app.bot import MQBot\nfrom settings.config import TG_TOKEN\nfrom app.handlers import main, proccess_images\n\n\ndef run():\n # request = Request(con_pool_size=16)\n mqbot = MQBot(\n token=TG_TOKEN,\n # request=request,\n mqueue=mq.MessageQueue(),\n )\n updater = Updater(\n bot=mqbot,\n use_context=True,\n persistence=PicklePersistence(filename='persistent_data')\n )\n dp = updater.dispatcher\n\n main.register(dp=dp)\n proccess_images.register(dp=dp)\n updater.start_polling()\n updater.idle()\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"382857614","text":"import json\nimport requests\nimport urllib\n\n# SPARCS SSO Client Version 0.9.0 (BETA)\n# VALID ONLY AFTER 2016-01-28T12:59+09:00\n# Made by SPARCS SSO Team\n\nclass Client:\n API_BASE_URL = 'https://sparcssso.kaist.ac.kr/api/v1/'\n REQUIRE_BASE_URL = '%stoken/require/' % API_BASE_URL\n INFO_BASE_URL = '%stoken/info/' % API_BASE_URL\n POINT_BASE_URL = '%spoint/' % API_BASE_URL\n NOTICE_BASE_URL = '%snotice/' % API_BASE_URL\n\n def __init__(self, is_test=False, app_name='', secret_key=''):\n if not is_test and (not app_name or not secret_key):\n raise AssertionError('Need \"app_name\" and \"secret_key\"')\n\n self.is_test = is_test\n self.app_name = app_name\n self.secret_key = secret_key\n\n def _post_data(self, url, data):\n r = requests.post(url, data)\n if r.status_code == 403:\n raise ValueError('Invalid secret key')\n elif r.status_code == 404:\n raise ValueError('Invalid / timeout token')\n elif r.status_code != 200:\n raise RuntimeError('Unknown server error')\n\n try:\n return json.loads(r.text)\n except:\n raise RuntimeError('Json decode error')\n\n def get_login_url(self, callback_url=''):\n if self.is_test and not callback_url:\n raise AssertionError('Need \"callback_url\"')\n\n if self.is_test:\n return '%s?url=%s' % (self.REQUIRE_BASE_URL, callback_url)\n return '%s?app=%s' % (self.REQUIRE_BASE_URL, self.app_name)\n\n def get_user_info(self, tokenid):\n result = self._post_data(self.INFO_BASE_URL,\n {\n 'tokenid': tokenid,\n 'key': self.secret_key\n })\n return result\n\n def get_point(self, sid):\n if self.is_test:\n raise NotImplementedError('Not supported on test mode')\n\n result = self._post_data(self.POINT_BASE_URL,\n {\n 'app': self.app_name,\n 'key': self.secret_key,\n 'sid': sid\n })\n return result['point']\n\n def modify_point(self, sid, delta, action, lower_bound=-100000000):\n if self.is_test:\n raise NotImplementedError('Not supported on test mode')\n\n result = self._post_data(self.POINT_BASE_URL,\n {\n 'app': self.app_name,\n 'key': self.secret_key,\n 'sid': sid,\n 'delta': delta,\n 'action': action,\n 'lower_bound': lower_bound\n })\n return result['changed'], result['point']\n\n def get_notice(self):\n return json.load(urllib.urlopen(self.NOTICE_BASE_URL))\n","sub_path":"apps/session/sparcssso.py","file_name":"sparcssso.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"304373197","text":"# Izveidot programmu, kura prasa lietotājam ievadīt cilindra rādiusu un tā augstumu, tiek aprēķināts cilindra laukums un tilpums. Rezultāts tiek parādīts konsolē.\n# tilpums = 3.14 * rādiuss * rādiuss * augstums\n# laukums = 2 * (3.14 * rādiuss * rādiuss) + augstums * (2 * 3.14 * rādiuss)\n\nh = int(input(\"Enter the height: \"))\nr = int(input(\"Enter the radius: \"))\n\npi = 3.14\nvol = pi * r**2 * h\narea = 2 * pi * r**2 + h * 2 * pi *r\n\nprint(\"Volume: \", vol)\nprint(\"Area: \", area)","sub_path":"uzd_01_20201210/uzd_01_2.py","file_name":"uzd_01_2.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"386798457","text":"\nimport re, util, json, csv\nfrom BeautifulSoup import BeautifulStoneSoup\nfrom StringIO import StringIO\n\ndef dictsToCsv(dicts, filename):\n keys = []\n for dict in dicts:\n for key in dict.keys():\n if not keys.__contains__(key):\n keys.append(key)\n \n #print(keys)\n \n finalList = []\n \n for dict in dicts:\n entry = []\n for key in keys:\n val = dict.get(key)\n if not val == None:\n entry.append(val)\n else:\n entry.append(\"\")\n finalList.append(entry) \n \n #print(finalList) \n \n \n file = open(filename, \"w\")\n writer = csv.writer(file)\n writer.writerow(keys)\n writer.writerows(finalList)\n file.close()\n \n\n\nlistFile = open('rooms.txt', 'r')\nlines = listFile.readlines()\n\nbaseUrl = \"http://ims.fas.harvard.edu/classrooms/room.php?rm=rm\"\n\nio = StringIO()\n\n# Open file for writing\nfile = open('output.txt', 'w')\nrooms = []\n\nfor line in lines:\n room = {}\n url = baseUrl + line[:4]\n soup = util.mysoupopen(url)\n \n bldg = soup.findAll(\"h1\")\n room['id'] = line[:4]\n room['bldg'] = bldg[0].contents[0].strip()\n room['room'] = bldg[0].contents[3].contents[0]\n \n table = soup.findAll(\"table\")\n table = table[0]\n #print(table.contents)\n for row in table.contents:\n if row != u'\\n':\n prop = row.contents[0].contents[0].strip().strip(\":\")\n m = re.search(\"([^<]*)\", str(row.contents[1]))\n val = m.group(1)\n room[prop] = val\n\n photo = soup.find(\"img\", {\"id\":\"room_photo\"})\n photo = photo[\"src\"]\n \n if photo == \"http://www.fas.harvard.edu/~ims/Class/images/nophoto.jpg\":\n photo = \"\"\n \n room['photo'] = photo\n rooms.append(room)\n print(room) \n\nfile.close()\n\ndictsToCsv(rooms, \"rooms.csv\")\n\n\n","sub_path":"roomspot-python/src/scraper/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"398544334","text":"# -*- coding: utf-8 -*-\n##############################################################################\n# \n# Author: Alessandro Camilli (alessandrocamilli@openforce.it)\n# Copyright (C) 2014\n# Openforce ()\n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp.osv import orm, fields\nfrom openerp.tools.translate import _\nimport openerp.addons.decimal_precision as dp\nfrom openerp import netsvc\n\n\nclass account_move_line(orm.Model):\n _inherit = \"account.move.line\"\n _columns = {\n 'withholding_tax_amount': fields.float('Withholding Tax Amount'),\n }\n \nclass account_voucher(orm.Model):\n _inherit = \"account.voucher\"\n \n def recompute_voucher_lines(self, cr, uid, ids, partner_id, journal_id, price, currency_id, ttype, date, context=None):\n '''\n Compute original amount of WT of rate\n '''\n move_line_obj = self.pool['account.move.line']\n voucher_line_obj = self.pool['account.voucher.line']\n dp_obj = self.pool['decimal.precision']\n res = super(account_voucher, self).recompute_voucher_lines(cr, uid, ids, \n partner_id,\n journal_id,\n price,\n currency_id,\n ttype, date,\n context=context)\n def _compute_wt_values(lines):\n amount_overflow_residual = 0.0\n # For each line, WT\n for line in lines:\n if 'move_line_id' in line and line['move_line_id']:\n move_line = move_line_obj.browse(cr, uid, line['move_line_id'])\n line['amount_original_withholding_tax'] = move_line.withholding_tax_amount\n line['amount_residual_withholding_tax']= \\\n voucher_line_obj.compute_amount_residual_withholdin_tax(cr, uid, \n line, \n context=None)\n # Recompute automatic values on amount: \n # The amount_residual_currency on account_move_line, doesn't see the WT values\n if lines and lines[0]['amount']:\n # For each amount to redistribuite\n tot_amount = 0\n for line in lines:\n tot_amount += line['amount'] + line['amount_residual_withholding_tax']\n \n # Redistribuite amount\n for line in lines:\n if tot_amount <= 0:\n break\n if line['amount'] > (line['amount_unreconciled'] - line['amount_residual_withholding_tax']):\n line['amount'] = line['amount_unreconciled'] - line['amount_residual_withholding_tax']\n line['amount'] = round(line['amount'], dp_obj.precision_get(cr, uid, 'Account'))\n tot_amount -= line['amount'] \n # Allocate WT \n for line in lines:\n if 'move_line_id' in line and line['move_line_id']:\n move_line = move_line_obj.browse(cr, uid, line['move_line_id'])\n if line['amount'] or amount_overflow_residual:\n # Assign overflow from other lines\n if amount_overflow_residual:\n if (line['amount'] + amount_overflow_residual) <= (line['amount_unreconciled'] - line['amount_residual_withholding_tax']):\n line['amount'] += amount_overflow_residual\n amount_overflow_residual = 0.0\n else:\n line['amount'] = line['amount_unreconciled'] - line['amount_residual_withholding_tax']\n # Compute WT\n line['amount_withholding_tax']= \\\n voucher_line_obj.compute_amount_withholdin_tax(cr, uid, line['amount'],\n line['amount_unreconciled'], \n line['amount_residual_withholding_tax'], \n context=None)\n # WT can generate an overflow. It will bw assigned to next line\n amount_overflow = line['amount'] + line['amount_withholding_tax'] - line['amount_unreconciled']\n if amount_overflow > 0 :\n line['amount'] -= amount_overflow\n amount_overflow_residual += amount_overflow\n line['amount_original'] -= line['amount_original_withholding_tax']\n \n return lines\n if partner_id:\n lines_dr = res['value']['line_dr_ids']\n lines_dr = _compute_wt_values(lines_dr)\n lines_cr = res['value']['line_cr_ids']\n lines_cr = _compute_wt_values(lines_cr)\n \n return res\n \n def voucher_move_line_create(self, cr, uid, voucher_id, line_total, move_id, company_currency, current_currency, context=None):\n '''\n Add WT line to registration and change amount on debit/credit line of the invoice \n '''\n move_line_obj = self.pool['account.move.line']\n voucher_line_obj = self.pool['account.voucher.line']\n payment_term_obj = self.pool['account.payment.term']\n reconcile_obj = self.pool['account.move.reconcile']\n line_total, rec_list_ids = super(account_voucher, self).voucher_move_line_create(cr, uid,\n voucher_id,\n line_total,\n move_id,\n company_currency,\n current_currency, \n context=context)\n def _unreconcile_move_line(move_line):\n '''\n Remove reconciliation to change amounts\n '''\n recs = []\n recs_to_rereconcile = []\n if move_line.reconcile_id:\n recs += [move_line.reconcile_id.id]\n if move_line.reconcile_partial_id:\n recs += [move_line.reconcile_partial_id.id]\n # If there are other partial payments, I save the id line to future reconcile\n cr.execute('SELECT id FROM account_move_line WHERE reconcile_partial_id=%s \\\n AND id <> %s', \n (move_line.reconcile_partial_id.id, move_line.id))\n for l in cr.dictfetchall():\n recs_to_rereconcile.append(l['id'])\n reconcile_obj.unlink(cr, uid, recs)\n return recs_to_rereconcile\n \n # rec_list_ids id payment move line with invoice move_line to reconcile\n rec_list_new_moves = []\n for rec in rec_list_ids:\n line_move_to_pay = move_line_obj.browse(cr, uid, rec[1])\n line_payment = move_line_obj.browse(cr, uid, rec[0])\n # Remove reconciliation to change amounts\n lines_to_rereconcile = _unreconcile_move_line(line_move_to_pay)\n for r_line_id in lines_to_rereconcile:\n rec_list_new_moves.append([r_line_id, line_move_to_pay.id])\n _unreconcile_move_line(line_payment)\n # line voucher with WT\n domain = [('voucher_id', '=', voucher_id), ('move_line_id', '=', line_move_to_pay.id)]\n v_line_payment_ids = voucher_line_obj.search(cr, uid, domain)\n for v_line in voucher_line_obj.browse(cr, uid, v_line_payment_ids):\n voucher = v_line.voucher_id\n for wt_v_line in v_line.withholding_tax_line_ids:\n credit = 0.0\n debit = 0.0\n if v_line.move_line_id.debit:\n debit = wt_v_line.amount\n else:\n credit = wt_v_line.amount\n # account\n if line_move_to_pay.account_id.type == 'receivable':\n wt_account_id = wt_v_line.withholding_tax_id.account_receivable_id.id\n else:\n wt_account_id = wt_v_line.withholding_tax_id.account_payable_id.id\n # Line WT\n payment_lines = payment_term_obj.compute(cr,\n uid, wt_v_line.withholding_tax_id.payment_term.id, wt_v_line.amount,\n voucher.date or False, context=context)\n line_wt_ids = []\n for payment_line in payment_lines:\n p_date_maturity = payment_line[0]\n p_credit = 0.0\n p_debit = 0.0\n if debit:\n p_debit = payment_line[1]\n else:\n p_credit = payment_line[1]\n val_move_line = {\n 'journal_id': voucher.journal_id.id,\n 'period_id': voucher.period_id.id,\n #'name': wt_v_line.withholding_tax_id.name or '/',\n 'name': wt_v_line.withholding_tax_id.name + ' ' + voucher.partner_id.name or '/',\n 'account_id': wt_account_id,\n 'move_id': move_id,\n #'partner_id': voucher.partner_id.id,\n 'partner_id': False,\n 'currency_id': v_line.move_line_id.currency_id.id or False,\n 'analytic_account_id': v_line.account_analytic_id and v_line.account_analytic_id.id or False,\n 'quantity': 1,\n 'credit': p_credit,\n 'debit': p_debit,\n 'date': voucher.date,\n 'date_maturity': p_date_maturity\n }\n line_wt_id = move_line_obj.create(cr, uid, val_move_line)\n line_wt_ids.append(line_wt_id)\n \n # Add amount WT to line debit/credit partner\n val = {\n 'credit': line_payment.credit + debit,\n 'debit': line_payment.debit + credit\n }\n move_line_obj.write(cr, uid, [line_payment.id], val)\n \n # Merge with existing lines to reconcile\n if rec_list_new_moves:\n for rec_new in rec_list_new_moves:\n for rec_ids in rec_list_ids:\n if not rec_new[1] == rec_ids[1]:\n continue\n rec_ids.append(rec_new[0])\n \n return (line_total, rec_list_ids)\n \n \nclass account_voucher_line(orm.Model):\n _inherit = \"account.voucher.line\"\n \n def _amount_withholding_tax(self, cr, uid, ids, name, args, context=None):\n res = {}\n for line in self.browse(cr, uid, ids, context=context):\n res[line.id] = {\n 'amount_original_withholding_tax': 0.0,\n }\n res[line.id]['amount_original_withholding_tax'] += line.move_line_id.withholding_tax_amount\n return res\n \n def _compute_balance(self, cr, uid, ids, name, args, context=None):\n '''\n Extends the compute of original amounts for exclude from total the WT amount\n '''\n currency_pool = self.pool.get('res.currency')\n rs_data = {}\n for line in self.browse(cr, uid, ids, context=context):\n ctx = context.copy()\n ctx.update({'date': line.voucher_id.date})\n voucher_rate = self.pool.get('res.currency').read(cr, uid, line.voucher_id.currency_id.id, ['rate'], context=ctx)['rate']\n ctx.update({\n 'voucher_special_currency': line.voucher_id.payment_rate_currency_id and line.voucher_id.payment_rate_currency_id.id or False,\n 'voucher_special_currency_rate': line.voucher_id.payment_rate * voucher_rate})\n res = {}\n company_currency = line.voucher_id.journal_id.company_id.currency_id.id\n voucher_currency = line.voucher_id.currency_id and line.voucher_id.currency_id.id or company_currency\n move_line = line.move_line_id or False\n\n if not move_line:\n res['amount_original'] = 0.0\n res['amount_unreconciled'] = 0.0\n res['amount_withholding_tax'] = 0.0\n elif move_line.currency_id and voucher_currency==move_line.currency_id.id:\n res['amount_original'] = abs(move_line.amount_currency - move_line.withholding_tax_amount) # modify for WT\n res['amount_unreconciled'] = abs(move_line.amount_residual_currency)\n else:\n #always use the amount booked in the company currency as the basis of the conversion into the voucher currency\n res['amount_original'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, move_line.credit or move_line.debit or 0.0, context=ctx)\n res['amount_unreconciled'] = currency_pool.compute(cr, uid, company_currency, voucher_currency, abs(move_line.amount_residual), context=ctx)\n res['amount_original'] -= move_line.withholding_tax_amount # add for WT\n \n rs_data[line.id] = res\n return rs_data\n \n _columns = {\n 'amount_original': fields.function(_compute_balance, multi='dc', type='float', string='Original Amount', store=True, digits_compute=dp.get_precision('Account')),\n 'amount_original_withholding_tax': fields.function(_amount_withholding_tax, \n digits_compute=dp.get_precision('Account'), string='Withholding Tax Original', multi='withholding_tax'),\n 'amount_residual_withholding_tax': fields.float('Withholding Tax Amount Residual'),\n 'amount_withholding_tax': fields.float('Withholding Tax Amount'),\n 'withholding_tax_line_ids': fields.one2many('withholding.tax.voucher.line', 'voucher_line_id', 'Withholding Tax Lines'),\n }\n \n def onchange_amount(self, cr, uid, ids, amount, amount_unreconciled, amount_residual_withholding_tax, context=None):\n res = super(account_voucher_line, self).onchange_amount(cr, uid, ids, \n amount, \n amount_unreconciled, \n context=context)\n dp_obj = self.pool['decimal.precision']\n wt_amount = self.compute_amount_withholdin_tax(cr, uid, amount, amount_unreconciled, amount_residual_withholding_tax, context)\n res['value'].update({'amount_withholding_tax': wt_amount})\n \n # Setting for Total amount\n if (amount + wt_amount) >= round(amount_unreconciled,dp_obj.precision_get(cr, uid, 'Account')):\n res['value'].update({'reconcile': True})\n res['value'].update({'amount': amount})\n\n return res\n \n def onchange_reconcile(self, cr, uid, ids, reconcile, amount, \n amount_unreconciled, \n amount_residual_withholding_tax, \n context=None):\n '''\n TO CONSIDER: Amount tot = amount net + amount WT \n '''\n res = super(account_voucher_line, self).onchange_reconcile(cr, uid, ids, \n reconcile,\n amount, \n amount_unreconciled, \n context=context)\n if reconcile: \n amount = amount_unreconciled\n wt_amount = self.compute_amount_withholdin_tax(cr, uid, amount, amount_unreconciled, amount_residual_withholding_tax, context)\n res['value']['amount'] = amount - wt_amount\n return res\n \n def compute_amount_residual_withholdin_tax(self, cr, uid, line, context=None):\n '''\n WT residual = WT amount original - (All WT amounts in voucher posted)\n '''\n dp_obj = self.pool['decimal.precision']\n wt_amount_residual = 0.0\n if not 'move_line_id' in line or not line['move_line_id']:\n return wt_amount_residual\n domain = [('move_line_id', '=', line['move_line_id'])]\n v_line_ids = self.search(cr, uid, domain)\n wt_amount_residual = line['amount_original_withholding_tax']\n for v_line in self.browse(cr, uid, v_line_ids):\n if v_line.voucher_id.state == 'posted':\n wt_amount_residual -= v_line.amount_withholding_tax\n \n return wt_amount_residual\n \n def compute_amount_withholdin_tax(self, cr, uid, amount, amount_unreconciled, wt_amount_residual, context=None):\n dp_obj = self.pool['decimal.precision']\n wt_amount = 0.0\n # Total amount\n amount_tot = amount + wt_amount_residual\n base_amount = amount_unreconciled - wt_amount_residual\n if amount_tot >= round(amount_unreconciled,dp_obj.precision_get(cr, uid, 'Account')):\n wt_amount = wt_amount_residual\n # Partial amount ( ratio with amount net)\n else:\n wt_amount = round(wt_amount_residual * (1.0 * amount / base_amount),\\\n dp_obj.precision_get(cr, uid, 'Account'))\n return wt_amount\n \n def recompute_withholding_tax_voucher_line(self, cr, uid, voucher_line_id, context=None):\n '''\n Split amount voucher line second WT lines invoice\n '''\n res = []\n invoice_obj = self.pool['account.invoice']\n wt_voucher_line_obj = self.pool['withholding.tax.voucher.line']\n dp_obj = self.pool['decimal.precision']\n \n voucher_line = self.browse(cr, uid, voucher_line_id)\n # delete existing wt lines\n domain = [('voucher_line_id', '=', voucher_line_id)]\n wtv_line_ids = wt_voucher_line_obj.search(cr, uid, domain)\n wt_voucher_line_obj.unlink(cr, uid, wtv_line_ids)\n #\n if voucher_line.amount_withholding_tax:\n domain = [('move_id', '=', voucher_line.move_line_id.move_id.id)]\n inv_ids = invoice_obj.search(cr, uid, domain)\n for inv in invoice_obj.browse(cr, uid, inv_ids):\n if len(inv.withholding_tax_line):\n rate_num = len(inv.withholding_tax_line)\n # Rates\n wt_amount_rate = round(voucher_line.amount_withholding_tax / rate_num, \\\n dp_obj.precision_get(cr, uid, 'Account'))\n wt_residual = voucher_line.amount_withholding_tax\n # Re-read move lines to assign the amounts of wt\n i = 0\n for wt_invoice_line in inv.withholding_tax_line:\n i += 1\n if i == rate_num:\n wt_amount = wt_residual\n else:\n wt_amount = wt_rate\n wt_residual -= wt_amount\n \n val = {\n 'voucher_line_id' : voucher_line_id,\n 'withholding_tax_id' : wt_invoice_line.withholding_tax_id.id,\n 'amount' : wt_amount\n }\n wt_voucher_line_obj.create(cr, uid, val)\n \n return res\n \n def create(self, cr, uid, vals, *args, **kwargs):\n res_id = super(account_voucher_line,self).create(cr, uid, vals, *args, **kwargs)\n self.recompute_withholding_tax_voucher_line(cr, uid, res_id, context=None)\n return res_id\n \n def write(self, cr, uid, ids, vals, context=None):\n res = super(account_voucher_line,self).write(cr, uid, ids, vals, context)\n if 'amount_withholding_tax' in vals:\n for line_id in ids:\n self.recompute_withholding_tax_voucher_line(cr, uid, line_id)\n return res\n \n \nclass account_fiscal_position(orm.Model):\n _inherit = \"account.fiscal.position\"\n _columns = {\n 'withholding_tax_ids': fields.many2many('withholding.tax', 'account_fiscal_position_withholding_tax_rel', 'fiscal_position_id', 'withholding_tax_id', 'Withholding Tax'),\n }\n \nclass account_invoice(orm.Model):\n _inherit = \"account.invoice\"\n \n def _amount_withholding_tax(self, cr, uid, ids, name, args, context=None):\n res = {}\n for invoice in self.browse(cr, uid, ids, context=context):\n res[invoice.id] = {\n 'withholding_tax_amount': 0.0,\n }\n for line in invoice.withholding_tax_line:\n res[invoice.id]['withholding_tax_amount'] += line.tax\n res[invoice.id]['amount_net_pay'] = invoice.amount_total - res[invoice.id]['withholding_tax_amount']\n return res\n \n _columns = {\n 'withholding_tax': fields.boolean('Withholding Tax'),\n 'withholding_tax_line': fields.one2many('account.invoice.withholding.tax', 'invoice_id', 'Withholding Tax', readonly=True, states={'draft':[('readonly',False)]}),\n 'withholding_tax_amount': fields.function(_amount_withholding_tax, digits_compute=dp.get_precision('Account'), string='Withholding tax', multi='withholding_tax'),\n 'amount_net_pay': fields.function(_amount_withholding_tax, digits_compute=dp.get_precision('Account'), string='Net To Pay', multi='withholding_tax')\n }\n \n def action_move_create(self, cr, uid, ids, context=None):\n '''\n Split amount withholding tax on account move lines\n '''\n move_line_obj = self.pool['account.move.line']\n dp_obj = self.pool['decimal.precision']\n \n res = super(account_invoice, self).action_move_create(cr, uid, ids, context=context)\n \n for inv in self.browse(cr, uid, ids):\n # Rates\n rate_num = 0\n for move_line in inv.move_id.line_id:\n if not move_line.date_maturity:\n continue\n rate_num += 1\n #\n if rate_num:\n wt_rate = round(inv.withholding_tax_amount / rate_num, \\\n dp_obj.precision_get(cr, uid, 'Account'))\n wt_residual = inv.withholding_tax_amount\n # Re-read move lines to assign the amounts of wt\n i = 0\n for move_line in inv.move_id.line_id:\n if not move_line.date_maturity:\n continue\n i += 1\n if i == rate_num:\n wt_amount = wt_residual\n else:\n wt_amount = wt_rate\n wt_residual -= wt_amount\n # update line\n move_line_obj.write(cr, uid, [move_line.id], {'withholding_tax_amount': wt_amount})\n \n return res\n \n def compute_all_withholding_tax(self, cr, uid, ids, context=None):\n \n withholdin_tax_obj = self.pool['withholding.tax']\n invoice_withholdin_tax_obj = self.pool['account.invoice.withholding.tax']\n res ={}\n \n if not ids :\n return res\n \n for invoice in self.browse(cr, uid, ids):\n # Clear for recompute o because there isn't withholding_tax to True \n if invoice.fiscal_position or not invoice.withholding_tax:\n cr.execute(\"DELETE FROM account_invoice_withholding_tax WHERE invoice_id=%s \", (invoice.id,))\n if invoice.fiscal_position and invoice.fiscal_position.withholding_tax_ids:\n for tax in invoice.fiscal_position.withholding_tax_ids:\n tot_invoice = 0\n withholding_tax = withholdin_tax_obj.compute_amount(cr, uid, tax.id, tot_invoice, invoice.id, context=None)\n val = {\n 'invoice_id' : invoice.id,\n 'withholding_tax_id' : tax.id,\n 'base': withholding_tax['base'],\n 'tax': withholding_tax['tax']\n }\n invoice_withholdin_tax_obj.create(cr, uid, val)\n \n return res\n \n def button_reset_taxes(self, cr, uid, ids, context=None):\n res = super(account_invoice, self).button_reset_taxes(cr, uid, ids, context=context)\n \n self.compute_all_withholding_tax(cr, uid, ids, context)\n \n return res\n \n def onchange_fiscal_position_id(self, cr, uid, ids, fiscal_position_id, context=None):\n res ={}\n fiscal_position_obj = self.pool['account.fiscal.position']\n vals= False\n if fiscal_position_id:\n fiscal_position = fiscal_position_obj.browse(cr, uid, fiscal_position_id)\n if fiscal_position.withholding_tax_ids:\n vals = {\n 'withholding_tax': True\n }\n \n res = {\n 'value': vals \n }\n return res\n \n \nclass account_invoice_line(orm.Model):\n _inherit = \"account.invoice.line\"\n \n def compute_amount_line(self, cr, uid, line):\n \n dp_obj = self.pool['decimal.precision']\n price_subtotal = 0 \n price = line['price_unit'] * (1-(line['discount'] or 0.0)/100.0)\n if 'discount2' in line: # field of my customization\n price = price * (1-(line['discount2'] or 0.0)/100.0)\n price_subtotal = round(price * line['quantity'], dp_obj.precision_get(cr, uid, 'Account'))\n \n return price_subtotal\n\n\nclass account_invoice_withholding_tax(orm.Model):\n _name = 'account.invoice.withholding.tax'\n _description = 'Invoice Withholding Tax Line'\n _columns = {\n 'invoice_id': fields.many2one('account.invoice', 'withholding_tax_line', 'Invoice'),\n 'withholding_tax_id': fields.many2one('withholding.tax', 'Withholding tax'),\n 'base': fields.float('Base'),\n 'tax': fields.float('Tax'),\n }\n \n def onchange_withholding_tax_id(self, cr, uid, ids, withholding_tax_id, invoice_line_ids):\n fiscal_position_obj = self.pool['account.fiscal.position']\n withholdin_tax_obj = self.pool['withholding.tax']\n invoice_line_obj = self.pool['account.invoice.line']\n res = {}\n tot_invoice = 0\n for line in invoice_line_ids:\n if line[1]:\n line_inv = invoice_line_obj.browse(cr, uid, line[1])\n price_subtotal = line_inv.price_subtotal\n else:\n price_subtotal = invoice_line_obj.compute_amount_line(cr, uid, line[2])\n tot_invoice += price_subtotal\n tax = withholdin_tax_obj.compute_amount(cr, uid, withholding_tax_id, tot_invoice, invoice_id=None, context=None)\n \n res['value'] = {\n 'base': tax['base'],\n 'tax': tax['tax']\n }\n \n return res\n \nclass withholding_tax(orm.Model):\n _name = 'withholding.tax'\n _description = 'Withholding Tax'\n \n def _get_rate(self, cr, uid, ids, field_names, args, context=None):\n res = {}\n for tax in self.browse(cr, uid, ids, context=context):\n cr.execute('SELECT tax, base FROM withholding_tax_rate ' \\\n ' WHERE withholding_tax_id = %s and (date_start < current_date or date_start is null)' \\\n ' ORDER by date_start LIMIT 1', (tax.id,))\n rate = cr.fetchone()\n if rate:\n res[tax.id] = {\n 'tax' : rate[0],\n 'base': rate[1]\n }\n else:\n res[tax.id] = {\n 'tax' : 0,\n 'base': 1\n }\n \n return res\n \n _columns = {\n 'active': fields.boolean('Active'),\n 'name': fields.char('Name', size=256, required=True),\n 'certification': fields.boolean('Certification'),\n 'comment': fields.text('Text'),\n 'account_receivable_id': fields.many2one('account.account', 'Account Receivable', required=True, \n domain=[('type','=', 'receivable')]),\n 'account_payable_id': fields.many2one('account.account', 'Account Payable', required=True, \n domain=[('type','=', 'payable')]),\n 'payment_term': fields.many2one('account.payment.term', 'Payment Terms', required=True),\n 'tax': fields.function(_get_rate, string='Tax %', multi='balance'),\n 'base': fields.function(_get_rate, string='Base', multi='balance'),\n 'rate_ids': fields.one2many('withholding.tax.rate', 'withholding_tax_id', 'Rates', required=True),\n }\n _defaults = {\n 'active': True\n }\n \n def compute_amount(self, cr, uid, withholding_tax_id, amount_invoice, invoice_id=None, context=None):\n invoice_obj = self.pool['account.invoice']\n res = {\n 'base' : 0,\n 'tax' : 0\n }\n if not amount_invoice and invoice_id:\n invoice = invoice_obj.browse(cr, uid, invoice_id)\n amount_invoice = invoice.amount_untaxed\n tax = self.browse(cr, uid, withholding_tax_id)\n base = amount_invoice * tax.base\n tax = base * ((tax.tax or 0.0)/100.0)\n \n res['base'] = base\n res['tax'] = tax\n \n return res\n \n\nclass withholding_tax_rate(orm.Model):\n _name = 'withholding.tax.rate'\n _description = 'Withholding Tax Rates'\n \n def _check_date(self, cursor, user, ids, context=None):\n for rate in self.browse(cursor, user, ids, context=context):\n if not rate.withholding_tax_id.active:\n continue\n where = []\n if rate.date_start:\n where.append(\"((date_stop>='%s') or (date_stop is null))\" % (rate.date_start,))\n if rate.date_stop:\n where.append(\"((date_start<='%s') or (date_start is null))\" % (rate.date_stop,))\n\n cursor.execute('SELECT id ' \\\n 'FROM withholding_tax_rate ' \\\n 'WHERE '+' and '.join(where) + (where and ' and ' or '')+\n 'withholding_tax_id = %s ' \\\n 'AND id <> %s', (\n rate.withholding_tax_id.id,\n rate.id))\n if cursor.fetchall():\n return False\n return True\n\n _columns = {\n 'withholding_tax_id': fields.many2one('withholding.tax', 'Withholding Tax', ondelete='cascade', readonly=True),\n 'date_start': fields.date('Date Start'),\n 'date_stop': fields.date('Date Stop'),\n 'comment': fields.text('Text'),\n 'base': fields.float('Base Coeff.'),\n 'tax': fields.float('Tax %'),\n }\n _defaults = {\n 'base': 1\n }\n \n _constraints = [\n (_check_date, 'You cannot have 2 pricelist versions that overlap!',\n ['date_start', 'date_stop'])\n ]\n\nclass withholding_tax_voucher_line(orm.Model):\n _name = 'withholding.tax.voucher.line'\n _description = 'Withholding Tax Voucher Line'\n _columns = {\n 'voucher_line_id': fields.many2one('account.voucher.line', 'Account Voucher Line', ondelete='cascade'),\n 'withholding_tax_id': fields.many2one('withholding.tax', 'Withholding Tax'),\n 'amount': fields.float('Amount'),\n }","sub_path":"openforce_withholding_tax/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":33170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"556350007","text":"# -*- coding: utf-8 -*-\n\n# FLO-2D Preprocessor tools for QGIS\n# Copyright © 2021 Lutra Consulting for FLO-2D\n\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version\n\nimport os\nimport traceback\nfrom qgis.PyQt.QtCore import Qt, QSettings\nfrom qgis.PyQt.QtGui import QColor\nfrom qgis.PyQt.QtWidgets import QInputDialog, QFileDialog, QApplication\nfrom .ui_utils import load_ui, try_disconnect, set_icon\nfrom ..flo2d_ie.rainfall_io import ASCProcessor, HDFProcessor\nfrom ..utils import is_number, m_fdata\nfrom ..geopackage_utils import GeoPackageUtils\nfrom .table_editor_widget import StandardItemModel, StandardItem, CommandItemEdit\nfrom ..flo2dobjects import Rain\nfrom ..gui.dlg_sampling_rain import SamplingRainDialog\nfrom ..user_communication import UserCommunication\nfrom math import isnan\n\nuiDialog, qtBaseClass = load_ui(\"rain_editor\")\n\n\nclass RainEditorWidget(qtBaseClass, uiDialog):\n def __init__(self, iface, plot, table, lyrs):\n qtBaseClass.__init__(self)\n uiDialog.__init__(self)\n self.iface = iface\n self.con = None\n self.setupUi(self)\n self.lyrs = lyrs\n self.plot = plot\n self.plot_item_name = None\n self.table = table\n self.tview = table.tview\n self.rain = None\n self.gutils = None\n self.uc = UserCommunication(iface, \"FLO-2D\")\n self.rain_data_model = StandardItemModel()\n self.rain_tseries_data = None\n\n self.d1, self.d2 = [[], []]\n\n set_icon(self.raster_rain_btn, \"sample_rain.svg\")\n set_icon(self.show_table_btn, \"show_cont_table.svg\")\n set_icon(self.remove_tseries_btn, \"mActionDeleteSelected.svg\")\n set_icon(self.add_tseries_btn, \"mActionAddRainTimeSeries.svg\")\n set_icon(self.add_predefined_tseries_btn, \"mActionOpenFile.svg\")\n set_icon(self.rename_tseries_btn, \"change_name.svg\")\n\n def block_saving(self):\n try_disconnect(self.rain_data_model.dataChanged, self.save_tseries_data)\n\n def unblock_saving(self):\n self.rain_data_model.dataChanged.connect(self.save_tseries_data)\n\n def itemDataChangedSlot(self, item, oldValue, newValue, role, save=True):\n \"\"\"\n Slot used to push changes of existing items onto undoStack.\n \"\"\"\n if role == Qt.EditRole:\n command = CommandItemEdit(\n self, item, oldValue, newValue, \"Text changed from '{0}' to '{1}'\".format(oldValue, newValue)\n )\n self.tview.undoStack.push(command)\n return True\n\n def connect_signals(self):\n self.asc_btn.clicked.connect(self.import_rainfall)\n self.hdf_btn.clicked.connect(self.export_rainfall_to_binary_hdf5)\n self.tseries_cbo.currentIndexChanged.connect(self.populate_tseries_data)\n self.simulate_rain_grp.toggled.connect(self.set_rain)\n self.realtime_rainfall_grp.toggled.connect(self.set_realtime)\n self.building_chbox.stateChanged.connect(self.set_building)\n self.spatial_variation_grp.toggled.connect(self.set_arf)\n self.moving_storm_grp.toggled.connect(self.set_moving_storm)\n self.moving_storm_speed_dbox.editingFinished.connect(self.set_moving_storm_speed)\n self.rainfall_time_distribution_grp.toggled.connect(self.set_time_series_fid)\n\n self.n_radio.clicked.connect(self.set_n_radio)\n self.e_radio.clicked.connect(self.set_e_radio)\n self.s_radio.clicked.connect(self.set_s_radio)\n self.w_radio.clicked.connect(self.set_w_radio)\n self.ne_radio.clicked.connect(self.set_ne_radio)\n self.se_radio.clicked.connect(self.set_se_radio)\n self.sw_radio.clicked.connect(self.set_sw_radio)\n self.nw_radio.clicked.connect(self.set_nw_radio)\n\n self.raster_rain_btn.clicked.connect(self.raster_rain)\n\n self.total_rainfall_sbox.editingFinished.connect(self.set_tot_rainfall)\n self.rainfall_abst_sbox.editingFinished.connect(self.set_rainfall_abst)\n self.show_table_btn.clicked.connect(self.populate_tseries_data)\n self.add_tseries_btn.clicked.connect(self.add_tseries)\n self.add_predefined_tseries_btn.clicked.connect(self.add_predefined_tseries)\n self.remove_tseries_btn.clicked.connect(self.delete_tseries)\n self.rename_tseries_btn.clicked.connect(self.rename_tseries)\n self.rain_data_model.dataChanged.connect(self.save_tseries_data)\n self.table.before_paste.connect(self.block_saving)\n self.table.after_paste.connect(self.unblock_saving)\n self.rain_data_model.itemDataChanged.connect(self.itemDataChangedSlot)\n\n def setup_connection(self):\n con = self.iface.f2d[\"con\"]\n if con is None:\n return\n self.con = con\n self.gutils = GeoPackageUtils(self.con, self.iface)\n\n # qry = '''SELECT movingstorm FROM rain;'''\n # row = self.gutils.execute(qry).fetchone()\n # if is_number(row[0]):\n # if row[0] == '0':\n # self.moving_storm_chbox.setChecked(False)\n # else:\n # self.moving_storm_chbox.setChecked(True)\n\n qry = \"\"\"SELECT value FROM cont WHERE name = 'IRAIN';\"\"\"\n row = self.gutils.execute(qry).fetchone()\n if is_number(row[0]):\n if row[0] == \"0\":\n self.simulate_rain_grp.setChecked(False)\n else:\n self.simulate_rain_grp.setChecked(True)\n\n self.rain = Rain(self.con, self.iface)\n\n # self.create_plot()\n\n def import_rainfall(self):\n try:\n s = QSettings()\n last_dir = s.value(\"FLO-2D/lastASC\", \"\")\n asc_dir = QFileDialog.getExistingDirectory(\n None, \"Select directory with Rainfall ASCII grid files\", directory=last_dir\n )\n if not asc_dir:\n return\n s.setValue(\"FLO-2D/lastASC\", asc_dir)\n\n try:\n grid_lyr = self.lyrs.data[\"grid\"][\"qlyr\"]\n QApplication.setOverrideCursor(Qt.WaitCursor)\n asc_processor = ASCProcessor(grid_lyr, asc_dir) # as_processor, an instance of the ASCProcessor class,\n head_qry = \"INSERT INTO raincell (rainintime, irinters, timestamp) VALUES(?,?,?);\"\n data_qry = \"INSERT INTO raincell_data (time_interval, rrgrid, iraindum) VALUES (?,?,?);\"\n self.gutils.clear_tables(\"raincell\", \"raincell_data\")\n header = asc_processor.parse_rfc()\n time_step = float(header[0])\n self.gutils.execute(head_qry, header)\n time_interval = 0\n for rain_series in asc_processor.rainfall_sampling():\n cur = self.gutils.con.cursor()\n for val, gid in rain_series:\n cur.execute(data_qry, (time_interval, gid, val))\n self.gutils.con.commit()\n time_interval += time_step\n QApplication.restoreOverrideCursor()\n self.uc.show_info(\"Importing Rainfall Data finished!\")\n except Exception as e:\n self.uc.log_info(traceback.format_exc())\n QApplication.restoreOverrideCursor()\n self.uc.bar_warn(\n \"Importing Rainfall Data from ASCII files failed! Please check your input data.\\nIs the .RFC file missing?\"\n )\n\n except Exception as e:\n self.uc.log_info(traceback.format_exc())\n QApplication.restoreOverrideCursor()\n self.uc.show_warn(\n \"WARNING 060319.1835: Importing Rainfall Data failed! ({0}) : {1}\".format(e.errno, e.strerror)\n )\n\n def export_rainfall_to_binary_hdf5(self):\n try:\n import h5py\n except ImportError:\n self.uc.bar_warn(\"There is no h5py module installed! Please install it to run export tool.\")\n return\n s = QSettings()\n last_dir = s.value(\"FLO-2D/lastHDF\", \"\")\n hdf_file, __ = QFileDialog.getSaveFileName(\n None, \"Export Rainfall to HDF file\", directory=last_dir, filter=\"*.hdf5\"\n )\n if not hdf_file:\n return\n s.setValue(\"FLO-2D/lastHDF\", os.path.dirname(hdf_file))\n try:\n QApplication.setOverrideCursor(Qt.WaitCursor)\n qry_header = \"SELECT rainintime, irinters, timestamp FROM raincell LIMIT 1;\"\n header = self.gutils.execute(qry_header).fetchone()\n rainintime, irinters, timestamp = header\n header_data = [rainintime, irinters, timestamp]\n qry_data = \"SELECT iraindum FROM raincell_data ORDER BY rrgrid, time_interval;\"\n data = self.gutils.execute(qry_data).fetchall()\n data = [data[i : i + irinters] for i in range(0, len(data), irinters)]\n hdf_processor = HDFProcessor(hdf_file)\n hdf_processor.export_rainfall_to_binary_hdf5(header_data, data)\n QApplication.restoreOverrideCursor()\n self.uc.show_info(\"Exporting Rainfall Data finished!\")\n except Exception as e:\n self.uc.log_info(traceback.format_exc())\n QApplication.restoreOverrideCursor()\n self.uc.bar_warn(\"Exporting Rainfall Data failed! Please check your input data.\")\n\n def create_plot(self):\n \"\"\"\n Create initial plot.\n \"\"\"\n self.plot.clear()\n if self.plot.plot.legend is not None:\n self.plot.plot.legend.scene().removeItem(self.plot.plot.legend)\n self.plot.plot.addLegend()\n\n self.plot_item_name = \"Rain timeseries\"\n self.plot.add_item(self.plot_item_name, [self.d1, self.d2], col=QColor(\"#0018d4\"))\n\n def rain_properties(self):\n if not self.rain:\n return\n\n row = self.rain.get_row()\n\n if row[\"movingstorm\"] == 1:\n self.moving_storm_grp.setChecked(True)\n else:\n self.moving_storm_grp.setChecked(False)\n\n if self.gutils.get_cont_par(\"IRAIN\") == \"1\":\n self.simulate_rain_grp.setChecked(True)\n else:\n self.simulate_rain_grp.setChecked(False)\n\n if row[\"irainreal\"] == 1:\n self.realtime_rainfall_grp.setChecked(True)\n else:\n self.realtime_rainfall_grp.setChecked(False)\n\n if row[\"irainbuilding\"] == 1:\n self.building_chbox.setChecked(True)\n else:\n self.building_chbox.setChecked(False)\n\n if row[\"irainarf\"] == 1:\n self.spatial_variation_grp.setChecked(True)\n else:\n self.spatial_variation_grp.setChecked(False)\n\n if is_number(row[\"tot_rainfall\"]):\n self.total_rainfall_sbox.setValue(float((row[\"tot_rainfall\"])))\n else:\n self.total_rainfall_sbox.setValue(0)\n\n if is_number(row[\"rainabs\"]):\n self.rainfall_abst_sbox.setValue(float(row[\"rainabs\"]))\n else:\n self.rainfall_abst_sbox.setValue(0)\n\n if is_number(row[\"rainspeed\"]):\n self.moving_storm_speed_dbox.setValue(float((row[\"rainspeed\"])))\n else:\n self.moving_storm_speed_dbox.setValue(0)\n\n self.populate_tseries()\n idx = self.tseries_cbo.findData(self.rain.series_fid)\n self.tseries_cbo.setCurrentIndex(idx)\n self.populate_tseries_data()\n self.connect_signals()\n\n def populate_tseries(self):\n self.tseries_cbo.clear()\n for row in self.rain.get_time_series():\n ts_fid, name = [x if x is not None else \"\" for x in row]\n self.tseries_cbo.addItem(name, ts_fid)\n\n def add_tseries(self):\n if not self.rain:\n return\n self.rain.add_time_series()\n self.populate_tseries()\n # self.tseries_cbo.setCurrentIndex(len(self.tseries_cbo)-1)\n\n def add_predefined_tseries(self):\n self.uc.clear_bar_messages()\n s = QSettings()\n last_dir = s.value(\"FLO-2D/lastPredefinedSeriesDir\", \"\")\n predefined_files, __ = QFileDialog.getOpenFileNames(\n None, \"Select time series files to import data\", directory=last_dir, filter=\"(*.DAT *.TXT)\"\n )\n if not predefined_files:\n return\n s.setValue(\"FLO-2D/lastPredefinedSeriesDir\", os.path.dirname(predefined_files[0]))\n try:\n QApplication.setOverrideCursor(Qt.WaitCursor)\n if not self.rain:\n return\n for file in predefined_files:\n tail = os.path.splitext(os.path.basename(file))[0]\n self.rain.add_time_series(tail, True)\n self.read_predefined_tseries_data(file)\n self.populate_tseries()\n\n QApplication.restoreOverrideCursor()\n self.uc.show_info(\"Importing predefined time series finished!\")\n except Exception as e:\n QApplication.restoreOverrideCursor()\n self.uc.bar_warn(\"Importing predefined time series failed! Please check your input data.\")\n\n def read_predefined_tseries_data(self, file):\n tsd_sql = \"INSERT INTO rain_time_series_data (series_fid, time, value) VALUES (?, ?, ?);\"\n data = self.parse_timeseries(file)\n ts_list = []\n for item in data:\n ts_list.append((self.rain.series_fid, float(item[0]), float(item[1])))\n self.gutils.execute_many(tsd_sql, ts_list)\n\n def parse_timeseries(self, filename):\n par = self.single_parser(filename)\n data = [row for row in par]\n return data\n\n def single_parser(self, file):\n with open(file, \"r\") as f1:\n for line in f1:\n row = line.split()\n if row:\n yield row\n\n def delete_tseries(self):\n if not self.rain:\n return\n self.rain.del_time_series()\n self.populate_tseries()\n\n def rename_tseries(self):\n if not self.rain:\n return\n new_name, ok = QInputDialog.getText(None, \"Change timeseries name\", \"New name:\")\n if not ok or not new_name:\n return\n if not self.tseries_cbo.findText(new_name) == -1:\n msg = \"WARNING 060319.1725: Time series with name {} already exists in the database. Please, choose another name.\".format(\n new_name\n )\n self.uc.show_warn(msg)\n return\n self.rain.set_time_series_data_name(new_name)\n self.populate_tseries()\n\n def populate_tseries_data(self):\n \"\"\"\n Get current time series data, populate data table and create plot.\n \"\"\"\n cur_ts_idx = self.tseries_cbo.currentIndex()\n cur_ts_fid = self.tseries_cbo.itemData(cur_ts_idx)\n self.rain.series_fid = cur_ts_fid\n self.rain_tseries_data = self.rain.get_time_series_data()\n if not self.rain_tseries_data:\n return\n self.create_plot()\n self.tview.undoStack.clear()\n self.tview.setModel(self.rain_data_model)\n self.rain_data_model.clear()\n self.rain_data_model.setHorizontalHeaderLabels([\"Time\", \"% of Total Storm\"])\n self.d1, self.d2 = [[], []]\n for row in self.rain_tseries_data:\n items = [StandardItem(\"{:.4f}\".format(x)) if x is not None else StandardItem(\"\") for x in row]\n self.rain_data_model.appendRow(items)\n self.d1.append(row[0] if not row[0] is None else float(\"NaN\"))\n self.d2.append(row[1] if not row[1] is None else float(\"NaN\"))\n rc = self.rain_data_model.rowCount()\n if rc < 500:\n for row in range(rc, 500 + 1):\n items = [StandardItem(x) for x in (\"\",) * 2]\n self.rain_data_model.appendRow(items)\n self.tview.horizontalHeader().setStretchLastSection(True)\n for col in range(2):\n self.tview.setColumnWidth(col, 100)\n for i in range(self.rain_data_model.rowCount()):\n self.tview.setRowHeight(i, 20)\n self.rain.set_row() # Inserts or replaces values in table 'rain'\n self.update_plot()\n\n def save_tseries_data(self):\n \"\"\"\n Get rain timeseries data and save them in gpkg.\n \"\"\"\n self.update_plot()\n ts_data = []\n for i in range(self.rain_data_model.rowCount()):\n # save only rows with a number in the first column\n if is_number(m_fdata(self.rain_data_model, i, 0)) and not isnan(m_fdata(self.rain_data_model, i, 0)):\n ts_data.append(\n (self.rain.series_fid, m_fdata(self.rain_data_model, i, 0), m_fdata(self.rain_data_model, i, 1))\n )\n else:\n pass\n data_name = self.tseries_cbo.currentText()\n self.rain.set_time_series_data(data_name, ts_data)\n\n def update_plot(self):\n \"\"\"\n When time series data for plot change, update the plot.\n \"\"\"\n if not self.plot_item_name:\n return\n self.d1, self.d2 = [[], []]\n for i in range(self.rain_data_model.rowCount()):\n self.d1.append(m_fdata(self.rain_data_model, i, 0))\n self.d2.append(m_fdata(self.rain_data_model, i, 1))\n self.plot.update_item(self.plot_item_name, [self.d1, self.d2])\n\n def raster_rain(self):\n if self.gutils.is_table_empty(\"user_model_boundary\"):\n self.uc.bar_warn(\"There is no computational domain! Please digitize it before running tool.\")\n return\n if self.gutils.is_table_empty(\"grid\"):\n self.uc.bar_warn(\"There is no grid! Please create it before running tool.\")\n return\n\n cell_size = self.get_cell_size()\n dlg = SamplingRainDialog(self.con, self.iface, self.lyrs, cell_size)\n ok = dlg.exec_()\n if ok:\n pass\n else:\n return\n try:\n if not self.gutils.is_table_empty(\"rain_arf_cells\"):\n q = \"There are some Rain ARF cells already defined in the database. Overwrite them?\"\n if not self.uc.question(q):\n return\n del_cells = \"DELETE FROM rain_arf_cells;\"\n self.gutils.execute(del_cells)\n\n QApplication.setOverrideCursor(Qt.WaitCursor)\n res = dlg.probe_rain()\n\n delete_null = \"\"\"DELETE FROM rain_arf_cells WHERE arf IS NULL;\"\"\"\n self.gutils.execute(delete_null)\n QApplication.restoreOverrideCursor()\n msg = \"Rain ARF sampling performed!.\\n\\n\"\n msg += 'Data was stored in the \"Rain ARF Cells\" layer.\\n'\n msg += \"Each sampled cell was assigned a rainfall depth area reduction value.\\n\"\n msg += \"They will be saved in the RAIN.DAT FLO-2D file as lines 5 if the\\n\"\n msg += '\"Spatial Variation (Depth Area Reduction)\" checkbox is toggled.'\n self.uc.show_info(msg)\n\n # if res:\n # dlg.show_probing_result_info()\n except Exception as e:\n QApplication.restoreOverrideCursor()\n self.uc.log_info(traceback.format_exc())\n self.uc.show_warn(\"WARNING 060319.1726: Probing grid elevation failed! Please check your raster layer.\")\n\n def get_cell_size(self):\n \"\"\"\n Get cell size from:\n - Computational Domain attr table (if defined, will be written to cont table)\n - cont table\n - ask user\n \"\"\"\n bl = self.lyrs.data[\"user_model_boundary\"][\"qlyr\"]\n bfeat = next(bl.getFeatures())\n if bfeat[\"cell_size\"]:\n cs = bfeat[\"cell_size\"]\n if cs <= 0:\n self.uc.show_warn(\n \"WARNING 060319.1727: Cell size must be positive. Change the feature attribute value in Computational Domain layer.\"\n )\n return None\n self.gutils.set_cont_par(\"CELLSIZE\", cs)\n else:\n cs = self.gutils.get_cont_par(\"CELLSIZE\")\n cs = None if cs == \"\" else cs\n if cs:\n if cs <= 0:\n self.uc.show_warn(\n \"WARNING 060319.1728: Cell size must be positive. Change the feature attribute value in Computational Domain layer or default cell size in the project settings.\"\n )\n return None\n return cs\n else:\n r, ok = QInputDialog.getDouble(\n None, \"Grid Cell Size\", \"Enter grid element cell size\", value=100, min=0.1, max=99999\n )\n if ok:\n cs = r\n self.gutils.set_cont_par(\"CELLSIZE\", cs)\n else:\n return None\n\n def set_rain(self):\n if not self.rain:\n return\n if self.simulate_rain_grp.isChecked():\n self.gutils.set_cont_par(\"IRAIN\", 1)\n else:\n self.gutils.set_cont_par(\"IRAIN\", 0)\n\n def set_realtime(self):\n if not self.rain:\n return\n self.rain.irainreal = self.realtime_rainfall_grp.isChecked()\n self.rain.set_row()\n\n def set_building(self):\n if not self.rain:\n return\n self.rain.irainbuilding = self.building_chbox.isChecked()\n self.rain.set_row()\n\n def set_arf(self):\n if not self.rain:\n return\n self.rain.irainarf = self.spatial_variation_grp.isChecked()\n self.rain.set_row()\n\n def set_time_series_fid(self):\n if not self.rain:\n return\n if not self.rainfall_time_distribution_grp.isChecked():\n self.rain.series_fid = \"\"\n else:\n cur_ts_idx = self.tseries_cbo.currentIndex()\n cur_ts_fid = self.tseries_cbo.itemData(cur_ts_idx)\n self.rain.series_fid = cur_ts_fid\n self.rain.set_row()\n\n def set_moving_storm(self):\n if not self.rain:\n return\n self.rain.movingstorm = self.moving_storm_grp.isChecked()\n self.rain.set_row()\n\n def set_moving_storm_speed(self):\n if not self.rain:\n return\n self.rain.rainspeed = self.moving_storm_speed_dbox.value()\n self.rain.set_row()\n\n def set_n_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 1\n self.rain.set_row()\n\n def set_e_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 2\n self.rain.set_row()\n\n def set_s_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 3\n self.rain.set_row()\n\n def set_w_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 4\n self.rain.set_row()\n\n def set_ne_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 5\n self.rain.set_row()\n\n def set_se_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 6\n self.rain.set_row()\n\n def set_sw_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 7\n self.rain.set_row()\n\n def set_nw_radio(self):\n if not self.rain:\n return\n self.rain.iraindir = 8\n self.rain.set_row()\n\n def set_tot_rainfall(self):\n if not self.rain:\n return\n self.rain.tot_rainfall = self.total_rainfall_sbox.value()\n self.rain.set_row()\n\n def set_rainfall_abst(self):\n if not self.rain:\n return\n self.rain.rainabs = self.rainfall_abst_sbox.value()\n self.rain.set_row()\n","sub_path":"flo2d/gui/rain_editor_widget.py","file_name":"rain_editor_widget.py","file_ext":"py","file_size_in_byte":23605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"44423939","text":"from PIL import Image\n\nclass Square:\n def __init__(self, image, dimension,width, height):\n self.image = image\n self.width = width\n self.height = height\n self.dimension = dimension\n self.total_red = 0\n self.total_green = 0\n self.total_blue = 0\n self.numberOfEntries = 0\n def reset (self):\n self.total_red = 0\n self.total_green = 0\n self.total_blue = 0\n self.numberOfEntries = 0\n\n def incrementAvg(self,pixel):\n self.total_red += pixel[0]\n self.total_green += pixel[1]\n self.total_blue += pixel[2]\n self.numberOfEntries += 1\n def getAverage(self):\n average = []\n average.append(round(self.total_red/self.numberOfEntries))\n average.append(round(self.total_green/self.numberOfEntries))\n average.append(round(self.total_blue/self.numberOfEntries))\n return tuple(average)\n\n\n def colorize (self):\n for w in range(self.dimension):\n for h in range (self.dimension):\n self.incrementAvg(self.image[w+ self.width,h + self.height])\n\n for w in range (self.dimension):\n for h in range (self.dimension):\n self.image[w + self.width,h + self.height] = self.getAverage()\n\n\nclass Image_process:\n def __init__(self, image, width, height, pixel_size):\n self.image = image\n self.width = width\n self.height = height\n self. pixel_size = pixel_size\n for w in range(0, self.width, self.pixel_size):\n for h in range(0, self.height, self.pixel_size):\n Square(self.image, self.pixel_size, w, h ).colorize()\n \npixel_size = 20\n\nim = Image.open(\"ass.jpg\")\nwidth, height = im.size\nprint(\"width:{} height:{}\".format(width, height))\nimage = im.load()\nImage_process(image, width, height, pixel_size)\n\n\n\n\n\n\n\n\n\nim.show()\n","sub_path":"driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"513520198","text":"#handle the CCSD output in TCC\n\ndef average_time(filename):\n times=[]\n finput = open(filename,\"r\")\n ccsd = False\n for line in finput:\n if line.find(\"Begining CC\") != -1:\n ccsd = True\n if(ccsd and line[0].isdigit()):\n time = float(line.split()[-1])\n times.append(time)\n finput.close()\n average = sum(times)/float(len(times)) \n return average\n\ndef CheckCCSDComplete(filename):\n finput = open(filename,\"r\")\n for line in finput:\n if line.find(\"CCSD Energy\") != -1:\n print(\"Good\",filename)\n return True\n print(\"Error\",filename)\n return False\n\ndef ReadEnergy(filename):\n finput = open(filename,\"r\")\n ccsd = False\n hf_energy = \"\"\n ccsd_energy=\"\"\n for line in finput:\n if (line.find(\"Iteration\")!=-1) and (line.find(\"energy\")!=-1):\n hf_energy = line.split()[-3]\n if (line.find(\"Final energy\")!=-1):\n hf_energy = line.split()[-1]\n if (line.find(\"HF Energy\")!=-1):\n hf_energy = line.split()[-1]\n if line.find(\"Begining CC\") != -1:\n ccsd = True\n if(ccsd and (line.find(\"CCSD Energy\")!=-1) ):\n ccsd_energy = line.split()[-1]\n\n return hf_energy, ccsd_energy\n\ndef print_energy(filename):\n finput = open(filename,\"r\")\n ccsd = False\n for line in finput:\n if line.find(\"Begining CC\") != -1:\n ccsd = True\n if(ccsd and line[0].isdigit()):\n split_line = line.split()\n print(split_line[0]),\n print(\" \"),\n print(split_line[3])\n \n finput.close()\n\ndef triple_time(filename):\n finput = open(filename,\"r\")\n time = 0.0\n for line in finput:\n if(line.find(\"(T) Energy\") != -1 and line.find(\"Time\") != -1):\n time = float(line.split(\" \")[-1])\n finput.close()\n return time\n","sub_path":"ccsd.py","file_name":"ccsd.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"497266545","text":"def roofcalc(floor_area, Tin, Tout): \n \n import numpy as np\n \n table2 = np.loadtxt('table2.txt')\n a = np.array(table2[:, 16])\n \n T1 = 25.5\n T2 = 29.4\n K = 0.83\n U_ceiling = 0.7\n \n #Tin = 22\n #Tout = 40\n #floor_area = 100\n \n \n r = a - a\n roofmatrix = r\n \n for j in range(0,12):\n r[j] = U_ceiling*floor_area*((23 + a[j])*K + T1 - T2 + Tout - Tin)\n # print(r[j])\n \n for i in range(0,23):\n roofmatrix = np.vstack((roofmatrix, r))\n \n roofmatrix = np.transpose(roofmatrix) \n \n return roofmatrix","sub_path":"roof.py","file_name":"roof.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"503194735","text":"# Import statements\nimport psycopg2\nimport sys\nimport psycopg2.extras\nimport csv\nfrom psycopg2 import sql\nfrom config_example import *\n\n# Write code / functions to set up database connection and cursor here.\n\ndef get_connection_and_cursor():\n try:\n db_conn = psycopg2.connect(\"dbname = '{0}' user = '{1}' password = '{2}'\".format(dbname, username, password))\n print(\"connected\")\n\n except:\n print(\"fail to connect\")\n sys.exit(1)\n\n db_cursor = db_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n return db_conn, db_cursor\n\n\n# Write code / functions to create tables with the columns you want and all database setup here.\n\ndef set_up_db():\n cur.execute(\"DROP TABLE IF EXISTS Sites\")\n cur.execute(\"DROP TABLE IF EXISTS States\")\n\n cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS States(\n ID SERIAL PRIMARY KEY,\n Name VARCHAR(40) UNIQUE\n )\"\"\")\n\n cur.execute(\"\"\"CREATE TABLE IF NOT EXISTS Sites(\n ID SERIAL,\n Name VARCHAR(128) UNIQUE,\n Type VARCHAR(128),\n State_ID INTEGER REFERENCES States(ID),\n Location VARCHAR(255),\n Description TEXT\n )\"\"\")\n\n conn.commit()\n print(\"setup success\")\n\n\n\n# Write code / functions to deal with CSV files and insert data into the database here.\n\ndef insert(conn, cur, table, data_dict, no_return=False):\n \"\"\"Accepts connection and cursor, table name, dictionary that represents one row, and inserts data into table. (Not the only way to do this!)\"\"\"\n column_names = data_dict.keys()\n #print(column_names, \"column_names\") # for debug\n if not no_return:\n query = sql.SQL('INSERT INTO {0}({1}) VALUES({2}) ON CONFLICT DO NOTHING RETURNING id').format(\n sql.SQL(table),\n sql.SQL(', ').join(map(sql.Identifier, column_names)),\n sql.SQL(', ').join(map(sql.Placeholder, column_names))\n )\n else:\n query = sql.SQL('INSERT INTO {0}({1}) VALUES({2}) ON CONFLICT DO NOTHING').format(\n sql.SQL(table),\n sql.SQL(', ').join(map(sql.Identifier, column_names)),\n sql.SQL(', ').join(map(sql.Placeholder, column_names))\n )\n query_string = query.as_string(conn) # thanks to sql module\n cur.execute(query_string, data_dict) # will mean that id is in cursor, because insert statement returns id in this function\n if not no_return:\n return cur.fetchone()['id']\n\ndef csv_to_db(statename):\n state_id = insert(conn, cur, \"States\", {\"name\" : statename})\n filename = statename + '.csv'\n with open(filename, newline = '', encoding = 'utf-8') as csvfile:\n reader = csv.DictReader(csvfile)\n for row_dict in reader:\n # print(row_dict)\n del row_dict['ADDRESS']\n lower_dict = dict((k.lower(), v) for k, v in row_dict.items() if k != None)\n lower_dict['state_id'] = state_id\n insert(conn, cur, \"Sites\", lower_dict, True)\n conn.commit()\n print(\"insert success\")\n\n\n# Make sure to commit your database changes with .commit() on the database connection.\n\n\n\n# Write code to be invoked here (e.g. invoking any functions you wrote above)\n\nconn, cur = get_connection_and_cursor()\nset_up_db()\ncsv_to_db('arkansas')\ncsv_to_db('california')\ncsv_to_db('michigan')\n\n# Write code to make queries and save data in variables here.\n\n\ncur.execute('SELECT location FROM sites')\nall_locations = cur.fetchall()\n# print(all_locations)\n\ncur.execute(\"\"\" SELECT name FROM sites WHERE description LIKE '%beautiful%' \"\"\") # when passing a string val to postgres, single quote should be used\nbeautiful_sites = cur.fetchall()\n# print(beautiful_sites)\n\ncur.execute(\"\"\" SELECT COUNT(*) FROM SITES WHERE TYPE = 'National Lakeshore' \"\"\")\nnatl_lakeshores = cur.fetchall()\n# print(natl_lakeshores)\n\ncur.execute(\"\"\" SELECT SITES.NAME FROM SITES INNER JOIN STATES ON (SITES.STATE_ID = STATES.ID) WHERE STATES.NAME = 'michigan' \"\"\")\nmichigan_names = cur.fetchall()\n# print(michigan_names)\n\ncur.execute(\"\"\" SELECT COUNT(*) FROM SITES INNER JOIN STATES ON (SITES.STATE_ID = STATES.ID) WHERE STATES.NAME = 'arkansas' \"\"\")\ntotal_number_arkansas = cur.fetchall()\n# print(total_number_arkansas)\n\n\n# We have not provided any tests, but you could write your own in this file or another file, if you want.\n","sub_path":"SI507_project6.py","file_name":"SI507_project6.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"354499587","text":"from django.conf import settings\nfrom django.urls import reverse\n\nimport mock\nfrom elasticsearch import TransportError\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\n\nclass SuggestCompanyTests(APITestCase):\n def setUp(self):\n pass\n\n @mock.patch(\"complaint_search.es_interface.filter_suggest\")\n def test_suggest_no_param(self, mock_essuggest):\n \"\"\"\n Suggesting with no parameters\n \"\"\"\n url = reverse(\"complaint_search:suggest_company\")\n response = self.client.get(url)\n self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n mock_essuggest.assert_not_called()\n self.assertDictEqual(\n {\"text\": [\"This field is required.\"]}, response.data\n )\n\n @mock.patch(\"complaint_search.es_interface.filter_suggest\")\n def test_suggest_text__valid(self, mock_essuggest):\n \"\"\"\n Suggesting with text\n \"\"\"\n url = reverse(\"complaint_search:suggest_company\")\n param = {\"text\": \"Ba\"}\n mock_essuggest.return_value = \"OK\"\n response = self.client.get(url, param)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n mock_essuggest.assert_called_once_with(\n \"company.suggest\",\n \"company.raw\",\n field=\"complaint_what_happened\",\n format=\"default\",\n frm=0,\n no_aggs=False,\n no_highlight=False,\n page=1,\n size=25,\n sort=\"relevance_desc\",\n text=\"BA\",\n )\n self.assertEqual(\"OK\", response.data)\n\n @mock.patch(\"complaint_search.es_interface.filter_suggest\")\n def test_suggest_cors_headers(self, mock_essuggest):\n \"\"\"\n Make sure the response has CORS headers in debug mode\n \"\"\"\n settings.DEBUG = True\n url = reverse(\"complaint_search:suggest_company\")\n param = {\"text\": \"20\"}\n mock_essuggest.return_value = \"OK\"\n response = self.client.get(url, param)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertTrue(response.has_header(\"Access-Control-Allow-Origin\"))\n\n @mock.patch(\"complaint_search.es_interface.filter_suggest\")\n def test_suggest__transport_error(self, mock_essuggest):\n mock_essuggest.side_effect = TransportError(\"N/A\", \"Error\")\n url = reverse(\"complaint_search:suggest_company\")\n param = {\"text\": \"test\"}\n response = self.client.get(url, param)\n self.assertEqual(response.status_code, 424)\n self.assertDictEqual(\n {\"error\": \"There was an error calling Elasticsearch\"},\n response.data,\n )\n","sub_path":"complaint_search/tests/test_view_suggest_company.py","file_name":"test_view_suggest_company.py","file_ext":"py","file_size_in_byte":2687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"621140296","text":"def main():\n stop = \"\"\n choise = \"\"\n\n while (stop != \"y\"):\n choise = input(\"Input 1 to use default calculator\\nInput 2 to use fractions calculator \")\n\n if (choise == \"1\"):\n input_check()\n elif (choise == \"2\"):\n fractions_count()\n else:\n print(\"No such operation. Try again\")\n\n stop = input(\"Would you like exit (Y/y - yes, other - continue)? \").lower()\n\ndef input_check():\n try:\n num1 = int(input(\"Input first number: \"))\n num2 = int(input(\"Input second number: \"))\n oper = input(\"Input operation (+, -, *, /): \")\n\n count(num1, num2, oper)\n except:\n print(\"Invalid input. Try again\")\n\ndef count(num1, num2, oper):\n if (oper == \"+\"):\n print (num1, oper, num2, \"=\", num1 + num2)\n elif (oper == \"-\"):\n print (num1, oper, num2, \"=\", num1 - num2)\n elif (oper == \"*\"):\n print (num1, oper, num2, \"=\", num1 * num2)\n elif (oper == \"/\"):\n print (num1, oper, num2, \"=\", num1 / num2)\n else:\n print(\"No such operation. Try again\")\n\ndef fractions_count():\n print(\"To make a fraction use \\\"/\\\"\")\n\n num1 = input(\"Input first fraction: \")\n num2 = input(\"Input second fraction: \")\n oper = input(\"Input operation (+, -, *, /): \")\n num1_up = \"\"\n num1_down = \"\"\n num2_up = \"\"\n num2_down = \"\"\n separator = 0\n\n for i in range(len(num1) - 1):\n if (num1[i] == \"/\"):\n separator = i\n break\n\n num1_up = int(num1[0:separator])\n num1_down = int(num1[separator + 1:len(num1)])\n\n for i in range(len(num2) - 1):\n if (num2[i] == \"/\"):\n separator = i\n break\n\n num2_up = int(num2[0:separator])\n num2_down = int(num2[separator + 1:len(num2)])\n\n if (oper == \"+\"):\n if(num1_down == num2_down):\n print (num1, oper, num2, \"=\", str(num1_up + num2_up) + \"/\" + str(num1_down))\n else:\n print (num1, oper, num2, \"=\", str(num1_up * num2_down + num2_up * num1_down) + \"/\" + str(num1_down * num2_down))\n elif (oper == \"-\"):\n if(num1_down == num2_down):\n print (num1, oper, num2, \"=\", str(num1_up - num2_up) + \"/\" + str(num1_down))\n else:\n print (num1, oper, num2, \"=\", str(num1_up * num2_down - num2_up * num1_down) + \"/\" + str(num1_down * num2_down))\n elif (oper == \"*\"):\n print (num1, oper, num2, \"=\", str(num1_up * num2_up) + \"/\" + str(num1_down * num2_down))\n elif (oper == \"/\"):\n print (num1, oper, num2, \"=\", str(num1_up * num2_down) + \"/\" + str(num1_down * num2_up))\n else:\n print(\"No such operation. Try again\")\n\nmain()","sub_path":"Simple-console-calculator/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"456959219","text":"from requests_html import HTMLSession\nfrom bs4 import BeautifulSoup as bs\n\n\nGAMES = {\n 'Trine 3: The Artifacts of Power': 'trine-3-the-artifacts-of-power',\n 'Trine 4: The Nightmare Prince': 'trine-4-the-nightmare-prince'\n}\n\n\nclass Fanatical:\n\n def __init__(self, prices):\n self.url = 'https://www.fanatical.com/en/game/'\n self.prices = prices\n\n def run(self):\n for game, game_url in GAMES.items():\n if game not in self.prices : self.prices[game] = []\n price_obj = {'url': self.url + game_url, 'platform': 'fanatical' }\n\n session = HTMLSession()\n resp = session.get(self.url + game_url)\n resp.html.render()\n bs_content = bs(resp.html.html, \"html.parser\")\n\n purchase = bs_content.find('div', { 'class': 'price-container' })\n discount_block = purchase.find('div', { 'class': 'was-price' })\n\n if discount_block is not None:\n price_obj['dsc'] = {\n 'pct': purchase.find('div', { 'class': 'saving-percentage' }).getText().strip(),\n 'original_price': discount_block.find('span').getText().strip(),\n 'final_price': purchase.find('div', { 'class': 'price' }).find('span').getText().strip()\n }\n else:\n price_obj['orig'] = {\n 'original_price': purchase.find('div', { 'class': 'price' }).find('span').getText().strip()\n }\n\n self.prices[game].append(price_obj)\n\n return self.prices\n","sub_path":"finder/platforms/fanatical.py","file_name":"fanatical.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"400276677","text":"__author__ = 'tarik'\n\n\nclass ShortInputException(Exception):\n def __init__(self, length, atleast):\n Exception.__init__(self)\n self.length = length\n self.atleast = atleast\n\n\ntry:\n something = input(\"Write something dawg: \")\n if len(something) < 3:\n raise ShortInputException(len(something), 3)\n\nexcept EOFError:\n print(\"what the fuck man, don't EOF me.\")\nexcept ShortInputException as ex:\n print(\"You typed {0} while I was expecting at least {1} characters...\".format(ex.length, ex.atleast))\n\nelse:\n print('Good job my man. No exception raised.')\n\n","sub_path":"catchexception.py","file_name":"catchexception.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"611825664","text":"import os\nimport datetime\nimport pathlib\nimport codecs\n\ntotalSites = 0\ntotalBCH = 0\n\nindex = 1\n\ndirPath = os.path.join(\"..\",\"..\",\"_data\")\nfilename = os.listdir(dirPath)\n\ndef countFile(dir, filename):\n path = os.path.join(dir, filename)\n #print(\"Testing site: \" + path)\n if \".yml\" in path:\n file = codecs.open(path, 'r', \"utf-8\")\n processed = True\n\n global index\n for line in file:\n #print(line)\n\n if \"- name:\" in line:\n global totalSites\n totalSites+= 1\n\n #check for bch tag\n if \"bch: \" in line:\n if \"Yes\" in line:\n global totalBCH\n totalBCH += 1\n processed = True\n index += 1\n\nprint(\"\\n acceptBitcoin.Cash Site Analyser\")\nprint(\"-================================-\")\n\nfor file in filename:\n #print(\"Testing path: \" + path)\n\tif \"examples.yml\" not in file:\n\t\tcountFile(dirPath, file)\n\n\nprint(\"- Total websites listed: \" + str(totalSites))\nprint(\"- Total websites supporting BCH: \" + str(totalBCH))\n\n#create log\ntimestamp = datetime.datetime.utcnow()\n\noutputPath = os.path.join(\".\", \"output\")\ntry:\n\tos.mkdir(outputPath)\nexcept Exception as e:\n\tpass\n\noutput = codecs.open(os.path.join(outputPath,\"bchAccepted_log.csv\"), \"a\", \"utf-8\")\n\noutput.write(str(timestamp) + \", \" + str(totalBCH) + \", \" + str(totalSites) + \"\\n\")\n\noutput.close()\n\n#create html file\noutput = codecs.open(os.path.join(\"..\",\"..\",\"_includes\",\"count_support.html\"), \"w+\", \"utf-8\")\n\nprint(\"- Generating HTML snippet for website progress bar...\")\n\noutput.write(' \\\n \\\n
\\\n
' + str(totalBCH) + ' out of ' + str(totalSites) + ' websites listed support Bitcoin Cash.
\\\n
')\n\noutput.close()\n\nprint(\"\\nDone!\")\n","sub_path":"scripts/python/bchAccepted.py","file_name":"bchAccepted.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"109642727","text":"#!/usr/bin/env python \r\n# -*- coding: utf-8 -*- \r\n# @Time : 2019/9/20 0020 10:07 \r\n# @Author : HL \r\n# @Site : \r\n# @File : commentDemo.py \r\n# @Software: PyCharm\r\n\r\nimport json\r\nimport random\r\nimport time\r\n\r\nimport requests\r\n\r\nts = int(time.time())\r\nss2 = int(time.time() * 1000)\r\n_rticket = int(ss2 - 57000)\r\n\r\nHEADERS = {\r\n 'Host': 'api.amemv.com',\r\n 'Connection': 'keep-alive',\r\n # 'Cookie': 'install_id=86658687962; ttreq=1$81a11eb0423f772c6350c193f483aab91717bca1; odin_tt=fd7716c94fde70926ee34081f1fda9ad499571e9e6aa7a60bcea823d5871e60f1e358d6b57076eff17ec9ba6d6f99b19e0b6ad6f44e0494b2f601ecac591836f',\r\n 'accept-encoding': 'gzip',\r\n 'X-SS-REQ-TICKET': str(_rticket),\r\n 'sdk-version': '1',\r\n 'X-SS-DP': '1128',\r\n # 'x-tt-trace-id': '00-09234d0d58014020b8048053b1f14e73-09234d0d58014020-01',\r\n # 'X-Gorgon': '030000004001a1250b00b68de09217da1f43f701e76f2c3c288a',\r\n 'X-Khronos': str(int((str(int(ss2)))[:-3])),\r\n # 'accept-language': 'zh-CN,zh;q=0.9',\r\n # 'pragma': 'no-cache',\r\n # 'cache-control': 'no-cache',\r\n # 'upgrade-insecure-requests': '1',\r\n 'User-Agent': \"com.ss.android.ugc.aweme/800 (Linux; U; Android 5.1.1; zh_CN; SM-G955F; Build/JLS36C; Cronet/58.0.2991.0)\"\r\n}\r\n\r\nuser_video_params = {\r\n 'aweme_id': 6737461298134617351,\r\n 'cursor': 0,\r\n 'address_book_access': 1,\r\n 'gps_access': 1,\r\n 'forward_page_type': 1,\r\n '_rticket': _rticket,\r\n\r\n 'count': 20,\r\n 'os_api': 22,\r\n 'device_type': 'M-G955F',\r\n 'ssmix': 'a',\r\n 'manifest_version_code': 800,\r\n 'dpi': 320,\r\n 'js_sdk_version': '1.25.0.1',\r\n 'app_name': 'aweme',\r\n 'version_name': '8.0.0',\r\n 'ts': ts,\r\n 'app_type': 'normal',\r\n 'ac': 'wifi',\r\n 'update_version_code': 8002,\r\n 'channel': 'tengxun_new',\r\n 'device_platform': 'android',\r\n 'iid': 86658687962,\r\n 'version_code': 800,\r\n 'openudid': 'f46d0495fe505041',\r\n 'device_id': 68798464502,\r\n 'resolution': '1080*1920',\r\n 'os_version': '5.1.1',\r\n 'language': 'zh',\r\n 'device_brand': 'samsung',\r\n 'aid': 1128,\r\n 'mcc_mnc': '46007',\r\n 'uuid': 355757010244107,\r\n\r\n # 'max': 0,\r\n # # 'sec_user_id': 'MS4wLjABAAAAQEz_scsICUFGfJnBpg5qav7tH3Vx7f1RJklH1aTyNXM',\r\n # # 'retry_type': 'retry_type',\r\n # # 'uuid': '355757010244107',_cursor\r\n}\r\ntime1 = time.time()\r\nwhile True:\r\n res = requests.get('https://api.amemv.com/aweme/v2/comment/list/',\r\n headers=HEADERS, params=user_video_params)\r\n\r\n contentJson = json.loads(res.content.decode('utf-8'))\r\n time2 = 0\r\n aweme_list = contentJson.get('comments', [])\r\n for aweme in aweme_list:\r\n if time2 == 0:\r\n time2 = time.time()\r\n print(\"用时 \" + str(time2 - time1))\r\n else:\r\n pass\r\n print(\"number: 有值\")\r\n if contentJson.get('has_more'):\r\n max_cursor = contentJson.get('max_cursor')\r\n break\r\n else:\r\n time.sleep(round(random.uniform(1, 3), 1))\r\n pass\r\n","sub_path":"commentDemo.py","file_name":"commentDemo.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"14175350","text":"import logging\n\nfrom abc import ABC, abstractmethod\n\n\nfrom datarobot_drum.drum.common import (\n LOGGER_NAME_PREFIX,\n TargetType,\n StructuredDtoKeys,\n ModelInfoKeys,\n)\nfrom datarobot_drum.drum.utils import StructuredInputReadUtils\n\nlogger = logging.getLogger(LOGGER_NAME_PREFIX + \".\" + __name__)\n\nmlops_loaded = False\nmlops_import_error = None\ntry:\n from datarobot.mlops.mlops import MLOps\n\n mlops_loaded = True\nexcept ImportError as e:\n mlops_import_error = \"Error importing MLOps python module: {}\".format(e)\n\n\nclass BaseLanguagePredictor(ABC):\n def __init__(self):\n self._model = None\n self._positive_class_label = None\n self._negative_class_label = None\n self._class_labels = None\n self._code_dir = None\n self._params = None\n self._mlops = None\n\n def configure(self, params):\n self._code_dir = params[\"__custom_model_path__\"]\n self._positive_class_label = params.get(\"positiveClassLabel\")\n self._negative_class_label = params.get(\"negativeClassLabel\")\n self._class_labels = params.get(\"classLabels\")\n self._target_type = TargetType(params.get(\"target_type\"))\n self._params = params\n\n if self._params[\"monitor\"] == \"True\":\n if not mlops_loaded:\n raise Exception(\"MLOps module was not imported: {}\".format(mlops_import_error))\n # TODO: if server use async, if batch, use sync etc.. some way of passing params\n self._mlops = (\n MLOps()\n .set_model_id(self._params[\"model_id\"])\n .set_deployment_id(self._params[\"deployment_id\"])\n .set_channel_config(self._params[\"monitor_settings\"])\n .init()\n )\n\n def monitor(self, kwargs, predictions, predict_time_ms):\n if self._params[\"monitor\"] == \"True\":\n self._mlops.report_deployment_stats(\n num_predictions=len(predictions), execution_time_ms=predict_time_ms\n )\n\n # TODO: Need to convert predictions to a proper format\n # TODO: or add report_predictions_data that can handle a df directly..\n # TODO: need to handle associds correctly\n\n # mlops.report_predictions_data expect the prediction data in the following format:\n # Regression: [10, 12, 13]\n # Classification: [[0.5, 0.5], [0.7, 03]]\n # In case of classification, class names are also required\n class_names = self._class_labels\n if len(predictions.columns) == 1:\n mlops_predictions = predictions[predictions.columns[0]].tolist()\n else:\n mlops_predictions = predictions.values.tolist()\n if (\n self._positive_class_label is not None\n and self._negative_class_label is not None\n ):\n class_names = [self._negative_class_label, self._positive_class_label]\n\n df = StructuredInputReadUtils.read_structured_input_data_as_df(\n kwargs.get(StructuredDtoKeys.BINARY_DATA), kwargs.get(StructuredDtoKeys.MIMETYPE),\n )\n self._mlops.report_predictions_data(\n features_df=df, predictions=mlops_predictions, class_names=class_names\n )\n\n @abstractmethod\n def predict(self, **kwargs):\n \"\"\" Predict on input_filename or binary_data \"\"\"\n pass\n\n @abstractmethod\n def transform(self, **kwargs):\n \"\"\" Predict on input_filename or binary_data \"\"\"\n pass\n\n @abstractmethod\n def has_read_input_data_hook(self):\n \"\"\" Check if read_input_data hook defined in predictor \"\"\"\n pass\n\n def model_info(self):\n model_info = {\n ModelInfoKeys.TARGET_TYPE: self._target_type.value,\n ModelInfoKeys.CODE_DIR: self._code_dir,\n }\n\n if self._target_type == TargetType.BINARY:\n model_info.update({ModelInfoKeys.POSITIVE_CLASS_LABEL: self._positive_class_label})\n model_info.update({ModelInfoKeys.NEGATIVE_CLASS_LABEL: self._negative_class_label})\n elif self._target_type == TargetType.MULTICLASS:\n model_info.update({ModelInfoKeys.CLASS_LABELS: self._class_labels})\n\n return model_info\n","sub_path":"custom_model_runner/datarobot_drum/drum/language_predictors/base_language_predictor.py","file_name":"base_language_predictor.py","file_ext":"py","file_size_in_byte":4297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"479882046","text":"import numpy as np\nfrom astropy.time import Time\nfrom surveysim.kpno import mayall\n\ndef earthOrientation(MJD):\n \"\"\"\n This is an approximate formula because the ser7.dat file's range\n is not long enough for the duration of the survey.\n All formulae are from the Naval Observatory.\n\n Args:\n MJD: float\n\n Returns:\n x: float (arcseconds)\n y: float (arcseconds)\n UT1-UTC: float (seconds)\n \"\"\"\n\n T = 2000.0 + (MJD - 51544.03) / 365.2422\n UT2_UT1 = 0.022*np.sin(2.0*np.pi*T) - 0.012*np.cos(2.0*np.pi*T) \\\n - 0.006*np.sin(4.0*np.pi*T) + 0.007*np.cos(4.0*np.pi*T)\n A = 2.0*np.pi*(MJD-57681.0)/365.25\n C = 2.0*np.pi*(MJD-57681.0)/435.0\n x = 0.1042 + 0.0809*np.cos(A) - 0.0636*np.sin(A) + 0.0229*np.cos(C) - 0.0156*np.sin(C) \n y = 0.3713 - 0.0593*np.cos(A) - 0.0798*np.sin(A) - 0.0156*np.cos(C) - 0.0229*np.sin(C) \n UT1_UTC = -0.3259 - 0.00138*(MJD - 57689.0) - (UT2_UT1)\n return x, y, UT1_UTC\n\ndef mjd2lst(mjd):\n \"\"\"\n Converts decimal MJD to LST in decimal degrees\n\n Args:\n mjd: float\n\n Returns:\n lst: float (degrees)\n \"\"\"\n\n lon = str(mayall.west_lon_deg) + 'd'\n lat = str(mayall.lat_deg) + 'd'\n \n t = Time(mjd, format = 'mjd', location=(lon, lat))\n lst_tmp = t.copy()\n \n #try:\n # lst_str = str(lst_tmp.sidereal_time('apparent'))\n #except IndexError:\n # lst_tmp.delta_ut1_utc = -0.1225\n # lst_str = str(lst_tmp.sidereal_time('apparent'))\n\n x, y, dut = earthOrientation(mjd)\n lst_tmp.delta_ut1_utc = dut\n lst_str = str(lst_tmp.sidereal_time('apparent'))\n # 23h09m35.9586s\n # 01234567890123\n if lst_str[2] == 'h':\n lst_hr = float(lst_str[0:2])\n lst_mn = float(lst_str[3:5])\n lst_sc = float(lst_str[6:-1])\n else:\n lst_hr = float(lst_str[0:1])\n lst_mn = float(lst_str[2:4])\n lst_sc = float(lst_str[5:-1])\n lst = lst_hr + lst_mn/60.0 + lst_sc/3600.0\n lst *= 15.0 # Convert from hours to degrees\n return lst\n\ndef radec2altaz(ra, dec, lst):\n \"\"\"\n Converts from ecliptic to horizontal coordinate systems.\n\n Args:\n ra: float, observed right ascension (degrees)\n dec: float, observed declination (degrees)\n lst: float, local sidereal time (degrees)\n\n Returns:\n alt: float, altitude i.e. elevation (degrees)\n az: float, azimuth (degrees)\n \"\"\"\n h = np.radians(lst - ra)\n if h < 0.0:\n h += 2.0*np.pi\n d = np.radians(dec)\n phi = np.radians(mayall.lat_deg)\n \n sinAz = np.sin(h) / (np.cos(h)*np.sin(phi) - np.tan(d)*np.cos(phi))\n sinAlt = np.sin(phi)*np.sin(d) + np.cos(phi)*np.cos(d)*np.cos(h)\n\n if sinAlt > 1.0:\n sinAlt = 1.0\n if sinAlt < -1.0:\n sinAlt = -1.0\n if sinAz > 1.0:\n sinAz = 1.0\n if sinAz < -1.0:\n sinAz = -1.0\n\n return np.degrees(np.arcsin(sinAlt)), np.degrees(np.arcsin(sinAz))\n\ndef angsep(ra1, dec1, ra2, dec2):\n \"\"\"\n Calculates the angular separation between two objects.\n\n Args:\n ra1: float (degrees)\n dec1: float (degrees)\n ra2: float (degrees)\n dec2: float (degrees)\n\n Returns:\n delta: float (degrees)\n \"\"\"\n\n deltaRA = np.radians(ra1-ra2)\n DEC1 = np.radians(dec1)\n DEC2 = np.radians(dec2)\n cosDelta = np.sin(DEC1)*np.sin(DEC2) + np.cos(DEC1)*np.cos(DEC2)*np.cos(deltaRA)\n return np.degrees(np.arccos(cosDelta))\n\n\n","sub_path":"py/surveysim/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"401959239","text":"from src import plugins\nfrom config import settings\nimport requests\nfrom concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor\nclass BaseClient(object):\n\n def process(self):\n raise NotImplementedError('派生类必须实现process方法')\n\n def send(self,info):\n # 将资产数据发送到API\n print(settings.API)\n\n\n response = requests.post(\n url=settings.API,\n json = info\n # data = info\n )\n\nclass AgentClient(BaseClient):\n\n def process(self):\n\n info = plugins.server_info()\n self.send(info)\n\nclass SubBaseClient(BaseClient):\n def get_host_list(self):\n import json\n response = requests.get(settings.API)\n host_list = json.loads(response.text)\n return host_list\n def task(self,hostname):\n info = plugins.server_info(hostname)\n # 将数据发送到API\n self.send(info)\nclass SshClient(SubBaseClient):\n\n def process(self):\n # 获取今日未采集的主机列表 [c1.com,c2.com,c3.com]\n host_list = self.get_host_list()\n pool = ThreadPoolExecutor(10)\n for host in host_list:\n pool.submit(self.task,host)\n\n\n\nclass SaltClient(SubBaseClient):\n\n def process(self):\n # 获取今日未采集的主机列表\n host_list = self.get_host_list()\n pool = ThreadPoolExecutor(10)\n for host in host_list:\n pool.submit(self.task,host)","sub_path":"CMDB/Client/src/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"542390874","text":"# -*- coding:utf-8 -*-\n#@Time :2020/7/18 12:12\n#@Author : Sun\n#@File :conftest.py\n\nimport pytest\nimport yaml\nfrom pythoncode.calc import Calculator\n\n@pytest.fixture(scope='function', autouse=True)\ndef start():\n print(\"开始计算\")\n cla = Calculator()\n yield\n print(\"计算结束\")\n\n\ndef pytest_collection_modifyitems(session,config,items):\n print(items)\n print(len(items))\n #倒序执行 items里面的测试用例\n # items.reverse()\n \"\"\"\n 测试用例收集完成时,将收集到的item的name和nodeid的中文显示在控制台上\n :return:\n \"\"\"\n for item in items:\n item.name = item.name.encode(\"utf-8\").decode(\"unicode_escape\")\n print(item.nodeid)\n item._nodeid = item.nodeid.encode(\"utf-8\").decode(\"unicode_escape\")\n\n\n\n","sub_path":"testing/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"168131769","text":"import unittest\n\nimport numpy\n\nimport clpy\nfrom clpy import testing\n\n\nclass TestEinSumError(unittest.TestCase):\n\n # '...' ellipsis is not supported.\n def test_not_supported_ellipsis(self):\n with self.assertRaises(TypeError):\n clpy.einsum('...', 0)\n\n @testing.numpy_clpy_raises()\n def test_no_arguments(self, xp):\n xp.einsum()\n\n @testing.numpy_clpy_raises()\n def test_one_argument(self, xp):\n xp.einsum('')\n\n @testing.numpy_clpy_raises()\n def test_not_string_subject(self, xp):\n xp.einsum(0, 0)\n\n @testing.numpy_clpy_raises()\n def test_bad_argument(self, xp):\n xp.einsum('', 0, bad_arg=0)\n\n @testing.numpy_clpy_raises()\n def test_too_many_operands1(self, xp):\n xp.einsum('', 0, 0)\n\n @testing.numpy_clpy_raises()\n def test_too_many_operands2(self, xp):\n xp.einsum('i,j', xp.array([0, 0]), xp.array([0, 0]), xp.array([0, 0]))\n\n @testing.numpy_clpy_raises()\n def test_too_few_operands1(self, xp):\n xp.einsum(',', 0)\n\n @testing.numpy_clpy_raises()\n def test_many_dimension1(self, xp):\n xp.einsum('i', 0)\n\n @testing.numpy_clpy_raises()\n def test_many_dimension2(self, xp):\n xp.einsum('ij', xp.array([0, 0]))\n\n @testing.numpy_clpy_raises()\n def test_too_few_dimension(self, xp):\n xp.einsum('i->i', xp.arange(6).reshape(2, 3))\n\n @testing.numpy_clpy_raises()\n def test_invalid_char1(self, xp):\n xp.einsum('i%', xp.array([0, 0]))\n\n @testing.numpy_clpy_raises()\n def test_invalid_char2(self, xp):\n xp.einsum('j$', xp.array([0, 0]))\n\n @testing.numpy_clpy_raises()\n def test_invalid_char3(self, xp):\n xp.einsum('i->&', xp.array([0, 0]))\n\n # output subscripts must appear in inumpy.t\n @testing.numpy_clpy_raises()\n def test_invalid_output_subscripts1(self, xp):\n xp.einsum('i->ij', xp.array([0, 0]))\n\n # output subscripts may only be specified once\n @testing.numpy_clpy_raises()\n def test_invalid_output_subscripts2(self, xp):\n xp.einsum('ij->jij', xp.array([[0, 0], [0, 0]]))\n\n # output subscripts must not incrudes comma\n @testing.numpy_clpy_raises()\n def test_invalid_output_subscripts3(self, xp):\n xp.einsum('ij->i,j', xp.array([[0, 0], [0, 0]]))\n\n # dimensions much match when being collapsed\n @testing.numpy_clpy_raises()\n def test_invalid_diagonal1(self, xp):\n xp.einsum('ii', xp.arange(6).reshape(2, 3))\n\n @testing.numpy_clpy_raises()\n def test_invalid_diagonal2(self, xp):\n xp.einsum('ii->', xp.arange(6).reshape(2, 3))\n\n # invalid -> operator\n @testing.numpy_clpy_raises()\n def test_invalid_arrow1(self, xp):\n xp.einsum('i-i', xp.array([0, 0]))\n\n @testing.numpy_clpy_raises()\n def test_invalid_arrow2(self, xp):\n xp.einsum('i>i', xp.array([0, 0]))\n\n @testing.numpy_clpy_raises()\n def test_invalid_arrow3(self, xp):\n xp.einsum('i->->i', xp.array([0, 0]))\n\n @testing.numpy_clpy_raises()\n def test_invalid_arrow4(self, xp):\n xp.einsum('i-', xp.array([0, 0]))\n\n\n@testing.parameterize(\n {'shape_a': (2, 3), 'subscripts': 'ij'}, # do nothing\n {'shape_a': (2, 3), 'subscripts': 'ij'}, # transpose\n {'shape_a': (3, 3), 'subscripts': 'ii->i'}, # diagonal 2d\n {'shape_a': (3, 3, 3), 'subscripts': 'jii->ij'}, # partial diagonal 3d\n {'shape_a': (3, 3, 3), 'subscripts': 'iji->ij'}, # partial diagonal 3d\n {'shape_a': (3, 3, 3), 'subscripts': 'iii->i'}, # diagonal 3d\n {'shape_a': (2, 3, 4), 'subscripts': 'ijk->jik'}, # swap axes\n {'shape_a': (2, 3, 4), 'subscripts': 'ijk->kij'}, # swap axes\n {'shape_a': (2, 3, 4), 'subscripts': 'ijk->ikj'}, # swap axes\n {'shape_a': (2, 3, 4), 'subscripts': 'kji->ikj'}, # swap axes\n {'shape_a': (3,), 'subscripts': 'i->'}, # sum\n {'shape_a': (3, 3), 'subscripts': 'ii'}, # trace\n {'shape_a': (2, 2, 2, 2), 'subscripts': 'ijkj->kij'}, # trace\n {'shape_a': (2, 2, 2, 2), 'subscripts': 'ijij->ij'}, # trace\n {'shape_a': (2, 2, 2, 2), 'subscripts': 'jiji->ij'}, # trace\n)\nclass TestEinSumUnaryOperation(unittest.TestCase):\n # Avoid overflow\n skip_dtypes = (numpy.bool_, numpy.int8, numpy.uint8)\n\n @testing.for_all_dtypes(no_complex=True)\n @testing.numpy_clpy_allclose()\n def test_einsum_unary(self, xp, dtype):\n if dtype in self.skip_dtypes:\n return xp.array([])\n a = testing.shaped_arange(self.shape_a, xp, dtype)\n return xp.einsum(self.subscripts, a)\n\n\n@testing.parameterize(\n # outer\n {'shape_a': (2,), 'shape_b': (3,),\n 'subscripts': 'i,j', 'skip_overflow': False},\n # dot matvec\n {'shape_a': (2, 3), 'shape_b': (3,),\n 'subscripts': 'ij,j', 'skip_overflow': False},\n {'shape_a': (2, 3), 'shape_b': (2,),\n 'subscripts': 'ij,i', 'skip_overflow': False},\n # dot matmat\n {'shape_a': (2, 3), 'shape_b': (3, 4),\n 'subscripts': 'ij,jk', 'skip_overflow': False},\n # tensordot\n {'shape_a': (3, 4, 2), 'shape_b': (4, 3, 2),\n 'subscripts': 'ijk, jil -> kl', 'skip_overflow': True},\n # trace and tensordot and diagonal\n {'shape_a': (2, 3, 2, 4), 'shape_b': (3, 2, 2),\n 'subscripts': 'ijil,jkk->kj', 'skip_overflow': True},\n)\nclass TestEinSumBinaryOperation(unittest.TestCase):\n skip_dtypes = (numpy.bool_, numpy.int8, numpy.uint8)\n\n @testing.for_all_dtypes_combination(['dtype_a', 'dtype_b'])\n @testing.numpy_clpy_allclose()\n def test_einsum_binary(self, xp, dtype_a, dtype_b):\n if self.skip_overflow and (dtype_a in self.skip_dtypes or\n dtype_b in self.skip_dtypes):\n return xp.array([])\n a = testing.shaped_arange(self.shape_a, xp, dtype_a)\n b = testing.shaped_arange(self.shape_b, xp, dtype_b)\n return xp.einsum(self.subscripts, a, b)\n\n\nclass TestEinSumBinaryOperationWithScalar(unittest.TestCase):\n @testing.for_all_dtypes()\n @testing.numpy_clpy_allclose()\n def test_scalar_1(self, xp, dtype):\n shape_a = (2,)\n a = testing.shaped_arange(shape_a, xp, dtype)\n return xp.asarray(xp.einsum(',i->', 3, a))\n\n @testing.for_all_dtypes()\n @testing.numpy_clpy_allclose()\n def test_scalar_2(self, xp, dtype):\n shape_a = (2,)\n a = testing.shaped_arange(shape_a, xp, dtype)\n return xp.asarray(xp.einsum('i,->', a, 4))\n\n\n@testing.parameterize(\n {'shape_a': (2, 3), 'shape_b': (3, 4), 'shape_c': (4, 5),\n 'subscripts': 'ij,jk,kl', 'skip_overflow': True},\n {'shape_a': (2, 4), 'shape_b': (2, 3), 'shape_c': (2,),\n 'subscripts': 'ij,ik,i->ijk', 'skip_overflow': False},\n {'shape_a': (2, 4), 'shape_b': (3, 2), 'shape_c': (2,),\n 'subscripts': 'ij,ki,i->jk', 'skip_overflow': False},\n)\nclass TestEinSumTernaryOperation(unittest.TestCase):\n skip_dtypes = (numpy.bool_, numpy.int8, numpy.uint8)\n\n @testing.for_all_dtypes(no_complex=True)\n @testing.numpy_clpy_allclose(contiguous_check=False)\n def test_einsum_ternary(self, xp, dtype):\n if self.skip_overflow and dtype in self.skip_dtypes:\n return xp.array([])\n a = testing.shaped_arange(self.shape_a, xp, dtype)\n b = testing.shaped_arange(self.shape_b, xp, dtype)\n c = testing.shaped_arange(self.shape_c, xp, dtype)\n return xp.einsum(self.subscripts, a, b, c).astype(numpy.float32)\n","sub_path":"tests/clpy_tests/linalg_tests/test_einsum.py","file_name":"test_einsum.py","file_ext":"py","file_size_in_byte":7338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"316645018","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n\r\nimport wx\r\n\r\nclass ChildFrame(wx.Frame):\r\n def __init__(self, parent):\r\n wx.Frame.__init__(self, parent, -1, \"child frame\", pos=(100, 100))\r\n\r\nclass MyWindow(wx.Frame):\r\n def __init__(self, parent, id):\r\n wx.Frame.__init__(self, parent, id, \"main frame\")\r\n panel = wx.Panel(self)\r\n self.showChildBtn = wx.Button(panel, label=\"show child\", pos=(10, 10))\r\n self.exitBtn = wx.Button(panel, label=\"exit\", pos=(100, 10))\r\n self.Bind(wx.EVT_BUTTON, self.showChild, self.showChildBtn)\r\n self.Bind(wx.EVT_BUTTON, self.exit, self.exitBtn)\r\n def showChild(self, event):\r\n childFrame = ChildFrame(self)\r\n childID = childFrame.Show()\r\n def exit(self, event):\r\n self.Close(True)\r\n\r\nif __name__ == '__main__':\r\n app = wx.App(0)\r\n frame = MyWindow(parent=None, id=-1)\r\n frame.Show()\r\n app.MainLoop()\r\n","sub_path":"src/TopWindow.py","file_name":"TopWindow.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"191221948","text":"'''\nGiven a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.\n\nA region is captured by flipping all 'O's into 'X's in that surrounded region.\n\nExample:\n\nX X X X\nX O O X\nX X O X\nX O X X\nAfter running your function, the board should be:\n\nX X X X\nX X X X\nX X X X\nX O X X\n'''\n\ndef surround(board):\n if not board: return \n M = len(board)\n N = len(board[0])\n \n for i in range(M):\n for j in range(N):\n if board[i][j] == 'O':\n board[i][j] = '$'\n\n def fill(i, j):\n if i < 0 or i >= M or j < 0 or j >= N or board[i][j] != '$':\n return\n\n board[i][j] = 'O'\n\n fill(i+1, j)\n fill(i-1, j)\n fill(i, j+1)\n fill(i, j-1)\n\n for i in range(M):\n for j in range(N):\n if (i in [0, M-1] or j in [0, N-1]) and board[i][j] == '$':\n fill(i, j)\n \n for i in range(M):\n for j in range(N):\n if board[i][j] == '$':\n board[i][j] = 'X'\n\n return board\n\n","sub_path":"algorithms/graphs/surround_region.py","file_name":"surround_region.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"154377382","text":"DEFAULT_USER_COL = \"userID\"\nDEFAULT_ITEM_COL = \"itemID\"\nDEFAULT_RATING_COL = \"rating\"\nDEFAULT_TIMESTAMP_COL = \"timestamp\"\nDEFAULT_PREDICTION_COL = \"prediction\"\nDEFAULT_HEADER = (\n DEFAULT_USER_COL,\n DEFAULT_ITEM_COL,\n DEFAULT_RATING_COL,\n DEFAULT_TIMESTAMP_COL,\n)\nDEFAULT_SPLIT_FLAG = \"split_flag\"\nDEFAULT_TEST_SIZE = 0.2\nDEFAULT_VAL_SIZE = 0.2\n","sub_path":"utils/common/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"271076485","text":"import time\nimport importlib\n\nfrom tsp_utilities import *\n\n##############################################\n## ADD HERE YOUR NEW SOLVERS CLASSES #########\n##############################################\nactive_solvers = [\"Bruteforce\",\n #\"Dwave_tsp\",\n \"TSP_genetico\"]\n##############################################\n##############################################\n\ndef main():\n\n starting_node = 0\n nodes = 5\n\n G = get_graph(nodes)\n cost_matrix = get_cost_matrix(G, nodes)\n\n for solver_ in active_solvers:\n ClassName = getattr(importlib.import_module(\"solvers.\"+solver_.lower()), solver_)\n instance = ClassName()\n route = instance.calculate(G, cost_matrix, starting_node)\n print(\"Route for %s:\" % solver_)\n print(route)\n print(\"Cost: %s\" % calculate_cost(cost_matrix, route))\n draw_tsp_solution(G, route)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"506903155","text":"\"\"\"\n@brief Example \"four panel\" performance plots using pyIrfLoader.\n\n@author J. Chiang\n\"\"\"\n#\n# $Header$\n#\n\nimport bisect\nimport numpy as num\nimport pylab\nimport pyIrfLoader\n\nclass FunctionWrapper(object):\n def __init__(self, func):\n self.func = func\n def __call__(self, xx, **kwds):\n try:\n y = []\n for x in xx:\n y.append(self.func(x, **kwds))\n if isinstance(xx, num.ndarray):\n y = num.array(y)\n return y\n except TypeError:\n return self.func(xx, **kwds)\n def __getattr__(self, attrname):\n return getattr(self.func, attrname)\n\n_win_id = 0\n\nclass Window(object):\n def __init__(self, id=None):\n global _win_id\n if id is None:\n id = _win_id\n _win_id += 1\n self.fig = pylab.figure(id)\n self.axes = self.fig.add_subplot(111)\n self.id = id\n def set_title(self, title):\n self.axes.set_title(title)\n\ndef setAxis(xrange=None, yrange=None):\n axisrange = list(pylab.axis())\n if xrange is not None:\n axisrange[:2] = xrange\n if yrange is not None:\n axisrange[2:] = yrange\n pylab.axis(axisrange)\n\ndef plot_curve(x, y, xlog=0, ylog=0, xname='x', yname='y', \n oplot=0, color='k', lineStyle='-', linewidth=1,\n xrange=None, yrange=None):\n if oplot == 0:\n win = Window()\n else:\n win = None\n marker = '%s%s' % (color, lineStyle)\n if xlog and ylog:\n pylab.loglog(x, y, marker, markersize=3, linewidth=linewidth)\n elif xlog:\n pylab.semilogx(x, y, marker, markersize=3, linewidth=linewidth)\n elif ylog:\n pylab.semilogy(x, y, marker, markersize=3, linewidth=linewidth)\n else:\n pylab.plot(x, y, marker, markersize=3, linewidth=linewidth)\n if not oplot:\n pylab.xlabel(xname)\n pylab.ylabel(yname)\n setAxis(xrange, yrange)\n return win\n\nlogspace = lambda xmin, xmax, nx : num.logspace(num.log10(xmin),\n num.log10(xmax), nx)\n\npyIrfLoader.Loader_go()\n\nfactory = pyIrfLoader.IrfsFactory_instance()\n\nirfName = \"P7SOURCE_V6MC\"\n\nfront = factory.create(irfName + \"::FRONT\")\nback = factory.create(irfName + \"::BACK\")\n\npsf_f = front.psf()\npsf_b = back.psf()\n\nradii = logspace(1e-2, 30., 30)\n\n@FunctionWrapper\ndef theta_68(energy, psf=None, inc=0, phi=0, frac=0.68):\n f = FunctionWrapper(lambda x : psf.angularIntegral(energy, inc, phi, x))\n y = f(radii)\n indx = bisect.bisect(y, frac) - 1\n return ((frac - y[indx])/(y[indx+1] - y[indx])\n *(radii[indx+1] - radii[indx]) + radii[indx])\n\nenergies = logspace(20., 3e5, 40)\nplot1 = plot_curve(energies, theta_68(energies, psf=psf_f),\n xlog=1, ylog=1, xname='Energy (MeV)',\n yname='theta_68 (deg)')\nplot1.set_title('normal incidence')\nplot_curve(energies, theta_68(energies, psf=psf_b), oplot=1, lineStyle=':')\n\naeff_f = front.aeff()\naeff_b = back.aeff()\n\n@FunctionWrapper\ndef aeff(energy, aeffObj=None, inc=0, phi=0):\n return aeffObj.value(energy, inc, phi)\n\nplot2 = plot_curve(energies, aeff(energies, aeffObj=aeff_f), xlog=1,\n xname='Energy (MeV)', yname='eff. area (cm^2)')\nplot2.set_title('normal incidence')\nplot_curve(energies, aeff(energies, aeffObj=aeff_b), oplot=1, lineStyle=':')\n\n@FunctionWrapper\ndef aeff_profile(inc, aeffObj=None, energy=1e3, phi=0):\n return aeffObj.value(energy, inc, phi)\n\nthetas = num.arange(70, dtype=float)\n\nplot3 = plot_curve(thetas, aeff_profile(thetas, aeffObj=aeff_f),\n xname='inclination (deg)', yname='eff. area (cm^2)')\nplot3.set_title('E = 1 GeV')\nplot_curve(thetas, aeff_profile(thetas, aeffObj=aeff_b), oplot=1,\n lineStyle=':')\n\n@FunctionWrapper\ndef th68_profile(inc, psf=None, energy=1e3, phi=0, frac=0.68):\n f = FunctionWrapper(lambda x : psf.angularIntegral(energy, inc, phi, x))\n y = f(radii)\n indx = bisect.bisect(y, frac) - 1\n return ((frac - y[indx])/(y[indx+1] - y[indx])\n *(radii[indx+1] - radii[indx]) + radii[indx])\n\nplot4 = plot_curve(thetas, th68_profile(thetas, psf=psf_f),\n xname='inclination (deg)', yname='theta_68 (deg)')\nplot4.set_title('E = 1 GeV')\nplot_curve(thetas, th68_profile(thetas, psf=psf_b), oplot=1,\n lineStyle=':')\n","sub_path":"pyIrfLoader/python/four_panel.py","file_name":"four_panel.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"4950070","text":"#!/usr/bin/python\n\nimport sys\nfrom functools import reduce\n\n# ALGORITHM:\n# obtain file name from sys.argv[1]\n# check that file exists\n# try read contents from file\n# parse contents:\n\t# skip empty lines and comments\n\t# if non-empty line, read states from it\n\t# check states are valid\n\t# read next N lines\n\t\t# check line syntax:\n\t\t\t# has N+1 words\n\t\t\t# fist word is in states[]\n\t\t\t# other words are floats\n\t\t# add rules to table\n\t# check table\n\t\t# give error if normalization fails\n\t\t# give warning if semi-detailed balance fails\n# generate collision function to argv[2]\n\ndef error(message):\n\tprint()\n\tprint(\"ERROR\", message)\n\tprint()\n\tsys.exit(1)\n\ndef extract_words(line):\n\treturn [x for x in line.replace('\\t', ' ').split(' ') if x.strip()]\n\ndef validate_prob(word, line):\n\ttry:\n\t\tnum=float(word)\n\t\tif num>=0 and num<=1:\n\t\t\treturn\n\texcept ValueError:\n\t\tpass\n\terror(\"Not a probability (\" + str(word) + ') in line: ' + line)\n\ndef validate_state(word, line):\n\ttry:\n\t\tnum=int(word)\n\t\tif num>=0 and num<=255:\n\t\t\treturn\n\texcept ValueError:\n\t\tpass\n\terror(\"Not a state (\" + str(word) + ') in line: ' + line)\n\nrules={}\n\ndef init_rules():\n\tglobal rules\n\tfor i in range(256):\n\t\trules[i]={i: 1.0}\n\ndef add_rule(s0, s1, p):\n\tglobal rules\n\trules[s0][s1]=p\n\tif p==0:\n\t\tdel rules[s0][s1]\n\ndef is_deterministic():\n\tfor r in rules:\n\t\tif len(rules[r])>1:\n\t\t\treturn False\n\treturn True\n\ninit_rules()\n\nif len(sys.argv) != 3:\n\tprint()\n\tprint(\"Usage:\", sys.argv[0], \"\", \"\")\n\tprint()\n\tsys.exit()\n\ntry:\n\tlines=[x for x in open(sys.argv[1]).readlines() if x.strip()]\nexcept IOError:\n\terror(\"ERROR: Failed to read from file \" + sys.argv[1])\n\ni=0\nwhile i= len(lines):\n\t\terror(\"Unexpected end of file, need more lines for states (\" +\\\n\t\t\t', '.join(states) + '), given in line ' + line);\n\ti+=1\n\tfor j in range(len(states)):\n\t\twords=extract_words(lines[i+j])\n\t\tif len(words) != len(states)+1:\n\t\t\terror(\"Too few words in line \" + lines[i+j])\n\t\tvalidate_state(words[0], lines[i+j])\n\t\tif words[0] != states[j]:\n\t\t\terror(\"Invalid state (\" + words[0] + \"), need (\" +\\\n\t\t\t\tstates[j] + \") in line \" + lines[i+j])\n\t\tfor k in range(len(words)-1):\n\t\t\tvalidate_prob(words[k+1], lines[i+j])\n\t\t\tadd_rule(int(words[0]), int(states[k]), float(words[k+1]))\n\ti+=len(states)\n\n# check normalization\nfor s0 in range(256):\n\tsum_prob=0\n\tif len(rules[s0])>0:\n\t\tsum_prob=reduce(lambda x, y: x+y,\n\t\t\t[rules[s0][s1] for s1 in rules[s0]])\n\tif abs(sum_prob-1)>0.0000001:\n\t\terror(\"Normalization fails for state (\" + str(s0) +\\\n\t\t\t\"), sum prob is \" + str(sum_prob))\n\n# generate code\ntry:\n\tf=open(sys.argv[2], 'w')\n\tf.write(\"char collide(char cell)\\n\")\n\tf.write(\"{\\n\")\n\tif not is_deterministic():\n\t\tf.write(\"\\tdouble r=drand48();\\n\")\n\tf.write(\"\\tswitch(cell) {\\n\")\n\tfor s0 in range(256):\n\t\tif len(rules[s0])==1 and s0 in rules[s0]:\n\t\t\tcontinue # trivial rule\n\t\tf.write(\"\\t\\tcase \" + str(s0) + \":\\n\")\n\t\tcur_prob=0\n\t\tfor s1, prob in rules[s0].items():\n\t\t\tcur_prob+=prob\n\t\t\tif cur_prob<1.0:\n\t\t\t\tf.write(\"\\t\\t\\tif (r<\" + str(cur_prob) + \") return \" +\\\n\t\t\t\t\tstr(s1) + \";\\n\")\n\t\t\telse:\n\t\t\t\tf.write(\"\\t\\t\\treturn \" + str(s1) + \";\\n\");\n\tf.write(\"\\t\\tdefault:\\n\")\n\tf.write(\"\\t\\t\\treturn cell;\\n\")\n\tf.write(\"\\t}\\n\")\n\tf.write(\"}\\n\")\nexcept IOError:\n\terror(\"Failed to write output to file \" + sys.argv[2])\n","sub_path":"system/gen_collide.py","file_name":"gen_collide.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"164042749","text":"from django.db import models\nfrom django.contrib.auth.models import AbstractUser\n\nfrom .constants import *\n\nclass User(AbstractUser):\n \"\"\"\n Extended UserModel.\n Extra Field that are required for the User Model\n are added here.\n Any changes here should also be reflected in admin.ADDITIONAL_FIELDS\n so they can appear on the admin panel\n \"\"\"\n has_changed_username = models.BooleanField(default=False,verbose_name=\"Has changed username?\")\n last_login = models.DateTimeField(verbose_name=\"Last Logged in\", blank=True, null=True)\n role = models.SmallIntegerField(\n choices=USER_ROLES, \n null = True,\n verbose_name=\"User Role\", \n help_text=\"\"\"\n This is an integer field, each role is assigned a specific integer: \n 0 for Students \n 1 for Teachers \n 2 for Principals \n \"\"\"\n )\n\n\nclass School(models.Model):\n created_by = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)\n name = models.CharField(max_length=50, verbose_name=\"Name\")\n location = models.TextField(max_length=150, blank=True, verbose_name=\"Location\")\n\n def __unicode__(self):\n return self.name\n \n def __str__(self):\n return self.name+', '+self.location\n\n\n\nclass Student(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n name = models.CharField(max_length=40, blank=True, verbose_name=\"Name\")\n city = models.CharField(max_length=30, blank=True, verbose_name=\"City\")\n school = models.ForeignKey(School, null=True, blank=True, on_delete=models.SET_NULL)\n standard = models.PositiveSmallIntegerField(choices=STUDENT_STD, null=True, blank=True, verbose_name=\"Class\")\n email = models.EmailField(max_length=254, blank=True, verbose_name=\"Email\")\n contact_no = models.CharField(max_length=20, blank=True, verbose_name=\"Contact No\")\n guardian_name = models.CharField(max_length=40, blank=True, verbose_name=\"Parents/Guardian's Name\")\n guardian_contact = models.CharField(max_length=20, blank=True, verbose_name=\"Parents/Guardian's Contact No\")\n guardian_address = models.TextField(max_length=150, blank=True, verbose_name=\"Parents/Guardian's Address\")\n\n\n def __unicode__(self):\n return self.name\n \n def __str__(self):\n return self.name\n\n","sub_path":"webD-backend/authentication/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"519894845","text":"import sys\nimport math\n\nsys.setrecursionlimit(10**6)\ninput = sys.stdin.readline\n\n\ndef dist(p1, p2):\n return math.sqrt((p1[0]-p2[0])**2 + (p1[1] - p2[1])**2)\n\n\ndef getP(x: int):\n if parents[x] == x:\n return x\n parents[x] = getP(parents[x])\n return parents[x]\n\n\ndef union(x: int, y: int):\n px, py = getP(x), getP(y)\n if px > py:\n parents[px] = py\n else:\n parents[py] = px\n\n\ndef find(x: int, y: int):\n px, py = getP(x), getP(y)\n return px == py\n\n\nN, M = map(int, input().split())\n# 0 사용 X , 각 노드의 위치\npoints = [list(map(float, input().split()))for _ in range(N)]\npoints = [[0, 0]] + points\n# 미리 연결된 노드\nnode_connected = [list(map(int, input().split())) for _ in range(M)]\n\nparents = [i for i in range(N+1)] # N개의 정점의 부모 ( 0 사용 X )\nans = 0\nfor i in range(len(node_connected)):\n u, v = node_connected[i]\n union(u, v)\n # ans += dist(points[u], points[v])\n\n# 모든 간선에대해, 크루스칼 적용\nedges = []\nfor i in range(1, N+1):\n for j in range(1, N+1):\n if i == j:\n continue\n edges.append((i, j, dist(points[i], points[j])))\nedges.sort(key=lambda x: x[2])\nfor i in range(len(edges)):\n u, v, w = edges[i]\n if not find(u, v):\n union(u, v)\n ans += w\n\n# print(\"%.2f\" % ans)\nprint(round(ans, 2))\n","sub_path":"BOJ_Gold/1774.py","file_name":"1774.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"66605391","text":"from selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium import webdriver\nimport time\nimport math\n#import os\n\ntry: \n link = \"http://suninjuly.github.io/explicit_wait2.html\"\n browser = webdriver.Chrome()\n #browser.implicitly_wait(5)\n browser.get(link)\n\n price_element=WebDriverWait(browser,12).until(EC.text_to_be_present_in_element((By.ID,\"price\"),\"$100\"))\n #price=price_element.text\n book_button=browser.find_element(By.ID,\"book\")\n book_button.click()\n \n x_element=browser.find_element_by_css_selector(\"#input_value\")\n x=x_element.text\n result=str(math.log(abs(12*math.sin(int(x)))))\n result_input=browser.find_element_by_css_selector(\"input#answer\")\n result_input.send_keys(result)\n submit_button=browser.find_element(By.ID,'solve') #WebDriverWait(browser,2).until(EC.element_to_be_clickable((By.ID,'submit')))\n submit_button.click()\n\n \nfinally:\n # ожидание чтобы визуально оценить результаты прохождения скрипта\n time.sleep(20)\n # закрываем браузер после всех манипуляций\n browser.quit()\n","sub_path":"Scripts/Module2/lesson2_4_step8.py","file_name":"lesson2_4_step8.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"187041988","text":"#!/usr/bin/env python\r\n# !-*-coding:utf-8 -*-\r\n\"\"\"\r\n@version: python3.7\r\n@author: v-enshi\r\n@license: Apache Licence\r\n@contact: 123@qq.com\r\n@site:\r\n@software: PyCharm\r\n@file: Queries2.py\r\n@time: 2019/4/22 14:21\r\n\r\ntraing epoch =8\r\nlstm+attan\r\nno test\r\n\"\"\"\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\nimport random\r\nimport numpy as np\r\nimport time\r\n\r\n\r\ntime_start = time.time()\r\ntorch.manual_seed(1)\r\n\r\nuse_gpu = False\r\n#use_gpu = True\r\nif use_gpu:\r\n device = torch.device(\"cuda\")\r\n max_vocab_size = 10000\r\n CONTEXT_WINDOW = 100\r\nelse:\r\n device = torch.device(\"cpu\")\r\n max_vocab_size = 100\r\n CONTEXT_WINDOW = 100\r\n\r\n##1. data loading\r\narr=np.load(r\"../data/python/training.npz\")\r\ninputs = arr['input_data']\r\nparents = arr['parent_data']\r\ntargets = arr['target_data']\r\nvalue_vocab = arr['value_vocab'].item()\r\ntype_vocab = arr['type_vocab'].item()\r\n\r\n\r\ndata_loading = time.time()\r\nprint(\"data loading\", data_loading - time_start)\r\n\r\n\r\n##2. parameters setting\r\nif use_gpu:\r\n EMBEDDING_value = 1200\r\n EMBEDDING_type = 300\r\n HIDDEN_SIZE = 1500\r\n BATCH_SIZE = 1\r\nelse:\r\n EMBEDDING_value = 2\r\n EMBEDDING_type = 3\r\n HIDDEN_SIZE = 5\r\n\r\n BATCH_SIZE = 1\r\n\r\n## 3.1 LSTM component\r\nclass LSTM_component(nn.Module):\r\n\r\n def __init__(self, vocab_value_size, value_dim, vocab_type_size, type_dim,\r\n hidden_dim, batch_size, context_window, dropout_p=0.5):\r\n super(LSTM_component, self).__init__()\r\n self.hidden_dim = hidden_dim\r\n self.batch_size = batch_size\r\n self.context_window = context_window\r\n self.value_embeddings = nn.Embedding(vocab_value_size, value_dim)\r\n self.type_embeddings = nn.Embedding(vocab_type_size, type_dim)\r\n self.dropout = nn.Dropout(dropout_p)\r\n self.lstm = nn.LSTM(value_dim + type_dim, hidden_dim)\r\n\r\n def forward(self, sentence, hc):\r\n\r\n embeds_type = self.type_embeddings(sentence[0])\r\n embeds_value = self.value_embeddings(sentence[1])\r\n embeds = torch.cat([embeds_value, embeds_type], 1).view(len(sentence[0]), 1, -1)\r\n h0 = hc[0]\r\n c0 = hc[1]\r\n embeds[:-self.context_window]\r\n\r\n lstm_out1, (lstm_h1, lstm_c1) = self.lstm(self.dropout(embeds[:-self.context_window]), (h0, c0))\r\n\r\n lstm_out, (lstm_h, lstm_c) = self.lstm(embeds[-self.context_window:], (lstm_h1, lstm_c1))\r\n\r\n return lstm_out, lstm_h, lstm_c\r\n\r\n def initHidden(self):\r\n return torch.zeros(1, self.batch_size, self.hidden_dim, device=device), torch.zeros(1, self.batch_size,\r\n self.hidden_dim,\r\n device=device)\r\n\r\n'''\r\nmodel_LSTM = LSTM_component(20,EMBEDDING_value,10,EMBEDDING_type,HIDDEN_SIZE, BATCH_SIZE)\r\n\r\n\r\nwith torch.no_grad():\r\n inputs =torch.tensor([[ 5, 11, 5, 11, 5, 11, 5, 11, 5, 12],\r\n [ 0, 0, 0, 0, 6, 0, 8, 0, 0, 7]])\r\n output, hn,cn = model_LSTM(inputs,model_LSTM.initHidden())\r\n print(\"tag_scorces\", output, hn,cn)\r\n'''\r\n\r\n## 3.2 attention component\r\nclass Context_atten(nn.Module):\r\n def __init__(self, hidden_dim, context_window, dropout_p=0.25):\r\n super(Context_atten, self).__init__()\r\n self.hidden_dim = hidden_dim\r\n self.context_window = context_window\r\n\r\n self.Wm = nn.Parameter(torch.ones(hidden_dim, hidden_dim))\r\n self.V = nn.Parameter(torch.ones(hidden_dim, 1))\r\n self.linear1 = nn.Linear(hidden_dim, hidden_dim, bias=False)\r\n\r\n def forward(self, inputs, hc):\r\n # Mt = inputs[-self.context_window:,:,:]\r\n Mt = inputs.view(self.context_window, self.hidden_dim) #\r\n one_TL = torch.ones(self.context_window, 1, device=device) # (L,1)\r\n\r\n At = torch.mm(torch.tanh(torch.mm(Mt, self.Wm) + torch.mm(one_TL, self.linear1(hc.view(1, -1)))), self.V)\r\n alphat = F.softmax(At.view(1, -1), dim=1) # [1,3]\r\n ct = torch.mm(alphat, Mt)\r\n return alphat, ct\r\n\r\n\r\n'''\r\nmodel_catten = Context_atten(HIDDEN_SIZE, CONTEXT_WINDOW)\r\n\r\nwith torch.no_grad():\r\n alpha , out_ct = model_catten (output, hn)\r\n print(out_ct)\r\n'''\r\n\r\n\r\n## 3.3parent attention\r\nclass Parent_atten(nn.Module):\r\n def __init__(self, hidden_dim, context_window):\r\n super(Parent_atten, self).__init__()\r\n self.hidden_dim = hidden_dim\r\n self.context_window = context_window\r\n self.Wg_linear = nn.Linear(hidden_dim * 3, hidden_dim, bias=False)\r\n self.Wv_linear = nn.Linear(hidden_dim, self.context_window)\r\n\r\n def forward(self, ht, ct, pt):\r\n Gt = torch.tanh(self.Wg_linear(torch.cat([ht.view(1, -1), ct.view(1, -1), pt.view(1, -1)], 1)))\r\n yt = F.log_softmax(self.Wv_linear(Gt), dim=1)\r\n return yt\r\n\r\n\r\n'''\r\nmodel_par_atten_type = Parent_atten(HIDDEN_SIZE, CONTEXT_WINDOW)\r\nwith torch.no_grad():\r\n Yt_type = model_par_atten_type ( hn,out_ct,output[6])\r\n print(Yt_type)\r\n\r\n'''\r\n\r\n## 3 main model\r\nclass main_model(nn.Module):\r\n def __init__(self, vocab_value_size, value_dim, vocab_type_size, type_dim,\r\n hidden_dim, batch_size, context_window, dropout_p=0.25):\r\n super(main_model, self).__init__()\r\n self.hidden_dim = hidden_dim\r\n self.batch_size = batch_size\r\n self.context_window = context_window\r\n\r\n self.model_LSTM = LSTM_component(vocab_value_size, value_dim, vocab_type_size, type_dim, hidden_dim, batch_size,\r\n context_window).to(device)\r\n self.model_catten = Context_atten(hidden_dim, context_window).to(device)\r\n self.model_par_atten_value = Parent_atten(hidden_dim, vocab_value_size).to(device)\r\n\r\n def forward(self, inputs, hc, parent):\r\n output, hn, cn = self.model_LSTM(inputs, hc)\r\n alpha, out_ct = self.model_catten(output, hn)\r\n Yt = self.model_par_atten_value(hn, out_ct, output[-parent - 1])\r\n return Yt\r\n\r\n def initHidden(self):\r\n return torch.zeros(1, self.batch_size, self.hidden_dim, device=device), torch.zeros(1, self.batch_size,\r\n self.hidden_dim,\r\n device=device)\r\n\r\n\r\n## 4 training\r\nmodel = main_model(len(value_vocab), EMBEDDING_value, len(type_vocab), EMBEDDING_type, HIDDEN_SIZE, BATCH_SIZE,CONTEXT_WINDOW).to(device)\r\nloss_function = nn.NLLLoss()\r\nlearning_rate = 0.01\r\ndecay = 0.6\r\noptimizer = optim.SGD(model.parameters(), lr=learning_rate, weight_decay=decay)\r\nclip = 5\r\nnn.utils.clip_grad_norm_(model.parameters(), clip)\r\nlosses = []\r\n\r\nstaring_training = time.time()\r\nprint(\"staring training \",staring_training-time_start)\r\nnum_epochs=8\r\nfor epoch in range(num_epochs):\r\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\r\n print('-' * 10)\r\n total_loss = 0\r\n print_loss_total = 0 # Reset every print_every\r\n plot_loss_total = 0 # Reset every plot_every\r\n # query = [context, predict_node, position, same_node_position, parent_node_position]\r\n print(len(targets))\r\n for i in range(len(targets)):\r\n start = time.time()\r\n # step1 init\r\n optimizer.zero_grad()\r\n # step 2 prepare the data\r\n #print(\"inputs[i]\",i,inputs[i])\r\n input = [torch.tensor(inputs[i][0] ,device=device),torch.tensor(inputs[i][1],device=device)]\r\n parent = parents[i]\r\n target = torch.tensor([targets[i]], dtype =torch.long,device=device)\r\n #\r\n\r\n # step 3 get the scorece\r\n yt_point = model(input, model.initHidden(), parent)\r\n #print(\"y_point\",yt_point)\r\n\r\n # step 4 train\r\n loss = loss_function(yt_point.view(1, -1), target)\r\n\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # loss\r\n total_loss += loss.item()\r\n topv, topi = yt_point.data.topk(1)\r\n eval_index = topi.squeeze().detach()\r\n # print(eval_index)\r\n end = time.time()\r\n print(i,\"batch time spend\",end-start)\r\n\r\n now = time.time()\r\n length = len(inputs[i][0])\r\n print('epoch = %d time spend:%s loss average%.4f' % (\r\n epoch + 1, now - time_start, total_loss / length))\r\n losses.append(total_loss / length)\r\n\r\nprint(losses)\r\ntorch.save(model.state_dict(), 'params_lstm_attn.pkl')\r\nmodel.load_state_dict(torch.load('params_lstm_attn.pkl'))\r\n","sub_path":"source code/model2.py","file_name":"model2.py","file_ext":"py","file_size_in_byte":8528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"93540276","text":"from . import halconfig_types as types\nfrom . import halconfig_dependency as dep\n\nname = \"UARTNCP\"\ndisplayname = \"UART NCP\"\ncompatibility = dep.Dependency() # all\ncategory = \" NCP\"\nstudio_module = {\n \"basename\": \"SDK.HAL.UARTNCP\",\n \"modules\": [types.StudioFrameworkModule(\"ZIGBEE\", types.Framework.ZNET),\n types.StudioFrameworkModule(\"THREAD\", types.Framework.THREAD),\n types.StudioFrameworkModule(\"BLE\", types.Framework.BLE)],\n }\noptions = {\n \"BSP_UARTNCP_USART_PORT\": {\n \"type\": types.Peripheral(filter=[\"USART\", \"UART\", \"LEUART\"],\n inherit_options=True,\n define_value_prefix=\"HAL_SERIAL_PORT_\",\n mode=\"uart\"),\n \"description\": \"UART port\",\n \"longdescription\": \"Select UART port for NCP communication\",\n },\n}\n","sub_path":"platform/hwconf_data/efr32fg14p/modules/UARTNCP/UARTNCP_model.py","file_name":"UARTNCP_model.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"74029317","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/linjiao/dv/beim/beim/scripts/build.py\n# Compiled at: 2013-12-08 21:45:16\n\n\ndef build(export_root):\n import sys, os\n pwd = os.path.abspath(os.curdir)\n import sys\n sys.path = [\n pwd] + sys.path\n from beim.build import build_release, clean_up\n rt = build_release(pwd, export_root=export_root)\n if rt:\n import sys\n sys.exit(1)\n\n\ndef getsrc():\n p = 'src'\n if hasSubdirs(p):\n return\n from .getsrc import main\n main()\n\n\ndef hasSubdirs(p):\n skip = '.svn'\n import os\n entries = os.listdir(p)\n for e in entries:\n if e in skip:\n continue\n p1 = os.path.join(p, e)\n if os.path.isdir(p1):\n return True\n continue\n\n return False\n\n\ndef main():\n getsrc()\n import sys, os, shlex\n from beim.datastore import open\n build_info = open('build_info')\n if len(sys.argv) == 2:\n export_root = sys.argv[1]\n elif build_info.get('export_root'):\n export_root = build_info['export_root']\n else:\n export_root = os.path.abspath('EXPORT')\n build_info['export_root'] = export_root\n del build_info\n deps_root = os.path.join(export_root, 'deps')\n env = os.environ.copy()\n env['PATH'] = '%s:%s' % (\n os.path.join(deps_root, 'bin'), env['PATH'])\n env['LD_LIBRARY_PATH'] = '%s:%s' % (\n os.path.join(deps_root, 'lib'), env.get('LD_LIBRARY_PATH') or '')\n env['DYLD_LIBRARY_PATH'] = '%s:%s' % (\n os.path.join(deps_root, 'lib'), env.get('DYLD_LIBRARY_PATH') or '')\n env['PYTHONPATH'] = '%s:%s' % (\n os.path.join(deps_root, 'python'), env.get('PYTHONPATH', ''))\n cmd = '%s -c \"from beim.scripts.build import build; build(%r)\"' % (\n sys.executable, export_root)\n args = shlex.split(cmd)\n import subprocess\n p = subprocess.Popen(args, env=env)\n while 1:\n p.communicate()\n rt = p.poll()\n if rt is not None:\n break\n else:\n continue\n\n if rt:\n raise RuntimeError('Command %s failed or aborted' % cmd)\n return\n\n\n__id__ = '$Id$'","sub_path":"pycfiles/beim-0.01.tar/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"462772547","text":"import requests\nfrom lxml import etree\n\n\n# 爬取免费代理IP 来源xicidaili.com\nclass ProxyFetch:\n\tdef __init__(self):\n\t\tself.headers = {\n\t\t\t\"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36\",\n\t\t\t# \"Referer\": \"http://www.xicidaili.com/\",\n\t\t}\n\n\tdef start_urls(self):\n\t\t#为了测试只爬取前三页\n\t\treturn [\"http://www.xicidaili.com/nn/%d\" % i for i in range(1,3)]\n\n\tdef parse_url(self, url):\n\t\treturn requests.get(url, headers=self.headers).content.decode()\n\n\tdef get_content_list(self, html_str):\n\t\tcontent_list = []\n\t\thtml = etree.HTML(html_str)\n\t\ttr_list = html.xpath('//table[@id=\"ip_list\"]/tr')[1:]\n\t\tprint(tr_list)\n\t\tfor tr in tr_list:\n\t\t\titem = {}\n\t\t\titem[\"ip\"] = tr.xpath('./td[2]/text()')[0]\n\t\t\titem[\"port\"] = tr.xpath('./td[3]/text()')[0]\n\t\t\tcontent_list.append(item)\n\t\treturn content_list\n\n\tdef save_content_list(self, content_list):\n\t\twith open(\"proxy.json\", \"a\", encoding=\"utf-8\") as f:\n\t\t\tfor ip in content_list:\n\t\t\t\tf.write(\"http://%s:%s\" % (ip[\"ip\"], ip[\"port\"]))\n\t\t\t\tf.write(\"\\n\")\n\n\tdef run(self):\n\t\tstart_urls = self.start_urls()\n\t\tfor url in start_urls:\n\t\t\thtml_str = self.parse_url(url)\n\t\t\t# print(html_str)\n\t\t\tcontent_list = self.get_content_list(html_str)\n\t\t\tself.save_content_list(content_list)\n\nif __name__ == '__main__':\n\tspider = ProxyFetch()\n\tspider.run()\n","sub_path":"proxy_fetch_xicidaili.py","file_name":"proxy_fetch_xicidaili.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"323415469","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals # standard\nimport json, sys, os, time, threading, asyncio # standard\nimport requests # da scaricare\nfrom telethon import TelegramClient, events, sync # da scaricare\nfrom serietvapi_bot.__init__ import __version__\n\nclass Client(TelegramClient):\n\tdef __init__(self, tg_api_id, tg_api_hash, bot):\n\t\tsuper().__init__('SerieTvItaly_bot_session', tg_api_id, tg_api_hash)\n\t\tself.tg_id = tg_api_id\n\t\tself.tg_hash = tg_api_hash\n\t\tself.bot_api = bot\n\n\tdef invia_file(self, nome_file, destinatario = \"@SerieTvItaly_bot\", caption = \"\"):\n\t\tself.send_file(destinatario, nome_file, caption=caption, force_document=True)\n\nclass Bot_API(Client):\n\tdef __init__(self, id, pw):\n\t\tself.id = id\n\t\tself.pw = pw\n\n\tdef execute_command(self, version, name_function, type_action, params={}, headers={}):\n\t\tdef_paras = {'a_id':self.id, 'a_pw':self.pw}\n\t\tif (len(params) != 0):\n\t\t\tfor key in params:\n\t\t\t\tdef_paras[key] = params[key]\n\t\tresponse = requests.get(\"https://serietvitalia.ml/api/\" + type_action + \"/\" + str(version) + \"/\" + name_function, params=def_paras, headers=headers)\n\t\tjson_response = response.json()\n\t\treturn json_response\n\t\t\n\nfiles = []\n\ndef main():\n\ttry:\n\t\t# update to latest version\n\t\trj = requests.get(\"https://serietvitalia.ml/api/r/1/api_versions?av=\" + __version__ + \"&tv=API&s=stable\").json()\n\t\tif (rj['ok'] == True):\n\t\t\tos.system('sudo pip install -U serietvapi_bot')\n\n\t\t# controlliamo se il file per le credenziali esiste\n\t\tif not os.path.exists(\"SerieTvItaly_bot.json\"):\n\t\t\tjson.dump({'api_id': 603638, 'api_hash': 'e0c8fdcd4516ef60e80c6bf89708d628', 'bot_a_id': None, 'bot_a_pw': None}, open(\"SerieTvItaly_bot.json\", 'w'))\n\n\t\twith open(\"SerieTvItaly_bot.json\") as f:\n\t\t\tconfig_file = json.load(f)\n\t\t\n\t\tbot_api_id = config_file['bot_a_id']\n\t\tbot_api_pw = config_file['bot_a_pw']\n\n\t\tif (bot_api_id == None or bot_api_pw == None):\n\t\t\tprint(\"Le credenziali non sono valide, aggiornale ora\")\n\t\t\tbot_api_id = input(\"@SerieTvItaly_bot > Immetti la tua api_id: \")\n\t\t\tbot_api_pw = input(\"@SerieTvItaly_bot > Immetti la tua api_pw: \")\n\n\t\twhile bot_api_id == \"\":\n\t\t\tprint(\"Devi inserire un ID valido\")\n\t\t\tbot_api_id = input(\"@SerieTvItaly_bot > Immetti la tua api_id: \")\n\n\t\twhile bot_api_pw == \"\":\n\t\t\tprint(\"Devi inserire una PW valida\")\n\t\t\tbot_api_pw = input(\"@SerieTvItaly_bot > Immetti la tua api_pw: \")\n\n\t\trj_status = requests.get(\"https://serietvitalia.ml/api/r/1/account_status?a_id=\" + str(bot_api_id) + \"&a_pw=\" + str(bot_api_pw)).json()\n\n\t\tif (rj_status['ok'] == True):\n\t\t\tprint(\"L'account è valido, inserirò le credenziali API del Bot SerieTvItaly_bot per le prossime volte.\\nDovrai nuovamente inserirle quando l'account scadrà.\")\n\t\telse:\n\t\t\tprint(\"L'account non è valido devi inserire nuovamente le credenziali API del Bot SerieTvItaly_bot\")\n\t\t\tbot_api_pw = \"\"\n\t\t\tbot_api_id = \"\"\n\t\t\tjson.dump({'api_id': config_file['api_id'], 'api_hash': config_file['api_hash'], 'bot_a_id': None, 'bot_a_pw': None}, open(\"SerieTvItaly_bot.json\", 'w'))\n\t\t\twhile bot_api_id == \"\":\n\t\t\t\tprint(\"Devi inserire un ID valido\")\n\t\t\t\tbot_api_id = input(\"@SerieTvItaly_bot > Immetti la tua api_id: \")\n\n\t\t\twhile bot_api_pw == \"\":\n\t\t\t\tprint(\"Devi inserire una PW valida\")\n\t\t\t\tbot_api_pw = input(\"@SerieTvItaly_bot > Immetti la tua api_pw: \")\n\n\t\t\trj_status = requests.get(\"https://serietvitalia.ml/api/r/1/account_status?a_id=\" + str(bot_api_id) + \"&a_pw=\" + str(bot_api_pw)).json()\n\t\tjson.dump({'api_id': 603638, 'api_hash': 'e0c8fdcd4516ef60e80c6bf89708d628', 'bot_a_id': bot_api_id, 'bot_a_pw': bot_api_pw}, open(\"SerieTvItaly_bot.json\", 'w'))\n\t\t\n\t\twith open(\"SerieTvItaly_bot.json\") as f:\n\t\t\tconfig_file = json.load(f)\n\t\t\n\t\tbot = Bot_API(config_file['bot_a_id'], config_file['bot_a_pw'])\n\t\tclient = Client(config_file['api_id'], config_file['api_hash'], bot)\n\t\tprint(\"Ora è tutto pronto per funzionare in modo corretto\")\n\t\twith client:\n\t\t\tif \"download_episode\" in rj_status[\"purpose\"]:\n\t\t\t\tclient.send_message(\"@SerieTvItaly_bot\", \"api \" + bot.id + \" benvenuto {}\".format(__version__))\n\t\t\t\tfrom serietvapi_bot import download_episode\n\t\t\t\tep_t = []\n\t\t\t\twhile True:\n\t\t\t\t\tEpisode_Downloader = download_episode.Downloader(bot)\n\t\t\t\t\tEpisode_Downloader.start()\n\t\t\t\t\tep_t.append(Episode_Downloader)\n\t\t\t\t\tfor t in ep_t:\n\t\t\t\t\t\tt.join()\n\n\t\t\t\t\tfor file in Episode_Downloader.files:\n\t\t\t\t\t\tprint(\"Carico il file chiamato \" + file)\n\t\t\t\t\t\trj = bot.execute_command(1, \"tg_message\", \"r\", {'msg':'📤 Caricamento file in corso \\n\\nIl file chiamato ' + file + ' è in fase di invio al Bot.'}, Episode_Downloader.download_ua)\n\t\t\t\t\t\tclient.invia_file(file, caption=os.path.splitext(file)[0])\n\t\t\t\t\t\tos.remove(file)\n\n\t\t\t\t\tif Episode_Downloader.flag_error == True:\n\t\t\t\t\t\tprint(\"Rilevato un errore durante la fase di download di un epiodio, vedere descrizione fornita dal bot\")\n\t\t\t\t\t\tbreak\n\n\t\t\telse:\n\t\t\t\tprint(\"Non ho riconosciuto questa funzione come valida, assicurati di avere l'ultima versione di questo script.\")\n\n\n\texcept Exception as e:\n\t\tprint(\"Errore: \" + str(e))\n\t\texit()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"serietvapi_bot/API_main.py","file_name":"API_main.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"539854985","text":"from django.conf import settings\nfrom django.db import models\n\nfrom product_details import product_details\n\n\nENGLISH_LANGUAGE_CHOICES = sorted(\n [(key.lower(), u'{0} ({1})'.format(key, value['English']))\n for key, value in product_details.languages.items()]\n)\n\nENGLISH_COUNTRY_CHOICES = sorted(\n [(code, u'{0} ({1})'.format(code, name)) for code, name in\n product_details.get_regions('en-US').items()\n if code not in settings.INELIGIBLE_COUNTRIES]\n)\n\n\nclass LocaleField(models.CharField):\n description = ('CharField with locale settings specific to Flicks '\n 'defaults.')\n\n def __init__(self, *args, **kwargs):\n options = {\n 'max_length': 32,\n 'default': settings.LANGUAGE_CODE,\n 'choices': ENGLISH_LANGUAGE_CHOICES\n }\n options.update(kwargs)\n return super(LocaleField, self).__init__(*args, **options)\n\n\nclass CountryField(models.CharField):\n description = ('CharField with country settings specific to Flicks '\n 'defaults.')\n\n def __init__(self, *args, **kwargs):\n options = {\n 'max_length': 16,\n 'default': u'us',\n 'choices': ENGLISH_COUNTRY_CHOICES\n }\n options.update(kwargs)\n return super(CountryField, self).__init__(*args, **options)\n\n\n# South introspection rules for custom fields\nfrom south.modelsinspector import add_introspection_rules\nadd_introspection_rules([], ['^flicks\\.base\\.models\\.LocaleField'])\nadd_introspection_rules([], ['^flicks\\.base\\.models\\.CountryField'])\n","sub_path":"flicks/base/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"626613757","text":"import time\n\ndef nanostr(timenow):\n l = list( \"{0:.9f}\".format( timenow ) ) # convert to list\n p = l.index(\".\") # find position of the letter \"a\"\n del(l[p]) # delete it\n return ( \"\".join(l) ) # convert\n\n\nfrom parse import main as Enphase\n\nimport sys\n\nimport subprocess\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\npprint = pp.pprint\n\ndef main(arg):\n results = Enphase(False)\n timestr = nanostr( time.time() )\n\n #currently = float(results['Currently'].split()[0])\n\n if ( results['Currently'].split()[1] == \"kW\" ) :\n currently = str(float(results['Currently'].split()[0])*1000)\n else:\n currently = results['Currently'].split()[0]\n\n\n microinverters = results['Number of Microinverters Online']\n\n pprint( currently )\n pprint( microinverters )\n\n compose = ['curl', '-i', '-XPOST', 'http://localhost:8086/write?db=Enphase', '--data-binary', 'Generating value='+currently+\" \"+ timestr ]\n pprint(compose)\n subprocess.call(compose)\n\n compose = ['curl', '-i', '-XPOST', 'http://localhost:8086/write?db=Enphase', '--data-binary', 'Microinverters value='+microinverters+\" \"+ timestr ]\n pprint(compose)\n subprocess.call(compose)\n\n\n\nif __name__ == \"__main__\":\n try:\n while ( 1 ):\n main(sys.argv)\n time.sleep(5)\n except KeyboardInterrupt:\n print('Received Ctrl-c')\n","sub_path":"parse2influx.py","file_name":"parse2influx.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"31914042","text":"import numpy as np\n\nfrom Simulation import SimulaTX, SimulaX\nfrom IC import u0\nfrom EigenF import EigeF, u02\nfrom JNM import Js\nfrom cheby import Cheby\nfrom Convergence import conv_IC\n\n\ndef run_fishers():\n \"\"\"\n Solves the Fishers-KPP Stochastic equation on 1D using Spectral method\n based on the spectral decomposition of the Ornstein-Uhlenbeck semigroup\n associated to the Kolmogorov equation and compute the norm between two solutions\n with different initial conditions for a fixed point in real space.\n\n Returns\n -------\n xSpace : array; discretized real space\n tim : array; discretized time\n simulation1 : array, shape(len(tim), len(xSpace))\n Array containing the solutions of partial equation\n simulation2 : array, shape(len(tim), len(xSpace))\n Array containing the solutions of partial equation with the IC approximated\n norms : array; norms between two solutions\n times : array; discretized time\n \"\"\"\n # Diffusion coefficient\n nu = 0.1\n\n # Parameteres of the method\n N = 7\n Q = 200\n\n # Discretization\n xSpace = np.linspace(0, 1, 512)\n tim = np.linspace(0, 10, 256)\n\n # Creating set J^{N;M}\n J = Js(N)\n M = len(J[:, 1])\n\n # Hermite polynomials evaluation\n rule1 = np.polynomial.hermite_e.hermegauss(Q)\n rulesX = rule1[0][::-1]\n rulesW = rule1[1]\n LRules = len(rulesX)\n\n # Simulation Space-Time\n EigValRe, EigValIm, EigVecRe, EigVecIm, U_1 = EigeF(J, N, M, rulesX, rulesW, LRules, xSpace, nu, u0)\n H1 = SimulaX(J, M, xSpace, nu, u0)\n\n # Aproximation to u0\n aprox = Cheby.fit(u0, 0, 1, 7)\n H2 = SimulaX(J, M, xSpace, nu, aprox)\n U_2 = u02(J, M, rulesX, rulesW, LRules, xSpace, nu, aprox)\n\n simulation1 = SimulaTX(xSpace, tim, M, EigValRe, EigValIm, EigVecRe, EigVecIm, U_1, H1)\n simulation2 = SimulaTX(xSpace, tim, M, EigValRe, EigValIm, EigVecRe, EigVecIm, U_2, H2)\n\n # compute convergence\n norms, times = conv_IC(xSpace, tim, M, J, EigValRe, EigValIm, EigVecRe, EigVecIm, U_1, U_2)\n \n return xSpace, tim, simulation1, simulation2, norms, times\n\n\nxSpace, tim, simulation1, simulation2, norms, times = run_fishers()\n\n\n","sub_path":"Thesis/Codes/Fisher_Stochastic/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"42336","text":"# Copyright 2016 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport pytest\n\nfrom fuel_ccp_tests.helpers import post_install_k8s_checks as funcs\n\ntest_images1 = [\n \"artifactory.example.net:5000/hyperkube-amd64:v1.4.1-test_100\",\n \"andyshinn/dnsmasq:2.72\",\n \"artifactory.example.net:5001/calico/node:v0.20.0-mcp-7b31adc\",\n \"artifactory.example.net:5001/calico/ctl:v0.20.0-mcp-7b31adc\",\n \"artifactory.example.net:5000/hyperkube-amd64:v1.4.1-test_100\",\n]\n\ntest_images2 = [\n \"andyshinn/dnsmasq:2.72\",\n \"gcr.io/google_containers/pause-amd64:3.0\",\n \"quay.io/coreos/etcd:v3.0.1\",\n]\n\nrequired_images = [\n \"andyshinn/dnsmasq\",\n \"calico/node\",\n \"hyperkube-amd64\",\n]\n\n\nclass MockUnderlay(object):\n def __init__(self, images):\n self.images = images\n\n def sudo_check_call(self, *args, **kwargs):\n return {'stdout': self.images}\n\n\n@pytest.mark.unit_tests\ndef test_required_images_exists():\n funcs.required_images_exists(node_name='master',\n underlay=MockUnderlay(test_images1),\n required_images=required_images)\n with pytest.raises(AssertionError):\n funcs.required_images_exists(node_name='master',\n underlay=MockUnderlay(test_images2),\n required_images=required_images)\n","sub_path":"fuel_ccp_tests/tests/unit/test_system_funcs.py","file_name":"test_system_funcs.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"541212635","text":"import slugify\nfrom django.db import models\n\n\nclass ItemSize(models.Model):\n SIZES = (\n ('Size S', 'Size S'),\n ('Size M', 'Size M'),\n ('Size L', 'Size L'),\n ('Size XL', 'Size XL'),\n ('Size 2XL', 'Size 2XL')\n )\n name = models.CharField(max_length=100, choices=SIZES, unique=True)\n\n class Meta:\n verbose_name = 'Product size'\n verbose_name_plural = 'Product sizes'\n\n def __str__(self):\n return self.name\n\n\nclass Item(models.Model):\n name = models.CharField(max_length=255)\n description = models.TextField(null=True, blank=True)\n price = models.SmallIntegerField()\n sizes = models.ManyToManyField(ItemSize)\n available = models.BooleanField(default=True)\n show = models.BooleanField(default=True)\n quantity = models.SmallIntegerField()\n timestamp = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n verbose_name = 'Product'\n verbose_name_plural = 'Products'\n ordering = ('timestamp',)\n\n def __str__(self):\n return self.name\n\n\nclass ItemImage(models.Model):\n alt = models.CharField(max_length=255, null=True, blank=True)\n cover = models.BooleanField(default=False)\n image = models.ImageField(upload_to='images/')\n item = models.ForeignKey(Item, related_name='images')\n\n class Meta:\n verbose_name = 'Product image'\n verbose_name_plural = 'Product images'\n\n def __str__(self):\n return 'Image {0} in item {1}'.format(self.pk, self.item.name)\n\n def save(self, *args, **kwargs):\n if self.cover:\n ItemImage.objects.filter(item=self.item).update(**{'cover': False})\n ret = super(ItemImage, self).save(*args, **kwargs)\n return ret\n\n def delete(self, *args, **kwargs):\n self.image.delete()\n super(ItemImage, self).delete(*args, **kwargs)\n\n\nclass Album(models.Model):\n name = models.CharField(max_length=255, unique=True)\n slug = models.CharField(max_length=255, unique=True)\n timestamp = models.DateTimeField('Date')\n show = models.BooleanField(default=True)\n\n class Meta:\n ordering = ('timestamp',)\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify.slugify(self.name)\n ret = super(Album, self).save(*args, **kwargs)\n return ret\n\n\nclass Post(models.Model):\n content = models.TextField(null=True, blank=True)\n show = models.BooleanField(default=True)\n album = models.ForeignKey(Album, related_name='posts')\n\n\nclass MainFile(models.Model):\n file = models.FileField(upload_to='main/')\n timestamp = models.DateTimeField(auto_now_add=True)\n show = models.BooleanField(default=True)\n\n class Meta:\n ordering = ('-timestamp',)\n\n\nclass Order(models.Model):\n name = models.CharField(max_length=255)\n email = models.EmailField()\n created = models.DateTimeField(auto_now_add=True)\n total_value = models.IntegerField(null=True, blank=True)\n paid = models.BooleanField(default=False)\n\n\nclass CartItem(models.Model):\n item = models.ForeignKey(Item)\n quantity = models.IntegerField()\n size = models.ForeignKey(ItemSize)\n value = models.IntegerField(null=True, blank=True)\n order = models.ForeignKey(Order, related_name='order_items')\n\n def save(self, *args, **kwargs):\n if self.quantity:\n self.value = self.quantity * self.item.price\n ret = super(CartItem, self).save(*args, **kwargs)\n return ret\n","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"176724975","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n'''\nRoles in this namespace are meant to provide Django app server utility methods for Debian distributions.\n'''\n\nfrom os.path import dirname, join, splitext, split\n\nfrom provy.core import Role\nfrom provy.more.debian.package.pip import PipRole\nfrom provy.more.debian.package.aptitude import AptitudeRole\nfrom provy.more.debian.monitoring.supervisor import SupervisorRole\n\nSITES_KEY = 'django-sites'\nMUST_RESTART_KEY = 'restart-django-sites'\n\n\nclass WithSite(object):\n def __init__(self, django, name):\n self.django = django\n self.auto_start = True\n self.daemon = True\n self.name = name\n self.settings_path = None\n self.host = '0.0.0.0'\n self.pid_file_path = '/var/run'\n self.threads = 1\n self.processes = 1\n self.starting_port = 8000\n self.user = None\n if SupervisorRole in self.django.context['roles_in_context']:\n self.use_supervisor = True\n self.supervisor_log_folder = self.django.context['roles_in_context'][SupervisorRole].log_folder\n else:\n self.use_supervisor = False\n self.supervisor_log_folder = '/var/log'\n\n self.settings = {}\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_value, traceback):\n if not self.settings_path:\n raise RuntimeError('[Django] The path to the site must be specified and should correspond to the directory where the settings.py file is for site %s.' % self.name)\n\n if SITES_KEY not in self.django.context:\n self.django.context[SITES_KEY] = []\n\n if self.use_supervisor:\n self.daemon = False\n self.auto_start = False\n self.django.restart_supervisor_on_changes = True\n\n self.django.context[SITES_KEY].append(self)\n\n\nclass DjangoRole(Role):\n '''\n This role provides Django app server management utilities for Debian distributions.\n When running Django under supervisor, remember to set restart_supervisor_on_changes to True.\n If you choose to automatically include supervisor support in your sites, don't forget to call SupervisorRole config method.\n When creating a new site using with role.create_site('somesite') as site these are the properties available in the site object:\n auto_start - Indicates whether the site should be automatically started by the operating system. Defaults to True. If using supervisor, explicitly set this to False.\n daemon - Indicates whether the init.d command for the website should daemonize itself. Defaults to True. If using supervisor, explicitly set this to False.\n settings_path - This is the only mandatory argument. This is the full path to django's settings.py file.\n host - The host IP address that django will listen to incoming requests. Defaults to '0.0.0.0'.\n starting_port - The first port that Django will be started in the event that more than one process is used. Defaults to 8000.\n processes - The number of processes that will have commands created at the server. As an example, if this is set to 2 and the name of the site is 'website', two commands will be created: /etc/init.d/website-8000 and /etc/init.d/website-8001. Defaults to 1.\n pid_file_path - Path to create the pid file. Defaults to '/var/run'.\n threads - Number of worker threads that Green Unicorn will use when spawning Django. Defaults to 1.\n user - User that gunicorn will run under. Defaults to the last created user. When using supervisor it is VERY important that this user is the same user as supervisor's.\n use_supervisor - States that supervisor configuration for these django website should be automatically included.\n supervisor_log_folder - Log folder that supervisor will store the configurations for this site.\n settings - Dictionary with settings that will overwrite Django's defaults. These settings will be included in a local_settings.py module that imports the original settings as KEY=value pairs. All values included here will have their string representation used in the local_settings.\n\n Sample usage \n \n from provy.core import Role\n from provy.more.debian import DjangoRole\n\n class MySampleRole(Role):\n def provision(self):\n with self.using(SupervisorRole) as role:\n role.config(\n config_file_directory='/home/someuser',\n log_file='/home/someuser/logs/supervisord.log',\n user='myuser'\n )\n\n with self.using(DjangoRole) as role:\n role.restart_supervisor_on_changes = True\n with role.create_site('mysite') as site:\n site.path = '/some/folder/with/settings.py'\n site.use_supervisor = True\n site.supervisor_log_path = '/some/folder/to/log'\n site.threads = 4\n site.processes = 2\n site.user = 'myuser'\n # settings that override the website defaults.\n site.settings = {\n\n }\n \n '''\n def __init__(self, prov, context):\n super(DjangoRole, self).__init__(prov, context)\n self.restart_supervisor_on_changes = False\n\n def provision(self):\n '''\n Installs Django and its dependencies. This method should be called upon if overriden in base classes, or Django won't work properly in the remote server.\n If you set a variable called django-version in the context, that version of django will be installed instead of latest.\n Sample usage \n \n from provy.core import Role\n from provy.more.debian import DjangoRole\n\n class MySampleRole(Role):\n def provision(self):\n self.provision_role(DjangoRole) # no need to call this if using with block.\n\n # or\n class MySampleRole(Role):\n def provision(self):\n self.context['django-version'] = '1.1.1'\n self.provision_role(DjangoRole) # no need to call this if using with block.\n # now django 1.1.1 is installed.\n \n '''\n self.register_template_loader('provy.more.debian.web')\n\n with self.using(AptitudeRole) as role:\n role.ensure_package_installed('python-mysqldb')\n\n with self.using(PipRole) as role:\n if 'django-version' in self.context:\n role.ensure_package_installed('django', version=self.context['django-version'])\n else:\n role.ensure_package_installed('django')\n\n role.ensure_package_installed('gunicorn')\n\n def create_site(self, name):\n '''\n Enters a with block with a Site variable that allows you to configure a django website.\n Parameters \n name - name of the website.\n Sample usage \n \n from provy.core import Role\n from provy.more.debian import DjangoRole\n\n class MySampleRole(Role):\n def provision(self):\n with self.using(DjangoRole) as role:\n with role.create_site('website') as program:\n site.path = '/some/folder/with/settings.py'\n site.threads = 4\n # settings that override the website defaults.\n site.settings = {\n\n }\n \n '''\n return WithSite(self, name)\n\n def cleanup(self):\n '''\n Updates the website and/or init files and restarts websites if needed.\n There's no need to call this method since provy's lifecycle will make sure it is called.\n '''\n\n if SITES_KEY in self.context:\n for website in self.context[SITES_KEY]:\n updated = self.__update_init_script(website)\n settings_updated = self.__update_settings(website)\n if website.use_supervisor:\n self.__update_supervisor_program(website)\n if updated or settings_updated:\n self.__ensure_restart(website)\n\n if MUST_RESTART_KEY in self.context and self.context[MUST_RESTART_KEY]:\n if self.restart_supervisor_on_changes:\n with self.using(SupervisorRole) as role:\n role.ensure_restart()\n for site in self.context[MUST_RESTART_KEY]:\n self.__restart(site)\n\n def __update_supervisor_program(self, website):\n with self.using(SupervisorRole) as role:\n for process_number in range(website.processes):\n port = website.starting_port + process_number\n script_name = \"%s-%d\" % (website.name, port)\n with role.with_program(script_name) as program:\n program.directory = dirname(website.settings_path)\n program.command = '/etc/init.d/%s start' % script_name\n program.name = script_name\n program.number_of_processes = 1\n program.user = website.user\n program.log_folder = website.supervisor_log_folder\n\n def __ensure_restart(self, website):\n if not MUST_RESTART_KEY in self.context:\n self.context[MUST_RESTART_KEY] = []\n self.context[MUST_RESTART_KEY].append(website)\n\n def __restart(self, website):\n if not website.auto_start:\n return\n for process_number in range(website.processes):\n port = website.starting_port + process_number\n script_name = \"%s-%d\" % (website.name, port)\n if self.remote_exists(join(website.pid_file_path.rstrip('/'), '%s_%s.pid' % (website.name, port))):\n self.execute('/etc/init.d/%s stop' % script_name, stdout=False, sudo=True)\n self.execute('/etc/init.d/%s start' % script_name, stdout=False, sudo=True)\n\n def __update_settings(self, website):\n local_settings_path = join(dirname(website.settings_path), 'local_settings.py')\n options = {\n 'settings_file': splitext(split(website.settings_path)[-1])[0],\n 'settings': website.settings\n }\n result = self.update_file('local.settings.template', local_settings_path, owner=website.user, options=options, sudo=True)\n return result\n\n def __update_init_script(self, website):\n at_least_one_updated = False\n for process_number in range(website.processes):\n port = website.starting_port + process_number\n options = {\n 'name': website.name,\n 'pid_file_path': website.pid_file_path.rstrip('/'),\n 'user': website.user,\n 'host': website.host,\n 'port': port,\n 'threads': website.threads,\n 'daemon': website.daemon,\n 'user': website.user,\n 'settings_directory': dirname(website.settings_path)\n }\n script_name = '%s-%d' % (website.name, port)\n result = self.update_file('website.init.template', '/etc/init.d/%s' % script_name, owner=website.user, options=options, sudo=True)\n\n if result:\n at_least_one_updated = True\n self.execute('chmod +x /etc/init.d/%s' % script_name, stdout=False, sudo=True)\n if website.auto_start:\n self.execute('update-rc.d %s defaults' % script_name, stdout=False, sudo=True)\n\n return at_least_one_updated\n","sub_path":"provy/more/debian/web/django.py","file_name":"django.py","file_ext":"py","file_size_in_byte":11777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"9499812","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n__project_parent__ = 'AGGREGATION'\n__project_title__ = 'Automated Gloss Mapping for Inferring Grammatical Properties'\n__project_name__ = 'Map Gloss'\n__script__ = 'eval/confusion_matrix.py'\n__date__ = 'March 2015'\n\n__author__ = 'MichaelLockwood'\n__email__ = 'lockwm@uw.edu'\n__github__ = 'mlockwood'\n__credits__ = 'Emily M. Bender for her guidance'\n__collaborators__ = None\n\n\nclass CM:\n\n objects = {}\n\n def __init__(self, gold, test, name):\n self.gold = gold\n self.test = test\n self.name = name\n self.matrix = {'FNeg': {}, 'FPos': {}, 'TPos': {}}\n self.set_confusion()\n self.precision = self.set_precision()\n self.recall = self.set_recall()\n self.fscore = self.set_fscore()\n CM.objects[name] = self\n\n def __repr__(self):\n return ''.format(self.name)\n\n def set_confusion(self):\n for label in self.gold:\n if label in self.test:\n self.matrix['TPos'][label] = True\n else:\n self.matrix['FNeg'][label] = True\n for label in self.test:\n if label not in self.gold:\n self.matrix['FPos'][label] = True\n\n def set_precision(self):\n try:\n precision = float(len(self.matrix['TPos'])) / (len(self.matrix['TPos']) + len(self.matrix['FPos']))\n except:\n precision = 0.0\n return precision\n\n def set_recall(self):\n try:\n recall = float(len(self.matrix['TPos'])) / (len(self.matrix['TPos']) + len(self.matrix['FNeg']))\n except:\n recall = 0.0\n return recall\n\n def set_fscore(self):\n try:\n fscore = 2 * (self.precision * self.recall / (self.precision + self.recall))\n except:\n fscore = 0.0\n return fscore\n\n def get_final(self):\n return self.precision, self.recall, self.fscore\n\n def write_prf_file(self, file):\n writer = open(file + '.prf', 'w')\n self.set_prf_file(writer)\n writer.close()\n\n def set_prf_file(self, writer):\n # Main p/r/f statistics\n writer.write('Precision: {}\\n'.format(self.precision))\n writer.write('Recall: {}\\n'.format(self.recall))\n writer.write('F-Score: {}\\n\\n'.format(self.fscore))\n \n # False negatives\n if self.matrix['FNeg']:\n writer.write('False Negatives\\n')\n for value in self.matrix['FNeg']:\n writer.write('\\t{}\\n'.format(value))\n writer.write('\\n')\n \n # False positives\n if self.matrix['FPos']:\n writer.write('False Positives\\n')\n for value in self.matrix['FPos']:\n writer.write('\\t{}\\n'.format(value))\n writer.write('\\n')\n\n def write_hprf_file(self, file):\n writer = open(file + '.hprf', 'w')\n self.set_hprf_file(writer)\n writer.close()\n\n def set_hprf_file(self, writer):\n # Gold labels\n writer.write('Gold Labels\\n')\n for value in self.gold:\n writer.write('G\\t{}\\n'.format(value))\n \n # Test labels\n writer.write('\\nTest Labels\\n')\n for value in self.test:\n writer.write('T\\t{}\\n'.format(value))\n\n\nclass Compare:\n\n objects = {} # (cm1, cm2)\n order = ['TP2FN', 'NO2FP', 'FN2TP', 'FP2NO']\n headers = {'TP2FN': 'True Positives to False Negatives',\n 'NO2FP': 'False Positives Added',\n 'FN2TP': 'False Negatives to True Positives',\n 'FP2NO': 'False Positives Removed'}\n\n def __init__(self, cm1, cm2):\n self.cm1 = cm1\n self.cm2 = cm2\n self.matrix = {'TP2FN': {}, 'NO2FP': {}, 'FN2TP': {}, 'FP2NO': {}}\n self.set_comparison_matrix()\n self.abs_precision = self.set_abs_precision()\n self.rel_precision = self.set_rel_precision()\n self.abs_recall = self.set_abs_recall()\n self.rel_recall = self.set_rel_recall()\n self.abs_fscore = self.set_abs_fscore()\n self.rel_fscore = self.set_rel_fscore()\n Compare.objects[(cm1.name, cm2.name)] = self\n\n def __repr__(self):\n return ''.format(self.cm1.name, self.cm2.name)\n\n def set_comparison_matrix(self):\n self.set_matrix_values(self.cm2.matrix['TPos'], self.cm1.matrix['TPos'], 'TP2FN')\n self.set_matrix_values(self.cm1.matrix['FPos'], self.cm2.matrix['FPos'], 'NO2FP')\n self.set_matrix_values(self.cm2.matrix['FNeg'], self.cm1.matrix['FNeg'], 'FN2TP')\n self.set_matrix_values(self.cm2.matrix['FPos'], self.cm1.matrix['FPos'], 'FP2NO')\n\n def set_matrix_values(self, first_matrix, second_matrix, new_type):\n for value in first_matrix:\n if value not in second_matrix:\n self.matrix[new_type][value] = True\n \n def set_abs_precision(self):\n return self.cm1.precision - self.cm2.precision\n\n def set_rel_precision(self):\n try:\n rel_precision = self.cm1.precision / self.cm2.precision\n except:\n rel_precision = 0.0\n return rel_precision\n \n def set_abs_recall(self):\n return self.cm1.recall - self.cm2.recall\n\n def set_rel_recall(self):\n try:\n rel_recall = self.cm1.recall / self.cm2.recall\n except:\n rel_recall = 0.0\n return rel_recall\n \n def set_abs_fscore(self):\n return self.cm1.fscore - self.cm2.fscore\n\n def set_rel_fscore(self):\n try:\n rel_fscore = self.cm1.fscore / self.cm2.fscore\n except:\n rel_fscore = 0.0\n return rel_fscore\n\n def write_cprf_file(self, file):\n writer = open(file + '.cprf', 'w')\n self.set_cprf_file(writer)\n \n # Write PRF file of the first confusion matrix\n writer.write('\\n\\n--- {} ---\\n\\n'.format(self.cm1.name))\n self.cm1.set_prf_file(writer)\n \n # Write PRF file of the second confusion matrix\n writer.write('\\n\\n--- {} ---\\n\\n'.format(self.cm2.name))\n self.cm2.set_prf_file(writer)\n \n writer.close()\n\n def set_cprf_file(self, writer):\n # Main p/r/f abs statistics\n writer.write('Absolute Change\\n')\n writer.write('Precision: {}\\n'.format(self.abs_precision))\n writer.write('Recall: {}\\n'.format(self.abs_recall))\n writer.write('F-Score: {}\\n\\n'.format(self.abs_fscore))\n \n # Main p/r/f rel statistics\n writer.write('Relative Change\\n')\n writer.write('Precision: {}\\n'.format(self.rel_precision))\n writer.write('Recall: {}\\n'.format(self.rel_recall))\n writer.write('F-Score: {}\\n\\n'.format(self.rel_fscore))\n \n # False negatives and false positives\n for entry in Compare.order:\n if self.matrix[entry]:\n writer.write('{}\\n'.format(Compare.headers[entry]))\n for value in self.matrix[entry]:\n writer.write('\\t{}\\n'.format(value))\n writer.write('\\n')\n","sub_path":"utils/confusion_matrix.py","file_name":"confusion_matrix.py","file_ext":"py","file_size_in_byte":7079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"315220102","text":"import sys\nimport signal\nimport cv2\nfrom time import localtime, strftime\nfrom datetime import datetime, timedelta\nend = False\n\ndef signal_handler(signal, frame):\n\tglobal end\n\tend = True\ncap = cv2.VideoCapture(2)\nif not cap.isOpened():\n\tsys.exit(-1)\nfourcc = cv2.VideoWriter_fourcc(*'DIVX')\ntempo = strftime(\"%a, %d %b %Y %H:%M:%S\", localtime())\nout = cv2.VideoWriter(tempo+'.AVI',fourcc, 20.0, (640,480))\nsignal.signal(signal.SIGINT, signal_handler)\n\n\nwhile(not end):\n\tret, frame = cap.read()\n\tif ret:\n\t\tnow = datetime.now()\n\t\tcv2.putText(frame, str(now),(5, 20),cv2.FONT_HERSHEY_COMPLEX_SMALL,.8,(225,255,255))\n\t\tout.write(frame)\n\t\t#print(str(now))\t\n\telse:\n\t\tprint('Erro na Captura')\n\t\tbreak\ncap.release()\nout.release()\n\n\n","sub_path":"Testes/CamSave.py","file_name":"CamSave.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"426479146","text":"import logging\nimport re\n\nimport app\nimport base_servlet\nimport fb_api\nfrom topics import grouping\nfrom topics import topic_db\nfrom search import search\nfrom search import search_base\n\n@app.route('/topic/?')\nclass TopicListHandler(base_servlet.BaseRequestHandler):\n def requires_login(self):\n return False\n\n def get(self):\n topics = topic_db.Topic.query().fetch(500)\n self.display['topics'] = sorted(topics, key=lambda x: x.url_path)\n\n self.render_template('topic_list')\n\n@app.route('/topic/([^/]+)/?')\nclass TopicHandler(base_servlet.BaseRequestHandler):\n def requires_login(self):\n return False\n\n def get(self, name):\n topics = topic_db.Topic.query(topic_db.Topic.url_path==name).fetch(1)\n if not topics:\n self.response.set_status(404)\n return\n\n topic = topics[0]\n\n if topic.graph_id:\n # We shouldn't need any tokens to access pages\n fbl = fb_api.FBLookup(None, None)\n fb_source = fbl.get(topic_db.LookupTopicPage, topic.graph_id)\n else:\n fb_source = None\n\n\n def prefilter(doc_event):\n \"\"\"Function for fitlering doc results, before we spend the energy to load the corresponding DBEvents.\n\n We only want on-topic events here:\n - Must contain keyword in the title\n - Must contain keyword on a line where it makes up >10% of the text (for judges, workshops, etc). We want to hide the resume-includes-classes-from-X people\n \"\"\"\n logging.info(\"Prefiltering event %s\", doc_event.doc_id)\n name = doc_event.field('name').value.lower()\n description = doc_event.field('description').value.lower()\n\n description_lines = description.split('\\n')\n\n for keyword in topic.search_keywords:\n keyword_word_re = re.compile(r'\\b%s\\b' % keyword)\n if keyword_word_re.search(name):\n return True\n for line in description_lines:\n result = keyword_word_re.search(line)\n # If the keyword is more than 10% of the text in the line:\n # Examples:\n # \"- HOUSE - KAPELA (Serial Stepperz/Wanted Posse)\"\n # \"5th November : EVENT Judged by HIRO :\"\n if result:\n if 1.0 * len(keyword) / len(line) > 0.1:\n return True\n else:\n logging.info(\"Found keyword %r on line, but not long enough: %r\", keyword, line)\n\n logging.info(\"Prefilter dropping event %s with name: %r\" % (doc_event.doc_id, name))\n return False\n\n keywords = ' OR '.join('\"%s\"' % x for x in topic.search_keywords)\n search_query = search_base.SearchQuery(keywords=keywords)\n # Need these fields for the prefilter\n search_query.extra_fields = ['name', 'description']\n search_results = search.Search(search_query).get_search_results(prefilter=prefilter)\n\n self.display['topic_title'] = topic.override_title or (fb_source and fb_source['info']['name'])\n self.display['topic_image'] = topic.override_image or (fb_source and fb_source['picture']['data']['url'])\n self.display['topic_description'] = topic.override_description or (fb_source and fb_source['info'].get('about')) or ''\n\n self.display['all_results'] = search_results\n\n by_year = []\n for year, month_events in sorted(grouping.group_results_by_date(search_results).items()):\n by_year.append((year, sorted(month_events.items())))\n self.display['group_by_date'] = by_year\n by_country = sorted(grouping.group_results_by_location(search_results).items(), key=lambda x: (-len(x[1]), x[0]))\n self.display['group_by_location'] = by_country\n\n\n # TODO:\n # show points on map (future and past?)\n # show future events\n # show past events\n # show high quality and low quality events (most viable with 'past')\n # have an ajax filter on the page that lets me filter by location?\n self.display['fb_page'] = fb_source\n\n self.render_template('topic')\n\n\ndef get_id_from_url(url):\n if '#' in url:\n url = url.split('#')[1]\n if 'facebook.com' in url:\n url = url.split('facebook.com')[1]\n\n path_components = url.split('/')\n if path_components[1] == 'pages':\n page_id = path_components[3]\n return page_id\n else:\n page_name = path_components[1]\n return page_name\n\n#\"https://www.facebook.com/dancedeets\"\n#\"https://www.facebook.com/pages/DanceDeets-Events/1613128148918160\"\n\n@app.route('/topic_add')\nclass AdminAddTopicHandler(base_servlet.BaseRequestHandler):\n\n def show_barebones_page(self):\n self.response.out.write('Bleh')\n\n def get(self):\n page_lookup_id = None\n if self.request.get('page_url'):\n page_lookup_id = get_id_from_url(self.request.get('page_url'))\n elif self.request.get('page_id'):\n page_lookup_id = self.request.get('page_id')\n else:\n self.add_error('Need to specify a page to create from')\n self.fbl.request(topic_db.LookupTopicPage, page_lookup_id, allow_cache=False)\n self.finish_preload()\n\n try:\n fb_page = self.fbl.fetched_data(topic_db.LookupTopicPage, page_lookup_id)\n except fb_api.NoFetchedDataException:\n return self.show_barebones_page()\n\n self.errors_are_fatal()\n\n real_page_id = fb_page['info']['id']\n\n topics = topic_db.Topic.query(topic_db.Topic.graph_id==real_page_id).fetch(1)\n topic = topics[0] if topics else topic_db.Topic()\n\n topic.graph_id = real_page_id\n topic.topic_class = topic_db.TOPIC_DANCER\n topic.search_keywords = self.request.get_all('search_keywords')\n topic.put()\n self.response.out.write('Added!')\n\n","sub_path":"topics/topic_servlets.py","file_name":"topic_servlets.py","file_ext":"py","file_size_in_byte":5983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"224419069","text":"'''\r\nCreated on Jul 31, 2018\r\n\r\n@author: Anthony\r\n'''\r\n\r\nimport pandas as pd\r\nimport os\r\nimport inspect\r\nfrom hockey_3D_Map import hockey_3D_Map\r\nimport re\r\n\r\ncsv_headers = ['TOI', 'CA', 'FA', 'SA', 'GA']\r\ntoi_threashold = 40 / 60\r\n\r\ndef check(player_1_name, player_1_data, player_2_name, player_2_data):\r\n if player_1_data < player_2_data:\r\n return player_1_name + \" less\"\r\n elif player_1_data == player_2_data:\r\n return \"Same\"\r\n else:\r\n return player_2_name + \" less\"\r\n \r\ndef extract_player(file_string, player_name):\r\n file = pd.read_csv(file_string, index_col='Player')\r\n \r\n retVal = None\r\n \r\n try:\r\n retVal = file.loc[player_name]\r\n except KeyError:\r\n print(player_name + ' is not in ' + file_string)\r\n \r\n return retVal \r\n \r\ndef main(project_folder, data_folder, use_threshold, player_1, player_2):\r\n if 'NST' in data_folder:\r\n csv_headers.append('SCA')\r\n csv_headers.append('HDCA')\r\n \r\n init_path = project_folder + '\\\\out\\\\' + player_1 + ' - ' + player_2\r\n games_path = init_path + '\\\\games'\r\n analysis_path = init_path + '\\\\ana'\r\n \r\n if not os.path.exists(games_path):\r\n os.makedirs(games_path)\r\n if not os.path.exists(analysis_path):\r\n os.makedirs(analysis_path)\r\n \r\n x = hockey_3D_Map(player_1, player_2)\r\n csvs = []\r\n player_1_stats = []\r\n player_2_stats = []\r\n \r\n for root, dirs, files in os.walk(project_folder + data_folder):\r\n for file in files:\r\n if file.endswith('.csv'):\r\n print(file)\r\n \r\n file_i = os.path.join(root, file)\r\n player_1_data = extract_player(file_i, player_1)\r\n player_2_data = extract_player(file_i, player_2)\r\n \r\n if(player_1_data is not None) and (player_2_data is not None):\r\n csvs.append(file)\r\n player_1_stats.append(player_1_data)\r\n player_2_stats.append(player_2_data)\r\n \r\n print('\\n')\r\n \r\n for csv_i, p1_row_i, p2_row_i in zip(csvs, player_1_stats, player_2_stats):\r\n file_i_name = games_path + '\\\\' + csv_i.replace('.csv', '.txt')\r\n game_file_i = open(file_i_name, 'w')\r\n game_file_i.write(csv_i + '\\r\\n')\r\n \r\n for j in csv_headers:\r\n p1_stat_j = p1_row_i.loc[j]\r\n p2_stat_j = p2_row_i.loc[j]\r\n \r\n if p1_stat_j == '--':\r\n p1_stat_j = 0\r\n else:\r\n p1_stat_j = float(p1_stat_j)\r\n \r\n if p2_stat_j == '--':\r\n p2_stat_j = 0\r\n else:\r\n p2_stat_j = float(p2_stat_j)\r\n \r\n string1 = check(player_1, p1_stat_j, player_2, p2_stat_j)\r\n \r\n if j == 'TOI':\r\n if ((p1_stat_j < toi_threashold) or (p2_stat_j < toi_threashold)) and use_threshold:\r\n # Go to the next file\r\n print(csv_i + ': Failed')\r\n game_file_i.close()\r\n os.remove(file_i_name)\r\n break\r\n else:\r\n x.public_update(string1, csv_i, j)\r\n \r\n game_file_i.write(j + \" -> \" + string1 + '\\n')\r\n game_file_i.write('\\t' + '(' + player_1 + ': ' + str(p1_stat_j) + ' vs ' + player_2 + ': ' + str(p2_stat_j) + ')\\n')\r\n else:\r\n x.public_update(string1, csv_i, j)\r\n \r\n game_file_i.write(j + \" -> \" + string1 + '\\n')\r\n game_file_i.write('\\t' + '(' + player_1 + ': ' + str(p1_stat_j) + ' vs ' + player_2 + ': ' + str(p2_stat_j) + ')\\n')\r\n \r\n p1_toi = p1_row_i.loc['TOI']\r\n p2_toi = p2_row_i.loc['TOI']\r\n p1_stat_j_n = float(p1_stat_j) / float(p1_toi)\r\n p2_stat_j_n = float(p2_stat_j) / float(p2_toi)\r\n \r\n string2 = check(player_1, p1_stat_j_n, player_2, p2_stat_j_n)\r\n game_file_i.write(j + \" Normalized -> \" + string2 + '\\n')\r\n game_file_i.write('\\t' + '(' + player_1 + ': ' + str(p1_stat_j_n) + ' vs ' + player_2 + ': ' + str(p2_stat_j_n) + ')\\n')\r\n \r\n x.public_update(string2, csv_i, (j+'N'))\r\n \r\n game_file_i.close()\r\n \r\n key_delimiter = os.path.basename(os.path.normpath(data_folder))\r\n \r\n relevant_metrics = ['CAN', 'FAN', 'SAN']\r\n \r\n if 'NST' in data_folder:\r\n analysis_file = open(analysis_path + '\\\\' + 'NST - ' + key_delimiter + '.txt', 'w')\r\n relevant_metrics.append('SCAN')\r\n relevant_metrics.append('HDCAN')\r\n \r\n for s in x.situations:\r\n update_analysis_file(analysis_file, x, s, relevant_metrics, player_1, player_2)\r\n \r\n elif 'Corsica' in data_folder:\r\n analysis_file = open(analysis_path + '\\\\' + 'Corsica - ' + key_delimiter + '.txt', 'w')\r\n update_analysis_file(analysis_file, x, 'Total', relevant_metrics, player_1, player_2)\r\n \r\n analysis_file.close()\r\n\r\ndef update_analysis_file(given_file, h_3D, situation, metrics, p1_name, p2_name):\r\n for m_i in metrics:\r\n p1_m_i = h_3D.d[p1_name][situation][m_i]\r\n given_file.write(p1_name + ' total ' + situation + ' for metric ' + m_i + ' -> ' + str(p1_m_i) + '\\n')\r\n \r\n p2_m_i = h_3D.d[p2_name][situation][m_i]\r\n given_file.write(p2_name + ' total ' + situation + ' for metric ' + m_i + ' -> ' + str(p2_m_i) + '\\n')\r\n \r\n same_m_i = h_3D.d['Same'][situation][m_i]\r\n given_file.write('Same total ' + situation + ' for metric ' + m_i + ' -> ' + str(same_m_i) + '\\n')\r\n given_file.write('\\n')\r\n \r\ndef get_toi(given_file_string):\r\n TOI_LINE_LOCATION = 3\r\n \r\n given_file = open(given_file_string, 'r')\r\n given_file_lines = given_file.readlines()\r\n toi_line = given_file_lines[TOI_LINE_LOCATION]\r\n broken_toi_line = toi_line.split(' ')\r\n \r\n retVal = []\r\n \r\n for value in broken_toi_line:\r\n value = value.replace(')\\n', '')\r\n try:\r\n converted_value = float(value)\r\n retVal.append(converted_value)\r\n except ValueError:\r\n pass\r\n \r\n return retVal\r\n\r\ndef get_player(given_file_string, metric):\r\n given_file = open(given_file_string, 'r')\r\n check = metric + ' Normalized'\r\n for line_i in given_file:\r\n if check in line_i:\r\n line_i = line_i.replace(check, '').replace(' -> ', '').replace(' less', '')\r\n return line_i\r\n \r\ndef loop_through_dict(given_dict):\r\n metrics = ['CA', 'FA', 'SA']\r\n for m in metrics:\r\n files_same = 0\r\n files_different = 0\r\n for g_c_f, g_n_f in given_dict.items():\r\n cor_player = get_player(g_c_f, m).strip().lower()\r\n nst_player = get_player(g_n_f, m).strip().lower()\r\n \r\n if(cor_player == nst_player):\r\n files_same = files_same + 1\r\n else:\r\n print(g_c_f)\r\n files_different = files_different + 1\r\n \r\n print(m)\r\n print('Players the same -> {} \\n Players different -> {}'.format(files_same, files_different))\r\n \r\ndef check_toi(project_dir, p1_name, p2_name):\r\n P1_LOCATION = 0\r\n P2_LOCATION = 1\r\n games_folder = project_dir + '\\\\out\\\\' + p1_name + ' - ' + p2_name + '\\\\games'\r\n \r\n nst_files = []\r\n corsica_files = []\r\n \r\n problem_files = {}\r\n good_files = {}\r\n \r\n pattern = '- [0-9]{2} [0-9]{2} [0-9]{4} - Total'\r\n for root, dirs, files in os.walk(games_folder):\r\n for file in files:\r\n matchObj = re.search(pattern, file)\r\n if matchObj:\r\n if 'Adjusted' in file:\r\n corsica_files.append(root + '\\\\' + file)\r\n else:\r\n nst_files.append(root + '\\\\' + file)\r\n \r\n for nst_i in nst_files:\r\n pattern1 = '[0-9]{2} [0-9]{2} [0-9]{4}'\r\n nst_i_timestamp = str(re.search(pattern1, nst_i).group())\r\n \r\n for cor_i in corsica_files:\r\n if re.search(nst_i_timestamp, cor_i):\r\n break\r\n \r\n nst_toi = get_toi(nst_i)\r\n cor_toi = get_toi(cor_i)\r\n \r\n p1_nst_toi = round(nst_toi[P1_LOCATION], 2)\r\n p2_nst_toi = round(nst_toi[P2_LOCATION], 2)\r\n p1_cor_toi = round(cor_toi[P1_LOCATION], 2)\r\n p2_cor_toi = round(cor_toi[P2_LOCATION], 2)\r\n \r\n if(p1_nst_toi != p1_cor_toi) or (p2_nst_toi != p2_cor_toi):\r\n problem_files[cor_i] = nst_i\r\n else:\r\n good_files[cor_i] = nst_i\r\n \r\n print('Problem Files')\r\n loop_through_dict(problem_files)\r\n \r\n print('Good Files')\r\n loop_through_dict(good_files)\r\n \r\nif __name__ == '__main__':\r\n this_file = os.path.abspath(inspect.getfile(inspect.currentframe()))\r\n project_dir = os.path.dirname(os.path.dirname(this_file))\r\n \r\n player1 = 'James Van Riemsdyk'\r\n player2 = 'Connor Brown'\r\n \r\n# main(project_dir, '\\\\etc\\\\Corsica\\\\by_game\\\\01 2018', True, player1, player2)\r\n\r\n check_toi(project_dir, player1, player2)\r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"PlayerComparison/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"567369427","text":"import edward as ed\nfrom edward.models import Gamma, Normal, Poisson\nimport tensorflow as tf\nimport numpy as np\n\n\ndef build_toy_dataset(N=40, noise_std=0.1):\n D = 1\n X = np.concatenate([np.linspace(0, 2, num=N / 2),\n np.linspace(6, 8, num=N / 2)])\n y = np.cos(X) + np.random.normal(0, noise_std, size=N)\n X = (X - 4.0) / 4.0\n X = X.reshape((N, D))\n return X, y\n\n\ndef nerual_net(X):\n X = tf.tanh(tf.matmul(X, W_0) + b_0)\n X = tf.matmul(X, W_1) + b_1\n return tf.reshape(X, [-1])\n\nN = 40\nD = 1\n\nX_train, y_train = build_toy_dataset(N)\n\n# model number of neurons with poisson and gamma prior\nwith tf.name_scope('model'):\n lam = Gamma(concentration=10.0, rate=2.0, name='lam')\n num_neurons = Poisson(rate=lam, name='num_neurons').sample()\n\n W_0 = Normal(loc=tf.zeros([D, num_neurons]), scale=tf.ones([D, num_neurons]), name='W_0')\n b_0 = Normal(loc=tf.zeros([num_neurons]), scale=tf.ones([num_neurons]), name='b_0')\n\n W_1 = Normal(loc=tf.zeros([num_neurons, 1]), scale=tf.ones([num_neurons, 1]), name='W_1')\n b_1 = Normal(loc=tf.zeros([1]), scale=tf.ones([1]), name='b_1')\n\n X = tf.placeholder(tf.float32, [N, D], name='X')\n y = Normal(loc=neural_net(X), scale=0.1 * tf.ones(N), name='y')\n\n\nwith tf.name_scope('posterior'):\n with tf.name_scope('qλ'):\n qλ = Gamma(concentration=tf.Variable(tf.random_gamma([1], [5])),\n rate=tf.Variable(tf.random_gamma([1], [2])))\n\n with tf.name_scope('qnum_neurons'):\n qnum_neurons = Poisson(rate=tf.Variable(rate=tf.random_gamma([1]), name='rate'))\n\n\n with tf.name_scope('qW_0'):\n qW_0 = Normal(loc=tf.Variable(tf.random_normal([D, num_neruons]), name='loc'),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([D, num_neurons]), name='scale')))\n\n with tf.name_scope('qW_1'):\n qW_1 = Normal(loc=tf.Variable(tf.random_normal([num_neurons, 1]), name='loc'),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([num_neurons, 1]), name='scale')))\n\n with tf.name_scope('qb_0'):\n qb_0 = Normal(loc=tf.Variable(tf.random_normal([num_neruons]), name='loc'),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([num_neurons]), name='scale')))\n\n\n with tf.name_scope('qb_1'):\n qb_1 = Normal(loc=tf.Variable(tf.random_normal([1]), name='loc'),\n scale=tf.nn.softplus(tf.Variable(tf.random_normal([1]), name='scale')))\n\n\ninference = ed.KLqp({λ:qλ, num_neruons:qnum_neurons,\n W_0:qW_0, b_0:qb_0,\n W_1:qW_1, b_1:qb_1},\n data={X:X_Train, y:y_train})\ninference.run(logdir='log')\n","sub_path":"src/bayesian-topology/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"457005677","text":"conveyor = [\"U\", \"D\", \"L\", \"R\"]\nconveyorMove = [[-1, 0], [1, 0], [0, -1], [0, 1]]\ncameraHelper = [[0, 1], [0, -1], [-1, 0], [1, 0]]\n\n\ndef isValidPos(grid, currRow, currCol):\n if currRow == 0 or currRow == len(grid):\n return False\n if currCol == 0 or currCol == len(grid[0]):\n return False\n if grid[currRow][currCol] == \"W\" or grid[currRow][currCol] == \"C\":\n return False\n if grid[currRow][currCol] in conveyor:\n return True\n else:\n # Check left right up and down for cameras\n # up and below\n for i in range(len(cameraHelper)):\n rowCopy = currRow\n colCopy = currCol\n while True:\n rowCopy += cameraHelper[i][0]\n colCopy += cameraHelper[i][1]\n if grid[rowCopy][colCopy] == \"C\":\n return False\n elif grid[rowCopy][colCopy] == \"W\":\n break\n return True\n\n\nincrimentHelper = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n\n\ndef buildTree(grid, currRow, currCol, n, m):\n if isValidPos(grid, currRow, currCol):\n currLevel = [[currRow, currCol]]\n else:\n currLevel = []\n visited = set()\n visited.add((currRow, currCol))\n tree = {}\n nextLevel = [[currRow, currCol]]\n level = 1\n while len(nextLevel) != 0:\n nextLevel = []\n for pos in currLevel:\n # Check up down left and right\n for x in range(4):\n row = pos[0]\n col = pos[1]\n row += incrimentHelper[x][0]\n col += incrimentHelper[x][1]\n for i, letter in enumerate(conveyor):\n if grid[row][col] == letter:\n row += conveyorMove[i][0]\n col += conveyorMove[i][1]\n if row <= n - 1 and row >= 0 and col <= m - 1 and col >= 0:\n if (row, col) in visited:\n continue\n else:\n visited.add((row, col))\n if isValidPos(grid, row, col):\n nextLevel.append([row, col])\n if nextLevel != []:\n tree[level] = nextLevel\n currLevel = nextLevel\n level += 1\n return tree\n\n\nif __name__ == \"__main__\":\n visited = []\n grid = []\n row, col = map(int, input().split())\n find = 0\n escapePos = []\n for rowi in range(row):\n grid.append(list(input()))\n visited.append([0 for _ in range(col)])\n for coli in range(col):\n if grid[rowi][coli] == \".\":\n find += 1\n escapePos.append([rowi, coli])\n if grid[rowi][coli] == \"S\":\n currRow = rowi\n currCol = coli\n tree = buildTree(grid, currRow, currCol, row, col)\n\n for end in escapePos:\n res = []\n for key, value in tree.items():\n if end in value:\n res.append(key)\n if len(res) == 0:\n print(-1)\n else:\n print(res[0])","sub_path":"CCC/18S3_2.py","file_name":"18S3_2.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"369313248","text":"#! /usr/bin/python3\n\nimport argparse\nimport boto3\n\n\nclient = boto3.client('route53')\nparser = argparse.ArgumentParser()\n\n\nparser.add_argument('-a', '--action', default='', help='CREATE | DELETE | UPSERT', action='store')\nparser.add_argument('-c', '--comment', default='', help='Comment the change', action='store')\nparser.add_argument('-n', '--name', default='', help='DNS name to use', action='store')\nparser.add_argument('-t', '--type', default='', help='Type of record (eg. A, CNAME, SOA, TXT)', action='store')\nparser.add_argument('-v', '--value', default='127.0.0.1', help='IP Address / Domain name to use for the new record', action='store')\nparser.add_argument('-z', '--zone', default='', help='Hosted Zone ID for the new record', action='store')\nparser.add_argument('--ttl', default=60, type=int, help='TTL for the new record', action='store')\n\n\nargs=parser.parse_args()\n\nresponse = client.change_resource_record_sets(\n HostedZoneId = args.zone,\n ChangeBatch={\n 'Comment': args.comment,\n 'Changes': [\n {\n 'Action': args.action,\n 'ResourceRecordSet': {\n 'Name': args.name,\n 'Type': args.type,\n 'TTL': args.ttl,\n 'ResourceRecords': [\n {\n 'Value': args.value\n }\n ]\n }\n },\n ]\n }\n)\n\nprint(response)","sub_path":"aws_route53_changer.py","file_name":"aws_route53_changer.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"418330136","text":"from .models.DS_net_trainer import *\nfrom .models.DS_net import *\nfrom .models.depth_trainer import *\nfrom .models.DepthModel import *\nimport torch\nimport sys\n\n\ninput_train_root_path, depth_train_root_path, input_test_root_path,\\\ndepth_test_root_path, semantics_train_root_path, semantics_test_root_path, \\\nnum_epochs,batch_size, use_gpu, pretrained, model_weights_path, resume, \\\nloss_type, learning_rate, read_semantics = sys.argv[1:]\n\nlearning_rate = float(learning_rate)\nuse_gpu = use_gpu.lower() == 'true'\npretrained = pretrained.lower() == 'true'\nread_semantics = read_semantics.lower() == 'true'\n\nif resume.lower() == 'none':\n resume = None\n\nif read_semantics:\n net = create_join_net(pretrained=False)\n\n trainer = JointTrainer(model=net,\n use_gpu=use_gpu,\n input_train_root_path=input_train_root_path,\n depth_train_root_path=depth_train_root_path,\n semantics_train_root_path=semantics_train_root_path,\n input_test_root_path=input_test_root_path,\n depth_test_root_path=depth_test_root_path,\n semantics_test_root_path=semantics_test_root_path,\n num_epochs=int(num_epochs),\n batch_size=int(batch_size),\n resume=resume,\n loss_type=loss_type\n )\n\n if not pretrained:\n trainer.train_model(checkpoint_freq=1)\n\n else:\n model_dict = torch.load(model_weights_path)\n net.load_state_dict(model_dict)\n trainer.model = net\n\n trainer.model.eval()\n av_depth_loss, av_depth_acc, semantic_loss, semantic_acc = trainer.validate()\n print('depth loss: %.4f' % av_depth_loss)\n print('depth acc: %.4f' % av_depth_acc)\n print('semantic loss: %.4f' % semantic_loss)\n print('semantic acc: %.4f' % semantic_acc)\n\nelse:\n # creating our network\n net = create_baseline(pretrained=True)\n\n trainer = DepthTrainer(model=net, use_gpu=use_gpu,\n input_train_root_path=input_train_root_path,\n target_train_root_path=depth_train_root_path,\n input_test_root_path=input_test_root_path,\n target_test_root_path=depth_test_root_path,\n num_epochs=int(num_epochs),\n batch_size=int(batch_size),\n resume=resume,\n loss_type=loss_type,\n learning_rate=learning_rate\n )\n\n if not pretrained:\n trainer.train_model(checkpoint_freq=1)\n\n else:\n model_dict = torch.load(model_weights_path, map_location=lambda storage, loc: storage)\n net.load_state_dict(model_dict)\n trainer.model = net\n trainer.model.eval()\n av_loss, av_acc = trainer.run(validate=True)\n print('av loss: ' + str(av_loss) + ' av acc: ' + str(av_acc))\n\n\n\n\n\n\n\n","sub_path":"back_up_pytorch/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"482888357","text":"# Copyright 2014 IBM Corp.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom testtools import matchers\n\nfrom keystone.common import dependency\nfrom keystone.tests import test_v3\n\n\n@dependency.requires('endpoint_policy_api')\nclass TestExtensionCase(test_v3.RestfulTestCase):\n\n EXTENSION_NAME = 'endpoint_policy'\n EXTENSION_TO_ADD = 'endpoint_policy_extension'\n\n\nclass EndpointPolicyTestCase(TestExtensionCase):\n \"\"\"Test endpoint policy CRUD.\n\n In general, the controller layer of the endpoint policy extension is really\n just marshalling the data around the underlying manager calls. Given that\n the manager layer is tested in depth by the backend tests, the tests we\n execute here concentrate on ensuring we are correctly passing and\n presenting the data.\n\n \"\"\"\n\n def setUp(self):\n super(EndpointPolicyTestCase, self).setUp()\n self.policy = self.new_policy_ref()\n self.policy_api.create_policy(self.policy['id'], self.policy)\n self.service = self.new_service_ref()\n self.catalog_api.create_service(self.service['id'], self.service)\n self.endpoint = self.new_endpoint_ref(self.service['id'], enabled=True)\n self.catalog_api.create_endpoint(self.endpoint['id'], self.endpoint)\n self.region = self.new_region_ref()\n self.catalog_api.create_region(self.region)\n\n # endpoint policy crud tests\n\n def test_crud_for_policy_for_explicit_endpoint(self):\n \"\"\"PUT, HEAD and DELETE for explicit endpoint policy.\"\"\"\n\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/endpoints/%(endpoint_id)s') % {\n 'policy_id': self.policy['id'],\n 'endpoint_id': self.endpoint['id']}\n\n self.put(url, expected_status=204)\n self.get(url, expected_status=204)\n self.head(url, expected_status=204)\n self.delete(url, expected_status=204)\n\n def test_crud_for_policy_for_service(self):\n \"\"\"PUT, HEAD and DELETE for service endpoint policy.\"\"\"\n\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/services/%(service_id)s') % {\n 'policy_id': self.policy['id'],\n 'service_id': self.service['id']}\n\n self.put(url, expected_status=204)\n self.get(url, expected_status=204)\n self.head(url, expected_status=204)\n self.delete(url, expected_status=204)\n\n def test_crud_for_policy_for_region_and_service(self):\n \"\"\"PUT, HEAD and DELETE for region and service endpoint policy.\"\"\"\n\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/services/%(service_id)s/regions/%(region_id)s') % {\n 'policy_id': self.policy['id'],\n 'service_id': self.service['id'],\n 'region_id': self.region['id']}\n\n self.put(url, expected_status=204)\n self.get(url, expected_status=204)\n self.head(url, expected_status=204)\n self.delete(url, expected_status=204)\n\n def test_get_policy_for_endpoint(self):\n \"\"\"GET /endpoints/{endpoint_id}/policy.\"\"\"\n\n self.put('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/endpoints/%(endpoint_id)s' % {\n 'policy_id': self.policy['id'],\n 'endpoint_id': self.endpoint['id']},\n expected_status=204)\n\n self.head('/endpoints/%(endpoint_id)s/OS-ENDPOINT-POLICY'\n '/policy' % {\n 'endpoint_id': self.endpoint['id']},\n expected_status=200)\n\n r = self.get('/endpoints/%(endpoint_id)s/OS-ENDPOINT-POLICY'\n '/policy' % {\n 'endpoint_id': self.endpoint['id']},\n expected_status=200)\n self.assertValidPolicyResponse(r, ref=self.policy)\n\n def test_list_endpoints_for_policy(self):\n \"\"\"GET /policies/%(policy_id}/endpoints.\"\"\"\n\n self.put('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/endpoints/%(endpoint_id)s' % {\n 'policy_id': self.policy['id'],\n 'endpoint_id': self.endpoint['id']},\n expected_status=204)\n\n r = self.get('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/endpoints' % {\n 'policy_id': self.policy['id']},\n expected_status=200)\n self.assertValidEndpointListResponse(r, ref=self.endpoint)\n self.assertThat(r.result.get('endpoints'), matchers.HasLength(1))\n\n def test_endpoint_association_cleanup_when_endpoint_deleted(self):\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/endpoints/%(endpoint_id)s') % {\n 'policy_id': self.policy['id'],\n 'endpoint_id': self.endpoint['id']}\n\n self.put(url, expected_status=204)\n self.head(url, expected_status=204)\n\n self.delete('/endpoints/%(endpoint_id)s' % {\n 'endpoint_id': self.endpoint['id']})\n\n self.head(url, expected_status=404)\n\n def test_region_service_association_cleanup_when_region_deleted(self):\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/services/%(service_id)s/regions/%(region_id)s') % {\n 'policy_id': self.policy['id'],\n 'service_id': self.service['id'],\n 'region_id': self.region['id']}\n\n self.put(url, expected_status=204)\n self.head(url, expected_status=204)\n\n self.delete('/regions/%(region_id)s' % {\n 'region_id': self.region['id']})\n\n self.head(url, expected_status=404)\n\n def test_region_service_association_cleanup_when_service_deleted(self):\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/services/%(service_id)s/regions/%(region_id)s') % {\n 'policy_id': self.policy['id'],\n 'service_id': self.service['id'],\n 'region_id': self.region['id']}\n\n self.put(url, expected_status=204)\n self.head(url, expected_status=204)\n\n self.delete('/services/%(service_id)s' % {\n 'service_id': self.service['id']})\n\n self.head(url, expected_status=404)\n\n def test_service_association_cleanup_when_service_deleted(self):\n url = ('/policies/%(policy_id)s/OS-ENDPOINT-POLICY'\n '/services/%(service_id)s') % {\n 'policy_id': self.policy['id'],\n 'service_id': self.service['id']}\n\n self.put(url, expected_status=204)\n self.get(url, expected_status=204)\n\n self.delete('/services/%(service_id)s' % {\n 'service_id': self.service['id']})\n\n self.head(url, expected_status=404)\n\n\nclass JsonHomeTests(TestExtensionCase, test_v3.JsonHomeTestMixin):\n EXTENSION_LOCATION = ('http://docs.openstack.org/api/openstack-identity/3/'\n 'ext/OS-ENDPOINT-POLICY/1.0/rel')\n PARAM_LOCATION = 'http://docs.openstack.org/api/openstack-identity/3/param'\n\n JSON_HOME_DATA = {\n EXTENSION_LOCATION + '/endpoint_policy': {\n 'href-template': '/endpoints/{endpoint_id}/OS-ENDPOINT-POLICY/'\n 'policy',\n 'href-vars': {\n 'endpoint_id': PARAM_LOCATION + '/endpoint_id',\n },\n },\n EXTENSION_LOCATION + '/policy_endpoints': {\n 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'\n 'endpoints',\n 'href-vars': {\n 'policy_id': PARAM_LOCATION + '/policy_id',\n },\n },\n EXTENSION_LOCATION + '/endpoint_policy_association': {\n 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'\n 'endpoints/{endpoint_id}',\n 'href-vars': {\n 'policy_id': PARAM_LOCATION + '/policy_id',\n 'endpoint_id': PARAM_LOCATION + '/endpoint_id',\n },\n },\n EXTENSION_LOCATION + '/service_policy_association': {\n 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'\n 'services/{service_id}',\n 'href-vars': {\n 'policy_id': PARAM_LOCATION + '/policy_id',\n 'service_id': PARAM_LOCATION + '/service_id',\n },\n },\n EXTENSION_LOCATION + '/region_and_service_policy_association': {\n 'href-template': '/policies/{policy_id}/OS-ENDPOINT-POLICY/'\n 'services/{service_id}/regions/{region_id}',\n 'href-vars': {\n 'policy_id': PARAM_LOCATION + '/policy_id',\n 'service_id': PARAM_LOCATION + '/service_id',\n 'region_id': PARAM_LOCATION + '/region_id',\n },\n },\n }\n","sub_path":"keystone/tests/test_v3_endpoint_policy.py","file_name":"test_v3_endpoint_policy.py","file_ext":"py","file_size_in_byte":9346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"611354336","text":"#!/usr/bin/env python\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pylab as p\n\nplot = pd.read_table(\"/Users/cmdb/qbb2015/stringtie/SRR072893/t_data.ctab\")\nroi = plot['FPKM'] >0\nplot2=plot[roi]['FPKM']\nplot3=np.log(plot2)\n\nmean=np.mean(plot3)\nstddev=np.std(plot3)\n\n\nx = mean + stddev * p.randn(1000)\n\n#n, bins, patches = p.hist(x, 50, normed=1, histtype='stepfilled')\n#p.setp(patches, 'facecolor', 'g', 'alpha', 0.75)\n\n\n#y = p.normpdf(bins, mean, stddev)\n\nx.sort() ###gets in order\n\n\n\nplt.figure()\nplt.hist(list(plot3))\ny = p.normpdf(x, mean, stddev)\n#plt.hist(plot.values)\nplt.plot(x,y*len(plot2),'r--')\n\n\nplt.title('Density Plot')\nplt.xlabel('log of fpkm')\nplt.ylabel('frequency')\n#plt.show()\nplt.savefig('density.png')\n\n\n","sub_path":"git/day3lunch3.py","file_name":"day3lunch3.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"462132572","text":"from simplify_fractions import GCD,simplify_fraction\n\ndef LCM(a,b): \n return (a*b) / GCD(a,b) \n\ndef check_zero_denominator(fractions):\n for elem in fractions:\n if elem[1] == 0:\n return True\n return False\n\ndef check_fraction_length_bigger_than_required(fractions):\n for elem in fractions:\n if len(elem) > 2:\n return True\n return False\n\ndef check_fraction_length_lower_than_required(fractions):\n for elem in fractions:\n if len(elem) < 2:\n return True\n return False\n\ndef validate_values(fractions):\n if not isinstance(fractions,list):\n raise ValueError('Passed fractions are not in the form of a list of tuples')\n elif len(fractions) > 2:\n raise ValueError('More than 2 fractions are being passed for the program to collect')\n elif check_fraction_length_bigger_than_required(fractions):\n raise ValueError('There is a fraction with more than two elements')\n elif check_fraction_length_lower_than_required(fractions):\n raise ValueError('There is a fraction with less than two elements')\n elif check_zero_denominator(fractions):\n raise ValueError('Second element of one of the fractions is zero - cannot divide by zero!!!')\n\ndef collect_fractions(fractions):\n firstFraction = simplify_fraction(fractions[0])\n secondFraction = simplify_fraction(fractions[1])\n\n newDenom = LCM(firstFraction[1],secondFraction[1])\n\n firstNumerator = newDenom / firstFraction[1]\n secondNumerator = newDenom / secondFraction[1]\n\n newNumer = firstNumerator + secondNumerator\n\n return simplify_fraction((int(newNumer),int(newDenom)))\n\n\ndef main():\n print(collect_fractions([(1, 4), (1, 2)]))\n print(collect_fractions([(1, 7), (2, 6)]))\n\nif __name__ == '__main__':\n main()","sub_path":"Week2/collect_fractions.py","file_name":"collect_fractions.py","file_ext":"py","file_size_in_byte":1796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"221791654","text":"# from attackgraph.sim_MPI_retrain import do_MPI_sim_retrain\nfrom attackgraph.simulation import series_sim_retrain\nfrom attackgraph import file_op as fp\nimport os\nimport numpy as np\nimport joblib\n\n\n#TODO: sim_MPI may cause error since name==main os.exit\ndef sim_retrain(env, game, mix_str_att, mix_str_def, epoch):\n # sim for retained attacker\n print(\"Begin sim_retrain_att.\")\n a_BD = sim_retrain_att(env, game, mix_str_def, epoch)\n print(\"Done sim_retrain_att.\")\n # sim for retained defender\n print('Begin sim_retrain_def')\n d_BD = sim_retrain_def(env, game, mix_str_att, epoch)\n print(\"Done sim_retrain_def\")\n\n return a_BD, d_BD\n\n\ndef sim_retrain_att(env, game, mix_str_def, epoch):\n rewards_att = fp.load_pkl(os.getcwd() + '/retrained_rew/' + 'rewards_att.pkl') # reward is np.array([1,2,3,4])\n k, gamma, alpha = game.param\n DIR = os.getcwd() + '/retrain_att/'\n str_list = [name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name)) and '.pkl' in name]\n num_str = len(str_list)\n if num_str != len(rewards_att):\n print('***************************')\n print('Retrain reward length does not match!')\n print('***************************')\n raise ValueError('Retrain reward length does not match!')\n util = []\n for i in range(num_str):\n nn_att = 'att_str_retrain' + str(i) + \".pkl\"\n nn_def = mix_str_def\n # if MPI_flag:\n # a_BD, _ = do_MPI_sim_retrain(nn_att, nn_def)\n # else:\n a_BD, _ = series_sim_retrain(env, game, nn_att, nn_def, 10)\n\n util.append(alpha*a_BD+(1-alpha)*rewards_att[i])\n\n best_idx = np.argmax(np.array(util))\n os.rename(os.getcwd() + '/retrain_att/' + 'att_str_retrain' + str(best_idx) + \".pkl\", os.getcwd() + \"/attacker_strategies/\" + 'att_str_epoch' + str(epoch) + '.pkl')\n change_scope(path=os.getcwd() + \"/attacker_strategies/\" + 'att_str_epoch' + str(epoch) + '.pkl', epoch=epoch, identity=1)\n return np.max(np.array(util))\n\n\n\ndef sim_retrain_def(env, game, mix_str_att, epoch):\n rewards_def = fp.load_pkl(os.getcwd() + '/retrained_rew/' + 'rewards_def.pkl')\n k, gamma, alpha = game.param\n DIR = os.getcwd() + '/retrain_def/'\n str_list = [name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name)) and '.pkl' in name]\n num_str = len(str_list)\n if num_str != len(rewards_def):\n print('***************************')\n print('Retrain reward length does not match!')\n print('***************************')\n raise ValueError('Retrain reward length does not match!')\n util = []\n for i in range(num_str):\n nn_att = mix_str_att\n nn_def = \"def_str_retrain\" + str(i) + \".pkl\"\n # if MPI_flag:\n # _, d_BD = do_MPI_sim_retrain(nn_att, nn_def)\n # else:\n _, d_BD = series_sim_retrain(env, game, nn_att, nn_def, 10)\n\n util.append(alpha * d_BD + (1 - alpha) * rewards_def[i])\n\n best_idx = np.argmax(np.array(util))\n os.rename(os.getcwd() + '/retrain_def/' + 'def_str_retrain' + str(best_idx) + \".pkl\", os.getcwd() + \"/defender_strategies/\" + 'def_str_epoch' + str(epoch) + '.pkl')\n change_scope(path=os.getcwd() + \"/defender_strategies/\" + 'def_str_epoch' + str(epoch) + '.pkl', epoch=epoch, identity=0)\n return np.max(np.array(util))\n\n\ndef change_scope(path, epoch, identity):\n loaded_params = joblib.load(os.path.expanduser(path))\n new_params = {}\n keys = loaded_params.keys()\n\n if identity == 0:\n old_keys = 'def_str_retrain0'\n new_keys = 'def_str_epoch' + str(epoch)\n elif identity == 1:\n old_keys = 'att_str_retrain0'\n new_keys = 'att_str_epoch' + str(epoch)\n else:\n raise ValueError(\"Identity error!\")\n\n for key in keys:\n a = key.replace(old_keys, new_keys)\n new_params[a] = loaded_params[key]\n\n joblib.dump(new_params, path)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"attackgraph/sim_retrain.py","file_name":"sim_retrain.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"198900258","text":"import pandas as pd\n\n\nclass ParseSampleSheet(object):\n \"\"\"Parses a sample sheet (CSV format) into two Python dictionaries, one for header details and one for sample details.\n\n :param csv_file: sample sheet\n\n Notes:\n Functions in this class are based on a standard sample sheet layout with the following header attributes:\n - Header\n - Manifests\n - Reads\n - Settings\n - Data\n \"\"\"\n def __init__(self, csv_file):\n self.csv = csv_file\n\n def parse_sample_sheet(self):\n # -----------------------------------------------------------------------------------------------------------\n # 1) Set some variables so we can use outside loops\n # -----------------------------------------------------------------------------------------------------------\n header_index = 0\n data_index = 0\n manifest_index = 0\n read_index = 0\n settings_index = 0\n df_run_data_temp = pd.DataFrame([])\n df_run_data_final = pd.DataFrame(columns=['Property', 'Value']) # this allows for easy appending later\n # -----------------------------------------------------------------------------------------------------------\n # 2) Parse sample sheet into pandas dataframe\n # -----------------------------------------------------------------------------------------------------------\n df_sample_sheet = pd.read_csv(self.csv, header=None)\n # -----------------------------------------------------------------------------------------------------------\n # 3) Get indexes where these details are\n for column in df_sample_sheet:\n for row_index, row in df_sample_sheet.iterrows():\n if row[column] == '[Data]':\n data_index = row_index\n df_run_data_temp = df_sample_sheet.ix[:data_index - 2, 0:1] # Put all header info into a separate df\n df_run_data_temp.columns = ['Property', 'Value']\n elif row[column] == '[Header]':\n header_index = row_index\n elif row[column] == '[Manifests]':\n manifest_index = row_index\n elif row[column] == '[Reads]':\n read_index = row_index\n elif row[column] == '[Settings]':\n settings_index = row_index\n else:\n pass\n # ----------------------------------------------------------------------------------------------------------\n # 4) Look at header info first: separate the header types and modify to correctly re-merge later.\n # ----------------------------------------------------------------------------------------------------------\n # [Header]\n df_headers = df_run_data_temp.ix[header_index + 1:manifest_index - 1]\n # [Manifests]\n df_manifests = df_run_data_temp.ix[manifest_index + 1:read_index - 2]\n for row_index, row in df_manifests.iterrows():\n row['Property'] = 'Manifest ' + row['Property']\n # [Reads]\n df_reads = df_run_data_temp.ix[read_index + 1:settings_index - 2]\n read_list = []\n for row_index, row in df_reads.iterrows():\n read_list.append(row['Property'])\n # [Settings]\n df_settings = df_run_data_temp.ix[settings_index + 1:]\n # Combine all\n df_run_data_final = df_run_data_final.append(df_headers)\n df_run_data_final = df_run_data_final.append(df_manifests)\n df_run_data_final = df_run_data_final.append({'Property': 'Reads', 'Value': read_list}, ignore_index=True)\n df_run_data_final = df_run_data_final.append(df_settings)\n df_run_data_final = df_run_data_final.reset_index(drop=True)\n # Convert to dictionary, set_index avoids the index being used a key\n run_dict = df_run_data_final.set_index('Property')['Value'].to_dict()\n # ----------------------------------------------------------------------------------------------------------\n # 5) Now look at sample data: extract lab numbers and transpose dataframe to make dictionary work per patient.\n # ----------------------------------------------------------------------------------------------------------\n df_data = df_sample_sheet.ix[data_index + 1:]\n df_data = df_data.reset_index(drop=True)\n # Change column names\n df_data.columns = df_data.iloc[0]\n df_data = df_data.reindex(df_data.index.drop(0))\n # Drop any columns with \"NaN\" all the way through\n df_data = df_data.dropna(axis=1, how='all')\n # Use lab numbers as column headings and initial key in dictionary\n sample_id_list = []\n for row_index, row in df_data.iterrows():\n sample_id_list.append(row['Sample_Name'][3:12])\n df_data_trans = df_data.transpose()\n df_data_trans.columns = sample_id_list\n # Convert to dictionary\n sample_dict = df_data_trans.to_dict()\n # ----------------------------------------------------------------------------------------------------------\n return run_dict, sample_dict\n\n '''\n Method 2:\n\n def get_run_info(csv_file):\n iem = ''\n investigator = ''\n experiment = ''\n run_date = ''\n workflow = ''\n app = ''\n assay = ''\n description = ''\n chemistry = ''\n worksheet = ''\n manifest = ''\n reads = ''\n data_index = 0\n read_index = 0\n manifest_index = 0\n read1 = 0\n read2 = 0\n sample_dict = {}\n\n with open(csv_file, 'r') as c:\n reader = csv.reader(c, delimiter=',')\n for i, row in enumerate(reader):\n if row[0] == 'IEMFileVersion':\n iem = row[1]\n elif row[0] == \"Investigator Name\":\n investigator = row[1]\n elif row[0] == 'Experiment Name':\n experiment = row[1]\n elif row[0] == 'Date':\n run_date = row[1]\n elif row[0] == 'Workflow':\n workflow = row[1]\n elif row[0] == 'Application':\n app = row[1]\n elif row[0] == 'Assay':\n assay = row[1]\n elif row[0] == 'Description':\n description = row[1]\n elif row[0] == 'Chemistry':\n chemistry = row[1]\n elif row[0] == 'worksheet':\n worksheet = row[1]\n elif row[0] == '[Manifests]':\n manifest_index = i\n elif row[0] == '[Reads]':\n read_index = i\n elif row[0] == '[Data]':\n data_index = i\n else:\n pass\n if i == (read_index + 1):\n read1 = row[0]\n if i == (read_index + 2):\n read2 = row[0]\n if i == (manifest_index + 1):\n manifest = row[1]\n reads = \"(%s,%s)\" % (read1, read2)\n\n run_dict = {\n \"IEM\": iem,\n \"Investigator\": investigator,\n \"Experiment\": experiment,\n \"Date\": run_date,\n \"Workflow\": workflow,\n \"Application\": app,\n \"Assay\": assay,\n \"Description\": description,\n \"Chemistry\": chemistry,\n \"worksheet\": worksheet,\n \"Manifest\": manifest,\n \"Reads\": reads\n }\n\n df_sample_sheet = pd.read_csv(csv_file, header=None)\n df_data = df_sample_sheet.ix[data_index + 1:]\n for row_index, row in df_data.iterrows():\n lab_id = str(row[1])[3:12]\n sample_id = row[0]\n name = row[1]\n plate = row[2]\n well = row[3]\n index1 = row[5]\n index2 = row[7]\n sample_manifest = row[8]\n project = row[10]\n\n sample_dict[lab_id] = {\n \"Sample_id\": sample_id,\n \"Name\": name,\n \"Plate\": plate,\n \"Well\": well,\n \"Index1\": index1,\n \"Index2\": index2,\n \"Manifest\": sample_manifest,\n \"Project\": project\n }\n\n print run_dict, sample_dict\n '''\n","sub_path":"aml/parse_sample_sheet.py","file_name":"parse_sample_sheet.py","file_ext":"py","file_size_in_byte":8059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"399581316","text":"# -*- coding: utf-8 -*-\n\"\"\"\ntransform.py\n\nThis script contains functions that take inputs and transform them to be of use in \nbigger functions where they are called. They focus mainly on overlapping\nrepeated structures and annotation markers.\n\nThis file contains the following functions:\n \n * create_anno_remove_overlaps - Turns rows of repeats into marked rows with \n annotation markers for the start indices and zeroes otherwise. After \n removing the annotations that have overlaps, creates separate arrays\n for annotations with overlaps and annotations without overlaps. Finally,\n the annotation markers are checked and fixed if necessary.\n \n * create_anno_rows - Turns rows of repeats into marked rows with annotation\n markers for start indices and zeroes otherwise. Then checks if the correct \n annotation markers were given and fixes the markers if necessary.\n \n * remove_overlaps - Removes any pairs of repeats with the same length and \n annotation marker where at least one pair of repeats overlap in time\n \n * separate_anno_markers - Expands vector of non-overlapping repeats into\n a matrix representation. The matrix representation is a visual recored of\n where all of the repeats in a song start and end.\n\"\"\"\n\nimport numpy as np\n\ndef create_anno_remove_overlaps(k_mat,song_length,band_width):\n \"\"\"\n Turn k_mat into marked rows with annotation markers for the start indices \n and zeroes otherwise. After removing the annotations that have overlaps, \n output k_lst_out which only contains rows that have no overlaps. Then \n take the annotations that have overlaps from k_lst_out and put them in\n overlap_lst. Lastly, check if the proper sequence of annotation markers \n was given and fix them if necessary.\n \n Args\n ----\n k_mat: np.array\n List of pairs of repeats of length 1 with annotations \n marked. The first two columns refer to the first repeat\n of the pair, the second two refer to the second repeat of\n the pair, the fifth column refers to the length of the\n repeats, and the sixth column contains the annotation markers.\n \n song_length: int\n number of audio shingles\n \n band_width: int\n the length of repeats encoded in k_mat\n \n Returns\n -------\n pattern_row: np.array\n row that marks where non-overlapping repeats occur, \n marking the annotation markers for the start indices \n and 0's otherwise\n \n k_lst_out: np.array\n list of pairs of repeats of length band_width that \n contain no overlapping repeats with annotations\n marked\n \n overlap_lst: np.array\n list of pairs of repeats of length band_width that\n contain overlapping repeats with annotations marked\n \"\"\"\n # Step 0: Initialize outputs: Start with a vector of all 0's for\n # pattern_row and assume that the row has no overlaps\n pattern_row = np.zeros((1,song_length)).astype(int)\n overlap_lst = []\n bw = band_width\n \n # Step 0a: Find the number of distinct annotations\n anno_lst = k_mat[:,5] # Get the elements of k_mat's fifth column\n anno_max = anno_lst.max(0) # Max in each column\n \n # Step 1: Loop over the annotations\n for a in range (1,anno_max+1):\n # Step 1a: Add 1's to pattern_row to the time steps where repeats with\n # annotation a begin\n ands = (anno_lst == a) # Check if anno_lst is equal to a\n bind_rows = [k_mat[ands,0],k_mat[ands,2]]\n start_inds = np.concatenate(bind_rows)\n pattern_row[0,start_inds-1] = a\n\n # Step 2: check annotation by annotation\n # Start with row of 0's\n good_check = np.zeros((1,song_length)).astype(int) \n good_check[0,start_inds-1] = 1 # Add 1 to all time steps where repeats \n # with annotation a begin\n \n # Using reconstruct_full_block to check for overlaps\n block_check = reconstruct_full_block(good_check,bw)\n\n # If there are any overlaps, remove the bad annotations from both\n # the pattern_row and from the k_lst_out\n if block_check.max() > 1:\n # Remove the bad annotations from pattern_row\n pattern_row[0,start_inds-1] = 0\n \n # Remove the bad annotations from k_lst_out and add them to \n # overlap_lst\n remove_inds = ands\n\n temp_add = k_mat[remove_inds,:]\n overlap_lst.append(temp_add)\n \n if np.any(remove_inds == True):\n # Convert the boolean array rm_inds into an array of integers\n remove_inds = np.array(remove_inds).astype(int)\n remove = np.where(remove_inds==1)\n \n # Delete the row that meets the condition set by remove_inds\n k_mat = np.delete(k_mat,remove,axis=0)\n \n anno_lst = k_mat[:,5]\n \n inds_markers = np.unique(pattern_row)\n # If any of inds_markers[i] is equal to zero, then remove this index\n if np.any(inds_markers == 0):\n inds_markers = np.delete(inds_markers,0)\n \n # If inds_markers is not empty, then execute this if statement\n if inds_markers.size > 0:\n for na in range(1,len(inds_markers)+1):\n IM = inds_markers[na-1]\n if IM > na:\n # Fix the annotations in pattern_row\n temp_anno = (pattern_row == IM)\n pattern_row = pattern_row - (IM * temp_anno) + (na * temp_anno)\n \n # If k_mat is not empty, then execute this if statement\n if k_mat.size > 0:\n k_lst_out = np.unique(k_mat,axis=0)\n for na in range(1,len(inds_markers)+1):\n IM = inds_markers[na-1]\n if IM > na:\n # Fix the annotations in k_lst_out\n kmat_temp_anno = (k_lst_out[:,5] == IM)\n k_lst_out[:,5] = k_lst_out[:,5] - (IM * kmat_temp_anno) + \\\n (na * kmat_temp_anno)\n else:\n k_lst_out = np.array([])\n \n # Edit the annotations in the overlap_lst so that the annotations start\n # with 1 and increase one each time\n if overlap_lst.size > 0:\n overlap_lst = np.unique(overlap_lst,axis=0)\n overlap_lst = add_annotations(overlap_lst, song_length)\n\n output = (pattern_row,k_lst_out,overlap_lst)\n \n return output\n\n\ndef create_anno_rows(k_mat,song_length):\n \"\"\"\n Turn the k_mat into marked rows with annotation markers for the start \n indices and zeroes otherwise. Check if the proper sequence of annotation \n markers was given and fix them if necessary.\n\n Args\n ----\n k_mat: np.array\n List of pairs of repeats of length 1 with annotations \n marked. The first two columns refer to the first repeat\n of the pair, the second two refer to the second repeat of\n the pair, the fifth column refers to the length of the\n repeats, and the sixth column contains the annotation markers.\n \n song_length: int\n song length, which is the number of audio shingles\n \n Returns\n ------- \n pattern_row: np.array\n row that marks where non-overlapping repeats\n occur, marking the annotation markers for the\n start indices and zeroes otherwise.\n\n k_lst_out: np.array\n list of pairs of repeats of length BAND_WIDTH that\n contain no overlapping repeats with annotations marked.\n \"\"\"\n # Step 0 Initialize outputs: Start with a vector of all 0's for \n # pattern_row and assume that the row has no overlaps \n pattern_row = np.zeros((1,song_length)).astype(int)\n \n # Step 0a: Find the number of distinct annotations\n anno_lst = k_mat[:,5] # Get the elements of k_mat's fifth column\n anno_max = anno_lst.max(0) # Set the number of max elements in each column\n \n # Step 1: Loop over the annotations\n for a in range(1,anno_max+1):\n ands = (anno_lst == a) # Check if anno_lst is equal to a \n \n # Combine rows into a single matrix\n bind_rows = [k_mat[ands,0],k_mat[ands,2]]\n start_inds = np.concatenate(bind_rows)\n pattern_row[0,start_inds-1] = a\n \n # Step 2: Check that in fact each annotation has a repeat associated to it\n inds_markers = np.unique(pattern_row)\n\n # If any of inds_markers[i] == 0, then delete this index\n if np.any(inds_markers == 0):\n inds_markers = np.delete(inds_markers,0)\n\n if inds_markers.size > 0:\n for na in range (1,len(inds_markers)+1):\n IM = inds_markers[na-1]\n if IM > na:\n # Fix the annotations in pattern_row\n temp_anno = (pattern_row == IM)\n pattern_row = pattern_row - (IM * temp_anno) + (na * temp_anno)\n \n # Edit the annotations to match the annotations in pattern_row\n if k_mat.size > 0:\n k_lst_out = np.unique(k_mat, axis=0)\n for na in range (1,len(inds_markers)+1):\n IM = inds_markers[na-1]\n if IM > na:\n # Fix the annotaions in k_lst_out\n kmat_temp_anno = (k_lst_out[:,5] == IM)\n k_lst_out[:,5] = k_lst_out[:,5] - (IM * kmat_temp_anno) + \\\n (na*kmat_temp_anno)\n else:\n k_lst_out = np.array([])\n \n output = (pattern_row,k_lst_out)\n \n return output\n\n\ndef remove_overlaps(input_mat, song_length): \n \"\"\"\n Removes any pairs of repeat length and specific annotation marker \n where there exists at least one pair of repeats that do\n overlap in time.\n\n Args\n ----\n input_mat: np.array(int)\n List of pairs of repeats with annotations marked. The first \n two columns refer to the first repeat or the pair, the second \n two refer to the second repeat of the pair, the fifth column \n refers to the length of the repeats, and the sixth column \n contains the annotation markers.\n \n song_length: int\n the number of audio shingles\n \n Returns\n -------\n lst_no_overlaps: np.array(int)\n List of pairs of repeats with annotations marked. All the \n repeats of a given length and with a specific annotation \n marker do not overlap in time.\n \n matrix_no_overlaps: np.array(int)\n Matrix representation of lst_no_overlaps with one row for \n each group of repeats\n \n key_no_overlaps: np.array(int)\n Vector containing the lengths of the repeats encoded in \n each row of matrix_no_overlaps\n \n annotations_no_overlaps: np.array(int)\n Vector containing the annotation markers of the repeats \n encoded in each row of matrix_no_overlaps\n \n all_overlap_lst: np.array(int)\n List of pairs of repeats with annotations marked removed \n from input_mat. For each pair of repeat length and specific \n annotation marker, there exist at least one pair of repeats \n that do overlap in time.\n \"\"\"\n # Same list with repetitions removed\n bw_vec = np.unique(input_mat[:,4])\n \n # Convert L to python list of np arrays\n L = []\n for i in range(0,(np.shape(input_mat)[0])-1):\n L.append(np.array(input_mat[i,:]))\n\n # Sort list ascending, then reverse it\n bw_vec = np.sort(bw_vec)\n bw_vec = bw_vec[::-1]\n\n mat_NO = []\n key_NO = []\n anno_NO = []\n all_overlap_lst = []\n \n # While bw_vec still has entries\n while np.size(bw_vec) != 0:\n bw_lst = []\n bw = bw_vec[0]\n # Extract pairs of repeats of length BW from the list of pairs of\n # repeats with annotation markers\n # Create bw_lst\n i = 0 \n while i < len(L):\n line = L[i][4]\n if line == bw:\n bw_lst.append(line)\n L[i] = np.array([])\n i=i+1\n #endWhile\n \n # Remove blanked entries from L (appended to bw_lst)\n\n # Doesn't like elem wise comparison when right operand numpy array\n L = list(filter(lambda L: L.tolist() != [], L))\n if bw > 1:\n # Use LIGHTUP_PATTERN_ROW_GB to do the following three things:\n # ONE: Turn the BW_LST into marked rows with annotation markers for \n # the start indices and 0's otherwise \n # TWO: After removing the annotations that have overlaps, output\n # BW_LST_OUT which only contains rows that have no overlaps\n # THREE: The annotations that have overlaps get removed from \n # BW_LST_OUT and gets added to ALL_OVERLAP_LST\n \n tuple_of_outputs = create_anno_remove_overlaps(bw_lst, \n song_length, bw)\n \n pattern_row = tuple_of_outputs[0]\n bw_lst_out = tuple_of_outputs[1]\n overlap_lst = tuple_of_outputs[2]\n\n\n # Convert the numpy arrays to lists of 1d numpy arrays\n bw_lst_out_py = []\n for i in range(0,(np.shape(bw_lst_out)[0])-1):\n bw_lst_out_py.append(np.array(input_mat[i,:]))\n\n overlap_lst_py = []\n for i in range(0,(np.shape(overlap_lst)[0])-1):\n overlap_lst_py.append(np.array(input_mat[i,:]))\n\n # If there are lines to add\n if len(overlap_lst_py) != 0:\n # Add them \n all_overlap_lst.extend(overlap_lst_py)\n else:\n # Similar to the IF case -- \n # Use LIGHTUP_PATTERN_ROW_BW_1 to do the following two things:\n # ONE: Turn the BW_LST into marked rows with annotation markers for \n # the start indices and 0's otherwise \n # TWO: In this case, there are no overlaps. Then BW_LST_OUT is just\n # BW_LST. Also in this case, THREE from above does not exist\n tuple_of_outputs = create_anno_rows(bw_lst, song_length)\n pattern_row = tuple_of_outputs[0]\n bw_lst_out_orig = tuple_of_outputs[1]\n \n # Convert the numpy arrays to lists of 1d numpy arrays\n bw_lst_out_py = []\n for i in range(0,(np.shape(bw_lst_out)[0])-1):\n bw_lst_out_py.append(np.array(input_mat[i,:]))\n\n overlap_lst_py = []\n for i in range(0,(np.shape(overlap_lst)[0])-1):\n overlap_lst_py.append(np.array(input_mat[i,:]))\n\n if np.max(np.max(pattern_row)) > 0:\n # Separate ALL annotations. In this step, we expand a row into a\n # matrix, so that there is one group of repeats per row.\n \n tuple_of_outputs = separate_anno_markers(bw_lst_out, \n song_length, bw, \n pattern_row)\n pattern_mat = tuple_of_outputs[0]\n pattern_key = tuple_of_outputs[1]\n anno_temp_lst = tuple_of_outputs[2]\n \n \n # Convert the numpy arrays to lists of 1d numpy arrays\n pattern_mat_py = []\n for i in range(0,(np.shape(pattern_mat)[0])-1):\n pattern_mat_py.append(np.array(pattern_mat[i,:]))\n\n pattern_key_py = []\n for i in range(0,(np.shape(pattern_key)[0])-1):\n pattern_key_py.append(np.array(pattern_key[i,:]))\n\n\n anno_temp_lst_py = []\n for i in range(0,(np.shape(anno_temp_lst)[0])-1):\n anno_temp_lst_py.append(np.array(anno_temp_lst[i,:]))\n\n\n else:\n pattern_mat = []\n pattern_key = []\n\n \n if np.sum(np.sum(pattern_mat)) > 0:\n # If there are lines to add, add them\n if np.shape(mat_NO)[0] != 0:\n mat_NO.append(pattern_mat)\n if np.shape(key_NO)[0] != 0:\n key_NO.append(pattern_key)\n if np.shape(anno_NO)[0] != 0:\n anno_NO.append(anno_temp_lst)\n\n\n # Add to L\n L.append(bw_lst_out_py)\n # Sort list by 5th column\n # Create dict to re-sort L\n re_sort_L = {}\n for i in range(0, len(L)-1):\n # Get 5th column values into list of tuples\n # Key = index, value = value\n re_sort_L[i] = (L[i])[4]\n # Convert to list of tuples and sort\n re_sort_L = re_sort_L.items()\n # Sort that dict by values \n re_sort_L = sorted(re_sort_L, key=lambda re_sort_L: re_sort_L[1])\n\n \n sorted_inds = [x[0] for x in re_sort_L]\n # Sort L according to sorted indexes\n L = [L for sorted_inds, L in sorted(zip(sorted_inds, L))]\n\n # Will just use a np array here\n np_mat_L = np.array(L)\n bw_vec = np.unique(np_mat_L[:,4])\n \n # Sort list ascending, then reverse it\n bw_vec = np.sort(bw_vec)\n bw_vec = bw_vec[::-1]\n # Remove entries that fall below the bandwidth threshold\n cut_index = 0\n\n for value in bw_vec:\n # If the value is above the bandwidth \n if value < bw:\n cut_index = cut_index+1\n #endfor\n bw_vec = bw_vec[cut_index:np.shape(bw_vec)[0]]\n\n #endWhile\n\n # Set the outputs\n lst_no_overlaps = np.array(L)\n \n # Turn key_NO, mat_NO, and KEY_NO to numpy lists\n key_NO = list(filter(lambda key_NO: key_NO.tolist() != [], key_NO))\n mat_NO = list(filter(lambda mat_NO: mat_NO.tolist() != [], mat_NO))\n anno_NO = list(filter(lambda anno_NO: anno_NO.tolist() != [], anno_NO))\n\n if len(key_NO) !=0:\n key_NO = np.concatenate(key_NO)\n else:\n key_NO = np.array([])\n \n if len(mat_NO) !=0:\n mat_NO = np.concatenate(mat_NO)\n else:\n mat_NO = np.array([])\n \n if len(anno_NO) !=0:\n anno_NO = np.concatenate(anno_NO)\n else:\n anno_NO = np.array([])\n\n # Convert to np.array\n all_overlap_lst = np.array(all_overlap_lst)\n if np.shape(all_overlap_lst)[0] != 0:\n overlap_inds = np.argsort(all_overlap_lst[:,4])\n all_overlap_lst = all_overlap_lst[overlap_inds, :]\n #endif\n \n key_NO = np.sort(key_NO)\n mat_inds = np.argsort(key_NO)\n if np.shape(mat_NO)[0] != 0:\n matrix_no_overlaps = mat_NO[mat_inds,:]\n else:\n matrix_no_overlaps = mat_NO\n \n key_no_overlaps = key_NO\n if np.shape(anno_NO)[0] != 0:\n annotations_no_overlaps = mat_NO[mat_inds,:]\n else:\n annotations_no_overlaps = mat_NO\n \n # Compile final outputs to a tuple\n output_tuple = (lst_no_overlaps, matrix_no_overlaps, key_no_overlaps, \n annotations_no_overlaps, all_overlap_lst)\n \n return output_tuple\n\ndef separate_anno_markers(k_mat, sn, band_width, pattern_row): \n \"\"\"\n Expands pattern_row, a row vector that marks where non-overlapping\n repeats occur, into a matrix representation or np.array. The dimension of \n this array is twice the pairs of repeats by the length of the song (sn). \n k_mat provides a list of annotation markers that is used in separating the \n repeats of length band_width into individual rows. Each row will mark the \n start and end time steps of a repeat with 1's and 0's otherwise. The array \n is a visual record of where all of the repeats in a song start and end.\n\n Args\n ----\n k_mat: np.array\n List of pairs of repeats of length BAND_WIDTH with annotations \n marked. The first two columns refer to the start and end time\n steps of the first repeat of the pair, the second two refer to \n the start and end time steps of second repeat of the pair, the \n fifth column refers to the length of the repeats, and the sixth \n column contains the annotation markers. We will be indexing into \n the sixth column to obtain a list of annotation markers. \n \n sn: number\n song length, which is the number of audio shingles\n \n band_width: number \n the length of repeats encoded in k_mat\n \n pattern_row: np.array\n row vector of the length of the song that marks where \n non-overlapping repeats occur with the repeats' corresponding \n annotation markers and 0's otherwise\n\n Returns\n -------\n pattern_mat: np.array\n matrix representation where each row contains a group of repeats\n marked \n \n patter_key: np.array\n column vector containing the lengths of the repeats encoded in \n each row of pattern_mat\n \n anno_id_lst: np.array \n column vector containing the annotation markers of the repeats \n encoded in each row of pattern_mat\n \"\"\"\n \n #List of annotation markers \n anno_lst = k_mat[:,5] \n\n #Initialize pattern_mat: Start with a matrix of all 0's that has\n #the same number of rows as there are annotations and sn columns \n pattern_mat = np.zeros((anno_lst.size, sn), dtype = np.intp)\n\n #Separate the annotions into individual rows \n if anno_lst.size > 1: #If there are two or more annotations \n #Loops through the list of annotation markers \n for a in anno_lst: \n #Find starting indices: \n #Start index of first repeat a \n a_one = k_mat[a-1, 0] - 1\n\n #Start index of second repeat a\n a_two = k_mat[a-1, 2] - 1\n\n #Start indices of repeat a \n s_inds = np.append(a_one, a_two)\n\n #Replace entries at each repeats' start time with \"1\"\n pattern_mat[a - 1, s_inds] = 1\n\n #Creates row vector with the same dimensions of anno_lst \n pattern_key = band_width * np.ones((anno_lst.size, 1)).astype(int)\n\n else: #When there is one annotation \n pattern_mat = pattern_row \n pattern_key = band_width\n \n #Transpose anno_lst from a row vector into a column vector \n anno_id_lst = anno_lst.reshape((1,2)).transpose()\n \n output = (pattern_mat, pattern_key, anno_id_lst)\n \n return output \n","sub_path":"aligned-hierarchies/transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":22127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"149019321","text":"import sys\n\ndef get_list(data):\n retlist = []\n for c in data:\n retlist.append( ord(c) )\n retlist += [17, 31, 73, 47, 23]\n return retlist\n\n#Given all input data, get the answer to the question\ndef get_answer(data, list_length=256):\n lengths = get_list(data)\n the_list = [x for x in range(list_length)]\n c_position = 0\n skip_size = 0\n\n #perform 64 rounds\n for _ in range(64):\n for length in lengths:\n for i in range(length//2):\n pos1 = (c_position+i)%list_length\n pos2 = (c_position+length-1-i)%list_length\n the_list[pos1], the_list[pos2] = the_list[pos2], the_list[pos1]\n\n c_position = (c_position + length + skip_size)%list_length\n skip_size += 1\n\n #get the xors\n xor_numbers = []\n for block in range(16):\n num = 0\n for x in the_list[block*16:block*16+16]:\n num ^= x\n xor_numbers.append( num )\n \n #get the string\n retstring = \"\"\n for num in xor_numbers:\n retstring += hex(num)[2:].zfill(2)\n\n\n return retstring\n\ndef main():\n data = input().strip()\n answer = get_answer(data)\n print(answer)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2017/Day10/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"519046068","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 29 18:16:49 2018\n\n@author: edanner\n\nThis is the script that I originally threw together to try and understand and sort the sequences from pacbio. I took pieces for the more\nrecent 'sortingseqs.py' . Just took dieas from it. Only for parts.\n\n\"\"\"\n\n\n\nimport os\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.Alphabet import generic_protein\nfrom Bio.Alphabet import IUPAC\n\n\n#\ninputFileName = \"../seqsfwd/fwdcellsand2kb99 .fasta\"\noutputFileName = \"DandG_mCherry_seq.fasta\"\noutputFileNameshort = \"DandG_mCherry_shortseq.fasta\"\noutputFileNamelong = \"DandG_mCherry_longseq.fasta\"\n\n\n#his is to compile a counting of the different sequence outcomes\n \nlengthList = []\n\ncountingAll = 0\nshortmCherryListCount = 0\nBFPfwd = 0\nBFPrev = 0\nBFPlong = 0\n\nmCherryF = 0\nmCherryR = 0\n\nHITImCherryF = 0\nHITImCherryR = 0\n\nvenus = 0\n\n\n\n#mCherry sequences searched for\nmCherryF_seq = Seq('CGGCGCCCTGAAGGGCGAGATCAA', IUPAC.unambiguous_dna)\nmCherryR_seq = mCherryF_seq.reverse_complement()\n\n#BFP sequences searched for (this is near the 3' end so that the whole issue with ssa or polymerase is avoided)\nBFPF_seq = Seq('TGGAGTTCCGCACCGCCGCCGGGAT', IUPAC.unambiguous_dna)\nBFPR_seq = BFPF_seq.reverse_complement()\n\n#venus sequences searched for\nvenus_seq = Seq('TGGAGTTCGTGACCGCCG', IUPAC.unambiguous_dna)\n\n\nmCherryList = []\nshortmCherryList = []\nlongmCherryList = []\nmCherryLengths = []\n\n\n#check for BFP seq\nfor sequence in SeqIO.parse(inputFileName, \"fasta\"):\n countingAll += 1\n if BFPF_seq in sequence:\n BFPfwd +=1\n if len(sequence) > 1700:\n BFPlong += 1\n elif BFPR_seq in sequence:\n BFPrev +=1\n\n#check for mCherry\nfor sequence in SeqIO.parse(inputFileName, \"fasta\"):\n if mCherryF_seq in sequence: \n mCherryF += 1\n mCherryList.append(sequence)\n mCherryLengths.append(len(sequence))\n elif mCherryR_seq in sequence:\n mCherryR += 1\n\n#check for mCherry HITI\nfor sequence in SeqIO.parse(inputFileName, \"fasta\"):\n if (mCherryF_seq in sequence) and (BFPF_seq in sequence):\n HITImCherryF += 1\n elif (mCherryR_seq in sequence) and (BFPF_seq in sequence):\n HITImCherryR += 1\n\n#check for venus \nfor sequence in SeqIO.parse(inputFileName, \"fasta\"):\n if venus_seq in sequence:\n venus += 1\n \nfor sequence in SeqIO.parse(inputFileName, \"fasta\"):\n if (BFPF_seq in sequence) or (mCherryF_seq in sequence) or (mCherryR_seq in sequence) or (venus_seq in sequence):\n lengthList.append(len(sequence))\n\nfor sequence in mCherryList:\n if len(sequence) <= 1800:\n shortmCherryList.append(sequence)\n elif len(sequence) >= 1800:\n longmCherryList.append(sequence)\n\n#Writing mCherry + cells to file\nSeqIO.write(mCherryList, outputFileName, \"fasta\")\nSeqIO.write(shortmCherryList, outputFileNameshort, \"fasta\")\nSeqIO.write(longmCherryList, outputFileNamelong, \"fasta\")\n\n\n \nprint(mCherryLengths)\n\nprint(\"number of reads in file:\",countingAll)\nprint(\"BFPf alignments:\", BFPfwd)\nprint(\"BFPf of size for original allele:\", BFPlong)\n\nprint(\"BFP inverted alignments:\", BFPrev)\nprint(\"mCherryF seq:\", mCherryF)\nprint(\"mCherryR seq:\", mCherryR)\nprint(\"HITI mCherryF:\", HITImCherryF)\nprint(\"HITI mCherryR:\", HITImCherryR)\nprint(\"Venus counts:\", venus)\n\nprint(\"short mCherryList List length:\", len(shortmCherryList))\nprint(\"long mCherryList List length:\", len(longmCherryList))\n\n\n#Checkign for Deletions \n\nnotdel = 0\ndeletions = 0\n\n\n\n\nfor x in lengthList:\n if x >=1090:\n notdel += 1\n else:\n deletions += 1\n\n \nprint(\"Deletions:\", deletions,\". Not deletion seq:\", notdel, \".\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"scripts/oldsortingscript.py","file_name":"oldsortingscript.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"624213642","text":"# import the necessary packages\nfrom imutils.video import FileVideoStream\nfrom imutils.video import FPS\nimport numpy as np\nimport argparse\nimport imutils\nimport time\nimport cv2\nimport numpy as np\nimport cv2\nimport glob\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom importlib import reload\nimport utils; reload(utils)\nfrom utils import *\nimport math\nfrom caliberate import *\n\ncalibration_dir = \"camera_cal\"\ntest_imgs_dir = \"test_images\"\noutput_imgs_dir = \"output_images\"\noutput_videos_dir = \"output_videos\"\n\ndef compute_perspective_transform_matrices(src, dst):\n \"\"\"\n Returns the tuple (M, M_inv) where M represents the matrix to use for perspective transform\n and M_inv is the matrix used to revert the transformed image back to the original one\n \"\"\"\n #Calculates a perspective transform from four pairs of the corresponding points.\n M = cv2.getPerspectiveTransform(src, dst)\n \n M_inv = cv2.getPerspectiveTransform(dst, src)\n \n return (M, M_inv)\ndef compute_hls_white_yellow_binary(rgb_img):\n \"\"\"\n Returns a binary thresholded image produced retaining only white and yellow elements on the picture\n The provided image should be in RGB format\n \"\"\"\n hls_img = to_hls(rgb_img)\n \n # Compute a binary thresholded image where yellow is isolated from HLS components\n img_hls_yellow_bin = np.zeros_like(hls_img[:,:,0])\n img_hls_yellow_bin[((hls_img[:,:,0] >= 15) & (hls_img[:,:,0] <= 35))\n & ((hls_img[:,:,1] >= 30) & (hls_img[:,:,1] <= 204))\n & ((hls_img[:,:,2] >= 115) & (hls_img[:,:,2] <= 255)) \n ] = 1\n \n # Compute a binary thresholded image where white is isolated from HLS components\n img_hls_white_bin = np.zeros_like(hls_img[:,:,0])\n img_hls_white_bin[((hls_img[:,:,0] >= 0) & (hls_img[:,:,0] <= 255))\n & ((hls_img[:,:,1] >= 200) & (hls_img[:,:,1] <= 255))\n & ((hls_img[:,:,2] >= 0) & (hls_img[:,:,2] <= 255)) \n ] = 1\n \n # Now combine both\n img_hls_white_yellow_bin = np.zeros_like(hls_img[:,:,0])\n img_hls_white_yellow_bin[(img_hls_yellow_bin == 1) | (img_hls_white_bin == 1)] = 1\n\n return img_hls_white_yellow_bin\ndef dir_sobel(gray_img, kernel_size=3, thres=(0, np.pi/2)):\n \"\"\"\n Computes sobel matrix in both x and y directions, gets their absolute values to find the direction of the gradient\n and applies a threshold value to only set pixels within the specified range\n \"\"\"\n sx_abs = np.absolute(cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=kernel_size))\n sy_abs = np.absolute(cv2.Sobel(gray_img, cv2.CV_64F, 0, 1, ksize=kernel_size))\n \n dir_sxy = np.arctan2(sx_abs, sy_abs)\n\n binary_output = np.zeros_like(dir_sxy)\n binary_output[(dir_sxy >= thres[0]) & (dir_sxy <= thres[1])] = 1\n \n return binary_output\n\ndef combined_sobels(sx_binary, sy_binary, sxy_magnitude_binary, gray_img, kernel_size=3, angle_thres=(0, np.pi/2)):\n sxy_direction_binary = dir_sobel(gray_img, kernel_size=kernel_size, thres=angle_thres)\n \n combined = np.zeros_like(sxy_direction_binary)\n # Sobel X returned the best output so we keep all of its results. We perform a binary and on all the other sobels \n combined[(sx_binary == 1) | ((sy_binary == 1) & (sxy_magnitude_binary == 1) & (sxy_direction_binary == 1))] = 1\n \n return combined\n\ndef mag_sobel(gray_img, kernel_size=3, thres=(0, 255)):\n \"\"\"\n Computes sobel matrix in both x and y directions, merges them by computing the magnitude in both directions\n and applies a threshold value to only set pixels within the specified range\n \"\"\"\n sx = cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=kernel_size)\n sy = cv2.Sobel(gray_img, cv2.CV_64F, 0, 1, ksize=kernel_size)\n \n sxy = np.sqrt(np.square(sx) + np.square(sy))\n scaled_sxy = np.uint8(255 * sxy / np.max(sxy))\n \n sxy_binary = np.zeros_like(scaled_sxy)\n sxy_binary[(scaled_sxy >= thres[0]) & (scaled_sxy <= thres[1])] = 1\n \n return sxy_binary\n\ndef abs_sobel(gray_img, x_dir=True, kernel_size=3, thres=(0, 255)):\n \"\"\"\n Applies the sobel operator to a grayscale-like (i.e. single channel) image in either horizontal \n or vertical direction.\n The function also computes the asbolute value of the resulting matrix and applies a \n binary threshold\n \"\"\"\n sobel = cv2.Sobel(gray_img, cv2.CV_64F, 1, 0, ksize=kernel_size) if x_dir else cv2.Sobel(gray_img, cv2.CV_64F, 0, 1, ksize=kernel_size) \n sobel_abs = np.absolute(sobel)\n sobel_scaled = np.uint8(255 * sobel / np.max(sobel_abs))\n \n gradient_mask = np.zeros_like(sobel_scaled)\n gradient_mask[(thres[0] <= sobel_scaled) & (sobel_scaled <= thres[1])] = 1\n return gradient_mask\n\ndef get_combined_binary_thresholded_img(undist_img):\n \"\"\"\n Applies a combination of binary Sobel and color thresholding to an undistorted image\n Those binary images are then combined to produce the returned binary image\n \"\"\"\n undist_img_gray = to_lab(undist_img)[:,:,0]\n sx = abs_sobel(undist_img_gray, kernel_size=15, thres=(20, 120))\n sy = abs_sobel(undist_img_gray, x_dir=False, kernel_size=15, thres=(20, 120))\n sxy = mag_sobel(undist_img_gray, kernel_size=15, thres=(80, 200))\n sxy_combined_dir = combined_sobels(sx, sy, sxy, undist_img_gray, kernel_size=15, angle_thres=(np.pi/4, np.pi/2)) \n \n hls_w_y_thres = compute_hls_white_yellow_binary(undist_img)\n \n combined_binary = np.zeros_like(hls_w_y_thres)\n combined_binary[(sxy_combined_dir == 1) | (hls_w_y_thres == 1)] = 1\n \n return combined_binary\ndef undistort_image(img, objpts, imgpts):\n \"\"\"\n Returns an undistorted image\n The desired object and image points must also be supplied to this function\n \"\"\"\n \n '''returns the camera matrix, distortion coefficients, rotation and translation vectors etc'''\n ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpts, imgpts, to_grayscale(img).shape[::-1], None, None)\n \n undist = cv2.undistort(img, mtx, dist, None, mtx)\n return undist\n\nfrom collections import deque\n\ndef create_queue(length = 10):\n return deque(maxlen=length)\n\nclass LaneLine:\n def __init__(self):\n \n self.polynomial_coeff = None\n self.line_fit_x = None\n self.non_zero_x = []\n self.non_zero_y = []\n self.windows = []\n\nclass LaneLineHistory:\n def __init__(self, queue_depth=2, test_points=[50, 300, 500, 700], poly_max_deviation_distance=150):\n self.lane_lines = create_queue(queue_depth)\n self.smoothed_poly = None\n self.test_points = test_points\n self.poly_max_deviation_distance = poly_max_deviation_distance\n \n def append(self, lane_line, force=False):\n if len(self.lane_lines) == 0 or force:\n self.lane_lines.append(lane_line)\n self.get_smoothed_polynomial()\n return True\n \n test_y_smooth = np.asarray(list(map(lambda x: self.smoothed_poly[0] * x**2 + self.smoothed_poly[1] * x + self.smoothed_poly[2], self.test_points)))\n test_y_new = np.asarray(list(map(lambda x: lane_line.polynomial_coeff[0] * x**2 + lane_line.polynomial_coeff[1] * x + lane_line.polynomial_coeff[2], self.test_points)))\n \n dist = np.absolute(test_y_smooth - test_y_new)\n \n #dist = np.absolute(self.smoothed_poly - lane_line.polynomial_coeff)\n #dist_max = np.absolute(self.smoothed_poly * self.poly_max_deviation_distance)\n max_dist = dist[np.argmax(dist)]\n \n if max_dist > self.poly_max_deviation_distance:\n print(\"**** MAX DISTANCE BREACHED ****\")\n print(\"y_smooth={0} - y_new={1} - distance={2} - max-distance={3}\".format(test_y_smooth, test_y_new, max_dist, self.poly_max_deviation_distance))\n return False\n \n self.lane_lines.append(lane_line)\n self.get_smoothed_polynomial()\n \n return True\n \n def get_smoothed_polynomial(self):\n all_coeffs = np.asarray(list(map(lambda lane_line: lane_line.polynomial_coeff, self.lane_lines)))\n self.smoothed_poly = np.mean(all_coeffs, axis=0)\n \n return self.smoothed_poly\n \n \n\n\nclass AdvancedLaneDetectorWithMemory:\n \"\"\"\n The AdvancedLaneDetectorWithMemory is a class that can detect lines on the road\n ld = AdvancedLaneDetectorWithMemory(opts, ipts, src_pts, dst_pts, 20, 100, 50)\n used parameters:-\n slidingwindows_per_line = 20\n \n # Set the width of the windows +/- margin\n sliding_window_half_width = 100\n \n # Set minimum number of pixels found to recenter window\n sliding_window_recenter_thres = 50\n \n \n \"\"\"\n def __init__(self, objpts, imgpts, psp_src, psp_dst, sliding_windows_per_line, \n sliding_window_half_width, sliding_window_recenter_thres, \n small_img_size=(256, 144), small_img_x_offset=20, small_img_y_offset=10,\n img_dimensions=(720, 1280), lane_width_px=800, \n lane_center_px_psp=600, real_world_lane_size_meters=(32, 3.7)):\n self.objpts = objpts\n self.imgpts = imgpts\n \n (self.M_psp, self.M_inv_psp) = compute_perspective_transform_matrices(psp_src, psp_dst)\n\n self.sliding_windows_per_line = sliding_windows_per_line\n self.sliding_window_half_width = sliding_window_half_width\n self.sliding_window_recenter_thres = sliding_window_recenter_thres\n \n self.small_img_size = small_img_size\n self.small_img_x_offset = small_img_x_offset\n self.small_img_y_offset = small_img_y_offset\n \n self.img_dimensions = img_dimensions\n self.lane_width_px = lane_width_px\n self.lane_center_px_psp = lane_center_px_psp \n self.real_world_lane_size_meters = real_world_lane_size_meters\n\n # We can pre-compute some data here\n \"\"\"\n ym_per_pix = 30/720 # meters per pixel in y dimension\n # xm_per_pix = 3.7/700 # meters per pixel in x dimension\n\n # ym_per_pix = 3.0/100 # meters per pixel in y dimension, lane line is 10 ft = 3 meters\n xm_per_pix = 3.7/550 # meters per pixel in x dimension, lane width is 12 ft = 3.7 meters\n \"\"\"\n \n self.ym_per_px = self.real_world_lane_size_meters[0] / self.img_dimensions[0]\n self.xm_per_px = self.real_world_lane_size_meters[1] / self.lane_width_px\n self.ploty = np.linspace(0, self.img_dimensions[0] - 1, self.img_dimensions[0])\n \n self.previous_left_lane_line = None\n self.previous_right_lane_line = None\n \n self.previous_left_lane_lines = LaneLineHistory()\n self.previous_right_lane_lines = LaneLineHistory()\n \n self.total_img_count = 0\n \n \n def process_image(self, img):\n \"\"\"\n Attempts to find lane lines on the given image and returns an image with lane area colored in green\n as well as small intermediate images overlaid on top to understand how the algorithm is performing\n \"\"\"\n \n # First step - undistort the image using the instance's object and image points\n undist_img = undistort_image(img, self.objpts, self.imgpts)\n \n # Produce binary thresholded image from color and gradients\n thres_img = get_combined_binary_thresholded_img(undist_img)\n \n # Create the undistorted and binary perspective transforms\n img_size = (undist_img.shape[1], undist_img.shape[0])\n undist_img_psp = cv2.warpPerspective(undist_img, self.M_psp, img_size, flags=cv2.INTER_LINEAR)\n thres_img_psp = cv2.warpPerspective(thres_img, self.M_psp, img_size, flags=cv2.INTER_LINEAR)\n \n ll, rl = self.compute_lane_lines(thres_img_psp)\n lcr, rcr, lco = self.compute_lane_curvature(ll, rl)\n\n drawn_lines = self.draw_lane_lines(thres_img_psp,undist_img, ll, rl) \n \n \n drawn_lines_regions = self.draw_lane_lines_regions(thres_img_psp,undist_img, ll, rl)\n \n \n drawn_lane_area = self.draw_lane_area(thres_img_psp, undist_img, ll, rl) \n \n \n drawn_hotspots = self.draw_lines_hotspots(thres_img_psp, ll, rl)\n \n \n combined_lane_img = self.combine_images(drawn_lane_area, drawn_lines, drawn_lines_regions, drawn_hotspots, undist_img_psp)\n final_img = self.draw_lane_curvature_text(combined_lane_img, lcr, rcr, lco)\n \n \n \n \n \n self.total_img_count += 1\n self.previous_left_lane_line = ll\n self.previous_right_lane_line = rl\n \n return final_img\n \n def draw_lane_curvature_text(self, img, left_curvature_meters, right_curvature_meters, center_offset_meters):\n \"\"\"\n Returns an image with curvature information inscribed\n \"\"\"\n \n offset_y = self.small_img_size[1] * 1 + self.small_img_y_offset * 5\n offset_x = self.small_img_x_offset\n \n template = \"{0:17}{1:17}{2:17}\"\n txt_header = template.format(\"Left Curvature\", \"Right Curvature\", \"Center Alignment\") \n print(txt_header)\n txt_values = template.format(\"{:.4f}m\".format(left_curvature_meters), \n \"{:.4f}m\".format(right_curvature_meters),\n \"{:.4f}m Right\".format(center_offset_meters))\n if center_offset_meters < 0.0:\n txt_values = template.format(\"{:.4f}m\".format(left_curvature_meters), \n \"{:.4f}m\".format(right_curvature_meters),\n \"{:.4f}m Left\".format(math.fabs(center_offset_meters)))\n \n \n print(txt_values)\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(img, txt_header, (offset_x, offset_y), font, 1, (255,255,255), 1, cv2.LINE_AA)\n cv2.putText(img, txt_values, (offset_x, offset_y + self.small_img_y_offset * 5), font, 1, (255,255,255), 2, cv2.LINE_AA)\n \n return img\n \n def combine_images(self, lane_area_img, lines_img, lines_regions_img, lane_hotspots_img, psp_color_img): \n \"\"\"\n Returns a new image made up of the lane area image, and the remaining lane images are overlaid as\n small images in a row at the top of the the new image\n \"\"\"\n small_lines = cv2.resize(lines_img, self.small_img_size)\n small_region = cv2.resize(lines_regions_img, self.small_img_size)\n small_hotspots = cv2.resize(lane_hotspots_img, self.small_img_size)\n small_color_psp = cv2.resize(psp_color_img, self.small_img_size)\n \n lane_area_img[self.small_img_y_offset: self.small_img_y_offset + self.small_img_size[1], self.small_img_x_offset: self.small_img_x_offset + self.small_img_size[0]] = small_lines\n \n start_offset_y = self.small_img_y_offset \n start_offset_x = 2 * self.small_img_x_offset + self.small_img_size[0]\n lane_area_img[start_offset_y: start_offset_y + self.small_img_size[1], start_offset_x: start_offset_x + self.small_img_size[0]] = small_region\n \n start_offset_y = self.small_img_y_offset \n start_offset_x = 3 * self.small_img_x_offset + 2 * self.small_img_size[0]\n lane_area_img[start_offset_y: start_offset_y + self.small_img_size[1], start_offset_x: start_offset_x + self.small_img_size[0]] = small_hotspots\n\n start_offset_y = self.small_img_y_offset \n start_offset_x = 4 * self.small_img_x_offset + 3 * self.small_img_size[0]\n lane_area_img[start_offset_y: start_offset_y + self.small_img_size[1], start_offset_x: start_offset_x + self.small_img_size[0]] = small_color_psp\n \n \n return lane_area_img\n \n \n def draw_lane_area(self, warped_img, undist_img, left_line, right_line):\n \"\"\"\n Returns an image where the inside of the lane has been colored in bright green\n \"\"\"\n # Create an image to draw the lines on\n warp_zero = np.zeros_like(warped_img).astype(np.uint8)\n color_warp = np.dstack((warp_zero, warp_zero, warp_zero))\n\n ploty = np.linspace(0, warped_img.shape[0] - 1, warped_img.shape[0])\n # Recast the x and y points into usable format for cv2.fillPoly()\n pts_left = np.array([np.transpose(np.vstack([left_line.line_fit_x, ploty]))])\n pts_right = np.array([np.flipud(np.transpose(np.vstack([right_line.line_fit_x, ploty])))])\n pts = np.hstack((pts_left, pts_right))\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp, np.int_([pts]), (255,255, 255))\n\n # Warp the blank back to original image space using inverse perspective matrix (Minv)\n newwarp = cv2.warpPerspective(color_warp, self.M_inv_psp, (undist_img.shape[1], undist_img.shape[0])) \n # Combine the result with the original image\n result = cv2.addWeighted(undist_img, 1, newwarp, 0.3, 0)\n \n return result\n \n \n def draw_lane_lines(self, warped_img, undist_img,left_line, right_line):\n \"\"\"\n Returns an image where the computed lane lines have been drawn on top of the original warped binary image\n \"\"\"\n # Create an output image with 3 colors (RGB) from the binary warped image to draw on and visualize the result\n out_img = np.dstack((warped_img, warped_img, warped_img))*255\n \n # Now draw the lines\n ploty = np.linspace(0, warped_img.shape[0] - 1, warped_img.shape[0])\n pts_left = np.dstack((left_line.line_fit_x, ploty)).astype(np.int32)\n pts_right = np.dstack((right_line.line_fit_x, ploty)).astype(np.int32)\n\n cv2.polylines(out_img, pts_left, False, (255, 140,0), 5)\n cv2.polylines(out_img, pts_right, False, (255, 140,0), 5)\n \n for low_pt, high_pt in left_line.windows:\n cv2.rectangle(out_img, low_pt, high_pt, (0, 255, 0), 3)\n\n for low_pt, high_pt in right_line.windows: \n cv2.rectangle(out_img, low_pt, high_pt, (0, 255, 0), 3) \n # Create an image to draw the lines on\n warp_zero1 = np.zeros_like(warped_img).astype(np.uint8)\n color_warp1 = np.dstack((warp_zero1, warp_zero1, warp_zero1))\n # Warp the blank back to original image space using inverse perspective matrix (Minv\n # Draw the lane onto the warped blank image\n cv2.polylines(color_warp1, pts_left, False, (255, 140,0), 5)\n cv2.polylines(color_warp1, pts_right, False, (255, 140,0), 5)\n \n \n \n newwarp = cv2.warpPerspective(color_warp1, self.M_inv_psp, (undist_img.shape[1], undist_img.shape[0])) \n # Combine the result with the original image\n result = cv2.addWeighted(undist_img, 1, newwarp, 0.3, 0)\n plt.imsave(\"out\\warpedlines.jpg\",result)\n \n return out_img \n \n def draw_lane_lines_regions(self, warped_img,undist_img, left_line, right_line):\n \"\"\"\n Returns an image where the computed left and right lane areas have been drawn on top of the original warped binary image\n \"\"\"\n # Generate a polygon to illustrate the search window area\n # And recast the x and y points into usable format for cv2.fillPoly()\n margin = self.sliding_window_half_width\n ploty = np.linspace(0, warped_img.shape[0] - 1, warped_img.shape[0])\n \n left_line_window1 = np.array([np.transpose(np.vstack([left_line.line_fit_x - margin, ploty]))])\n left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_line.line_fit_x + margin, \n ploty])))])\n left_line_pts = np.hstack((left_line_window1, left_line_window2))\n \n right_line_window1 = np.array([np.transpose(np.vstack([right_line.line_fit_x - margin, ploty]))])\n right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_line.line_fit_x + margin, \n ploty])))])\n right_line_pts = np.hstack((right_line_window1, right_line_window2))\n\n # Create RGB image from binary warped image\n region_img = np.dstack((warped_img, warped_img, warped_img)) * 255\n\n # Draw the lane onto the warped blank image\n cv2.fillPoly(region_img, np.int_([left_line_pts]), (0, 255, 0))\n cv2.fillPoly(region_img, np.int_([right_line_pts]), (0, 255, 0))\n \n # Create an image to draw the lines on\n warp_zero1 = np.zeros_like(warped_img).astype(np.uint8)\n color_warp1 = np.dstack((warp_zero1, warp_zero1, warp_zero1))\n # Warp the blank back to original image space using inverse perspective matrix (Minv\n # Draw the lane onto the warped blank image\n cv2.fillPoly(color_warp1, np.int_([left_line_pts]), (0, 255, 0))\n cv2.fillPoly(color_warp1, np.int_([right_line_pts]), (0, 255, 0))\n \n newwarp = cv2.warpPerspective(color_warp1, self.M_inv_psp, (undist_img.shape[1], undist_img.shape[0])) \n # Combine the result with the original image\n result = cv2.addWeighted(undist_img, 1, newwarp, 0.3, 0)\n plt.imsave(\"out\\warpedregion.jpg\",result)\n return region_img\n\n\n def draw_lines_hotspots(self, warped_img, left_line, right_line):\n \"\"\"\n Returns a RGB image where the portions of the lane lines that were\n identified by our pipeline are colored in yellow (left) and blue (right)\n \"\"\"\n out_img = np.dstack((warped_img, warped_img, warped_img))*255\n \n out_img[left_line.non_zero_y, left_line.non_zero_x] = [255, 255, 0]\n out_img[right_line.non_zero_y, right_line.non_zero_x] = [0, 0, 255]\n \n return out_img\n\n def compute_lane_curvature(self, left_line, right_line):\n \"\"\"\n Returns the triple (left_curvature, right_curvature, lane_center_offset), which are all in meters\n \"\"\" \n ploty = self.ploty\n y_eval = np.max(ploty)\n # Define conversions in x and y from pixels space to meters\n \n leftx = left_line.line_fit_x\n rightx = right_line.line_fit_x\n \n # Fit new polynomials: find x for y in real-world space\n left_fit_cr = np.polyfit(ploty * self.ym_per_px, leftx * self.xm_per_px, 2)\n right_fit_cr = np.polyfit(ploty * self.ym_per_px, rightx * self.xm_per_px, 2)\n \n # Now calculate the radii of the curvature\n left_curverad = ((1 + (2 * left_fit_cr[0] * y_eval * self.ym_per_px + left_fit_cr[1])**2)**1.5) / np.absolute(2 * left_fit_cr[0])\n right_curverad = ((1 + (2 *right_fit_cr[0] * y_eval * self.ym_per_px + right_fit_cr[1])**2)**1.5) / np.absolute(2 * right_fit_cr[0])\n \n # Use our computed polynomial to determine the car's center position in image space, then\n left_fit = left_line.polynomial_coeff\n right_fit = right_line.polynomial_coeff\n \n center_offset_img_space = (((left_fit[0] * y_eval**2 + left_fit[1] * y_eval + left_fit[2]) + \n (right_fit[0] * y_eval**2 + right_fit[1] * y_eval + right_fit[2])) / 2) - self.lane_center_px_psp\n center_offset_real_world_m = center_offset_img_space * self.xm_per_px\n \n # Now our radius of curvature is in meters \n return left_curverad, right_curverad, center_offset_real_world_m\n \n \n \n def compute_lane_lines(self, warped_img):\n \"\"\"\n Returns the tuple (left_lane_line, right_lane_line) which represents respectively the LaneLine\n instances for the computed left and right lanes, for the supplied binary warped image\n \"\"\"\n\n # Take a histogram of the bottom half of the image, summing pixel values column wise \n histogram = np.sum(warped_img[warped_img.shape[0]//3:,:], axis=0)\n \n \n # Find the peak of the left and right halves of the histogram\n # These will be the starting point for the left and right lines \n midpoint = np.int(histogram.shape[0]//3)\n leftx_base = np.argmax(histogram[:midpoint])\n rightx_base = np.argmax(histogram[midpoint:]) + midpoint # don't forget to offset by midpoint!\n \n\n # Set height of windows\n window_height = np.int(warped_img.shape[0]//self.sliding_windows_per_line)\n # Identify the x and y positions of all nonzero pixels in the image\n # NOTE: nonzero returns a tuple of arrays in y and x directions\n nonzero = warped_img.nonzero()\n nonzeroy = np.array(nonzero[0])\n nonzerox = np.array(nonzero[1])\n \n total_non_zeros = len(nonzeroy)\n non_zero_found_pct = 0.0\n \n # Current positions to be updated for each window\n leftx_current = leftx_base\n rightx_current = rightx_base \n\n\n # Set the width of the windows +/- margin\n margin = self.sliding_window_half_width\n # Set minimum number of pixels found to recenter window\n minpix = self.sliding_window_recenter_thres\n # Create empty lists to receive left and right lane pixel indices\n left_lane_inds = []\n right_lane_inds = []\n \n # Our lane line objects we store the result of this computation\n left_line = LaneLine()\n right_line = LaneLine()\n \n if self.previous_left_lane_line is not None and self.previous_right_lane_line is not None:\n # We have already computed the lane lines polynomials from a previous image\n left_lane_inds = ((nonzerox > (self.previous_left_lane_line.polynomial_coeff[0] * (nonzeroy**2) \n + self.previous_left_lane_line.polynomial_coeff[1] * nonzeroy \n + self.previous_left_lane_line.polynomial_coeff[2] - margin)) \n & (nonzerox < (self.previous_left_lane_line.polynomial_coeff[0] * (nonzeroy**2) \n + self.previous_left_lane_line.polynomial_coeff[1] * nonzeroy \n + self.previous_left_lane_line.polynomial_coeff[2] + margin))) \n\n right_lane_inds = ((nonzerox > (self.previous_right_lane_line.polynomial_coeff[0] * (nonzeroy**2) \n + self.previous_right_lane_line.polynomial_coeff[1] * nonzeroy \n + self.previous_right_lane_line.polynomial_coeff[2] - margin)) \n & (nonzerox < (self.previous_right_lane_line.polynomial_coeff[0] * (nonzeroy**2) \n + self.previous_right_lane_line.polynomial_coeff[1] * nonzeroy \n + self.previous_right_lane_line.polynomial_coeff[2] + margin))) \n \n non_zero_found_left = np.sum(left_lane_inds)\n non_zero_found_right = np.sum(right_lane_inds)\n non_zero_found_pct = (non_zero_found_left + non_zero_found_right) / total_non_zeros\n \n print(\"[Previous lane] Found pct={0}\".format(non_zero_found_pct))\n #print(left_lane_inds)\n \n if non_zero_found_pct < 0.85:\n print(\"Non zeros found below thresholds, begining sliding window - pct={0}\".format(non_zero_found_pct))\n left_lane_inds = []\n right_lane_inds = []\n\n # Step through the windows one by one\n for window in range(self.sliding_windows_per_line):\n # Identify window boundaries in x and y (and right and left)\n # We are moving our windows from the bottom to the top of the screen (highest to lowest y value)\n win_y_low = warped_img.shape[0] - (window + 1)* window_height\n win_y_high = warped_img.shape[0] - window * window_height\n\n # Defining our window's coverage in the horizontal (i.e. x) direction \n # Notice that the window's width is twice the margin\n win_xleft_low = leftx_current - margin\n win_xleft_high = leftx_current + margin\n win_xright_low = rightx_current - margin\n win_xright_high = rightx_current + margin\n\n left_line.windows.append([(win_xleft_low,win_y_low),(win_xleft_high,win_y_high)])\n right_line.windows.append([(win_xright_low,win_y_low),(win_xright_high,win_y_high)])\n\n # Super crytic and hard to understand...\n # Basically nonzerox and nonzeroy have the same size and any nonzero pixel is identified by\n # (nonzeroy[i],nonzerox[i]), therefore we just return the i indices within the window that are nonzero\n # and can then index into nonzeroy and nonzerox to find the ACTUAL pixel coordinates that are not zero\n good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]\n good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & \n (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]\n \n # Append these indices to the lists\n left_lane_inds.append(good_left_inds)\n right_lane_inds.append(good_right_inds)\n\n # If you found > minpix pixels, recenter next window on their mean position\n if len(good_left_inds) > minpix:\n leftx_current = np.int(np.mean(nonzerox[good_left_inds]))\n if len(good_right_inds) > minpix: \n rightx_current = np.int(np.mean(nonzerox[good_right_inds]))\n\n # Concatenate the arrays of indices since we now have a list of multiple arrays (e.g. ([1,3,6],[8,5,2]))\n # We want to create a single array with elements from all those lists (e.g. [1,3,6,8,5,2])\n # These are the indices that are non zero in our sliding windows\n left_lane_inds = np.concatenate(left_lane_inds)\n right_lane_inds = np.concatenate(right_lane_inds)\n \n non_zero_found_left = np.sum(left_lane_inds)\n non_zero_found_right = np.sum(right_lane_inds)\n non_zero_found_pct = (non_zero_found_left + non_zero_found_right) / total_non_zeros\n \n print(\"[Sliding windows] Found pct={0}\".format(non_zero_found_pct))\n \n \n # Extract left and right line pixel positions\n leftx = nonzerox[left_lane_inds]\n lefty = nonzeroy[left_lane_inds] \n rightx = nonzerox[right_lane_inds]\n righty = nonzeroy[right_lane_inds] \n \n #print(\"[LEFT] Number of hot pixels={0}\".format(len(leftx)))\n #print(\"[RIGHT] Number of hot pixels={0}\".format(len(rightx)))\n # Fit a second order polynomial to each\n left_fit = np.polyfit(lefty, leftx, 2)\n right_fit = np.polyfit(righty, rightx, 2)\n #print(\"Poly left {0}\".format(left_fit))\n #print(\"Poly right {0}\".format(right_fit))\n left_line.polynomial_coeff = left_fit\n right_line.polynomial_coeff = right_fit\n \n if not self.previous_left_lane_lines.append(left_line):\n left_fit = self.previous_left_lane_lines.get_smoothed_polynomial()\n left_line.polynomial_coeff = left_fit\n self.previous_left_lane_lines.append(left_line, force=True)\n print(\"**** REVISED Poly left {0}\".format(left_fit)) \n #else:\n #left_fit = self.previous_left_lane_lines.get_smoothed_polynomial()\n #left_line.polynomial_coeff = left_fit\n\n\n if not self.previous_right_lane_lines.append(right_line):\n right_fit = self.previous_right_lane_lines.get_smoothed_polynomial()\n right_line.polynomial_coeff = right_fit\n self.previous_right_lane_lines.append(right_line, force=True)\n print(\"**** REVISED Poly right {0}\".format(right_fit))\n #else:\n #right_fit = self.previous_right_lane_lines.get_smoothed_polynomial()\n #right_line.polynomial_coeff = right_fit\n\n\n \n # Generate x and y values for plotting\n ploty = np.linspace(0, warped_img.shape[0] - 1, warped_img.shape[0] )\n left_fitx = left_fit[0] * ploty**2 + left_fit[1] * ploty + left_fit[2]\n right_fitx = right_fit[0] * ploty**2 + right_fit[1] * ploty + right_fit[2]\n \n \n left_line.polynomial_coeff = left_fit\n left_line.line_fit_x = left_fitx\n left_line.non_zero_x = leftx \n left_line.non_zero_y = lefty\n\n right_line.polynomial_coeff = right_fit\n right_line.line_fit_x = right_fitx\n right_line.non_zero_x = rightx\n right_line.non_zero_y = righty\n\n\n \n return (left_line, right_line)\n \n \n\n# construct the argument parse and parse the arguments\n\n(bottom_px, right_px) = (719, 1279) \n# pts = np.array([[0,bottom_px],[0,bottom_px/3],[right_px,bottom_px/3], [right_px, bottom_px]], np.int32) LVT\n# pts = np.array([[170,bottom_px],[550,530],[740,530], [870, bottom_px]], np.int32) NVT5\n#pts = np.array([[170,bottom_px],[550,530],[740,530], [870, bottom_px]], np.int32) NVT1 without resize\npts = np.array([[100,bottom_px],[225,180],[310,180], [360, bottom_px]], np.int32)\n\nsrc_pts = pts.astype(np.float32)\n\ndst_pts = np.array([[200, bottom_px], [200, 0], [1000, 0], [1000, bottom_px]], np.float32)\n'''\nld = AdvancedLaneDetectorWithMemory(opts, ipts, src_pts, dst_pts, 20, 100, 50)\n\nfrom tkinter.ttk import *\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom PIL import Image,ImageTk \nimport os\n\npath1 = \"extract\"\npath2 = \"extractout\"\ntest_imgs_paths = glob.glob(path1 + \"/*.jpg\") \nfor image in test_imgs_paths:\n img = load_image(image)\n print(\"Processing \"+image)\n img= ld.process_image(img)\n c = 0\n plt.imsave(\"extractout/\"+str(c)+\".jpg\",img) \n c = c+1\n'''\nfrom tkinter.ttk import *\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom PIL import Image,ImageTk \nfrom imageio import *\nfrom tkinter.filedialog import askopenfilename\nfrom imutils.video import FPS\nfrom imutils.video import FileVideoStream\nimport time\nimport imutils\n\n\n\n\n\n\ndef inputImg():\n global panelA\n \n file = filedialog.askopenfilename()\n \n image = load_image(file)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n ld = AdvancedLaneDetectorWithMemory(opts, ipts, src_pts, dst_pts, 20, 100, 50)\n proc_img = ld.process_image(image)\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n \n v.set(\"Image Selected\")\ndef undistort():\n \n global panelA\n\n \n image = load_image(\"out/undist_img.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n v.set(\"Undistorted Output ===>\") \ndef threshold():\n \n global panelA\n\n \n image = load_image(\"out/thres_img.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n v.set(\"Thresholded Output ===>\") \ndef transform():\n \n global panelA\n\n \n image = load_image(\"out/thres_img_psp.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n v.set(\"Transformed Output ===>\") \ndef linefit():\n \n global panelA\n\n \n image = load_image(\"out/drawn_lines.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n v.set(\"Line Fitted Output ===>\") \n \ndef regionmark():\n \n global panelA\n\n \n image = load_image(\"out/drawn_lines_regions.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n v.set(\"Region Marked Output ===>\") \ndef regionimg():\n \n global panelA\n\n \n image = load_image(\"out/warpedregion.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n \n v.set(\"Lane line Region Drawn ===>\") \n\ndef finaloutput():\n \n global panelA\n\n \n image = load_image(\"out/drawn_lane_area.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n \n v.set(\"Final Output ===>\") \n \ndef linedrawn():\n \n global panelA\n\n \n image = load_image(\"out/warpedlines.jpg\")\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=500,anchor=W,height=540,width=780)\n else:\n panelA.configure(image=image)\n panelA.image = image\n \n v.set(\"Lane Lines Drawn ===>\") \n \ndef combinedoutput():\n \n global panelA\n\n \n image = load_image(\"out/final_img.jpg\")\n scale_percent = 70 # percent of original size\n width = int(image.shape[1] * scale_percent / 100)\n height = int(image.shape[0] * scale_percent / 100)\n dim = (width, height)\n # resize image\n image = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)\n image = Image.fromarray(image)\n image = ImageTk.PhotoImage(image)\n if panelA is None :\n panelA = Label(image=image)\n panelA.image = image\n panelA.place(x=500,y=450,anchor=W,height=510,width=720)\n else:\n panelA.configure(image=image)\n panelA.image = image\n v.set(\" \")\ndef vplay():\n stream = askopenfilename()\n ld = AdvancedLaneDetectorWithMemory(opts, ipts, src_pts, dst_pts, 20, 100, 50)\n # import the necessary packages\n\n print(\"[INFO] starting video file thread...\")\n fvs = FileVideoStream(stream).start()\n time.sleep(1.0)\n\n # start the FPS timer\n fps = FPS().start()\n\n # loop over frames from the video file stream\n while fvs.more():\n # grab the frame from the threaded video file stream, resize\n # it, and convert it to grayscale (while still retaining 3\n # channels)\n frame = fvs.read()\n print(frame.shape)\n \n \n \n frame = ld.process_image(frame)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n #frame = np.dstack([frame])\n frame = np.dstack([frame, frame, frame])\n # display the size of the queue on the frame\n \n # show the frame and update the FPS counter\n print(frame.shape)\n cv2.imshow(\"Frame\", frame)\n cv2.waitKey(1)\n fps.update()\n\n # stop the timer and display FPS information\n fps.stop()\n print(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\n print(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n\n # do a bit of cleanup\n cv2.destroyAllWindows()\n fvs.stop()\n \n\nwindow = Tk()\nwindow.geometry('1050x1200')\npanelA=None\n\nwindow.configure(background='black')\nwindow.title(\"Road-lane Detection Software\")\nv = StringVar()\nlbl = Label(window, text=\"Road-lane Detection Software \",font=(\"Times New Roman\",25,\"bold\"),fg=\"white\",bg=\"black\")\nlbl.place(x=700,y=30,anchor=N)\nlbl1 = Label(window, text=\" \",font=(\"Times New Roman\",18,\"italic\"),fg=\"red\",bg=\"black\",textvariable=v)\nlbl1.place(x=380,y=130,anchor=N)\n\nb1 = Button(window, text=\"Select Image\", bg=\"grey\", fg=\"cyan\",activebackground=\"red\",font=(\"Times New Roman\",15),command=inputImg)\nb1.place(y=60,x=20,anchor=W,height=60,width=170)\nb2 = Button(window, text=\"Undistortion\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=undistort)\nb2.place(x=20,y=130,anchor=W,height=60,width=170)\n\nb3 = Button(window, text=\"Thresholding\", bg=\"grey\",activebackground=\"red\", fg=\"cyan\",font=(\"Times New Roman\",15),command=threshold)\nb3.place(y=200,x=20,anchor=W,height=60,width=170)\nb4 = Button(window, text=\"Perspective \\n Transformation\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=transform)\nb4.place(x=20,y=270,anchor=W,height=60,width=170)\n\nb5 = Button(window, text=\"Line Fitting\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=linefit)\nb5.place(y=340,x=20,anchor=W,height=60,width=170)\nb8 = Button(window, text=\"Line Drawn \\n Result\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=linedrawn)\nb8.place(x=20,y=410,anchor=W,height=60,width=170)\nb6 = Button(window, text=\"Region Marking\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=regionmark)\nb6.place(x=20,y=480,anchor=W,height=60,width=170)\nb9 = Button(window, text=\"Region Marked \\n Result\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=regionimg)\nb9.place(x=20,y=550,anchor=W,height=60,width=170)\nb7 = Button(window, text=\"Final Output\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=finaloutput)\nb7.place(x=20,y=620,anchor=W,height=60,width=170)\n\nb10 = Button(window, text=\"Combined \\n Output\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=combinedoutput)\nb10.place(x=20,y=690,anchor=W,height=60,width=170)\nb11 = Button(window, text=\"Video \\n Outputs\", bg=\"grey\", fg=\"cyan\",font=(\"Times New Roman\",15),command=vplay)\nb11.place(x=210,y=690,anchor=W,height=60,width=170)\nwindow.mainloop()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'''\n\ndef inputImg():\n\tglobal panelA\n \n\ttest_imgs_paths = glob.glob(test_imgs_dir + \"/*.jpg\")\n\tfor img in test_imgs_paths :\n\t\timage = load_image(img)\n\t\timage = Image.fromarray(image)\n\t\timage = ImageTk.PhotoImage(image)\n\t\tpanelA = Label(image=image)\n\t\tpanelA.image = image\n\t\tpanelA.place(x=500,y=500,anchor=W,height=540,width=780)\n\t\t\n \n\nwindow = Tk()\nwindow.geometry('1050x1200')\npanelA=None\n\nwindow.configure(background='black')\nwindow.title(\"Road-lane Detection Software\")\nv = StringVar()\nlbl = Label(window, text=\"Road-lane Detection Software \",font=(\"Times New Roman\",25,\"bold\"),fg=\"white\",bg=\"black\")\nlbl.place(x=700,y=30,anchor=N)\n\nb1 = Button(window, text=\"Do\", bg=\"grey\", fg=\"cyan\",activebackground=\"red\",font=(\"Times New Roman\",15),command=inputImg)\nb1.place(y=60,x=20,anchor=W,height=60,width=170)\nwindow.mainloop()'''\n","sub_path":"videorun.py","file_name":"videorun.py","file_ext":"py","file_size_in_byte":43696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"51538864","text":"import logging\nimport colorama\n\ncolorama.init()\n\nlogger = logging.getLogger(__name__)\nch = logging.StreamHandler()\nch.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\n\nfrom describe_dsl.dsl import *\n\n__author__ = \"Hiroshi Ioka\"\n__copyright__ = \"Copyright 2012, Hiroshi Ioka\"\n__credits__ = []\n__license__ = \"MIT\"\n__version__ = \"0.1.0\"\n__maintainer__ = \"Hiroshi Ioka\"\n__email__ = \"hirochachacha@gmail.com\"\n__status__ = \"Production\"\n","sub_path":"describe_dsl/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"589489959","text":"import gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk, GObject\n\nimport os, sys\nimport time, datetime\n\nclass Window(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self, title=\"GTK3.0 Example\")\n self.set_default_size(400,360)\n\n st = os.statvfs(\"/\")\n self.total = (st.f_blocks * st.f_frsize)/1024/1024/1024\n self.used = ((st.f_blocks - st.f_bfree) * st.f_frsize)/1024/1024/1024\n self.free = (st.f_bavail * st.f_frsize)/1024/1024/1024\n self.usage = self.used/self.total\n\n vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)\n vbox.set_valign(Gtk.Align.START)\n\n # total (GB)\n label = Gtk.Label(\"Disk Total\")\n vbox.pack_start(label, True, True, 8)\n entry = Gtk.Entry()\n entry.set_text(str(self.total)[0:5] + \" GB\")\n vbox.pack_start(entry, True, True, 0)\n\n # used (GB)\n label = Gtk.Label(\"Used Space\")\n vbox.pack_start(label, True, True, 8)\n entry = Gtk.Entry()\n entry.set_text(str(self.used)[0:5] + \" GB\")\n vbox.pack_start(entry, True, True, 0)\n\n # free (GB)\n label = Gtk.Label(\"Free Space\")\n vbox.pack_start(label, True, True, 8)\n entry = Gtk.Entry()\n entry.set_text(str(self.free)[0:5] + \" GB\")\n vbox.pack_start(entry, True, True, 0)\n\n # usage (%)\n label = Gtk.Label(\"Disk Usage (\" + str(self.usage*100)[0:4] + \" %) Used\")\n vbox.pack_start(label, True, True, 4)\n pbar = Gtk.ProgressBar()\n pbar.set_fraction(self.usage)\n vbox.pack_start(pbar, True, True, 16)\n\n frm = Gtk.Frame()\n frm.set_border_width(16)\n frm.add(vbox)\n frm.set_label(\"SYSTEM STATUS\")\n self.add(frm)\n\n self.connect(\"delete-event\", Gtk.main_quit)\n # self.fullscreen()\n self.show_all()\n Gtk.main()\n\nif __name__ == '__main__':\n win = Window()","sub_path":"0004-gtk3.0-simple-system-status/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"447440444","text":"# Copyright © 2017-2018 Cedric Legrand\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice (including the next\n# paragraph) shall be included in all copies or substantial portions of the\n# Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nclass Failure(Exception):\n def __init__(self, severity, pos, msg):\n self.severity = severity\n self.pos = pos\n self.msg = msg\n\n def __str__(self): return str(self.linecol[0]) + ':' + str(self.linecol[1]) + ': ' + self.msg\n\nclass ParseError(Exception):\n class Severity:\n Warning = 1\n Error = 2\n Fatal = 3\n\n def __init__(self, failures, parser = None):\n self.failures = failures\n self.max_level = -1\n self.errors = 0\n self.warnings = 0\n if parser is not None:\n for f in failures:\n if f.severity > self.max_level: self.max_level = f.severity\n if f.severity is ParseError.Severity.Warning: self.warnings += 1\n else: self.errors += 1\n f.linecol = parser.pos_to_linecol(f.pos)\n\n @property\n def summary(self):\n if self.warnings is 0: return 'build finished with %d errors' % self.errors\n elif self.errors is 0: return 'build finished with %d warnings' % self.warnings\n else: return 'build finished with %d errors and %d warnings' % (self.errors, self.warnings)\n\n def __str__(self):\n res = []\n for f in self.failures:\n res.append(str(f))\n return '\\n'.join(res) + '\\n'\n","sub_path":"reflex/parser/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"347836369","text":"# Import required libraries\nimport pandas as pd\nimport dash\nfrom dash import html\nfrom dash import dcc\nfrom dash.dependencies import Input, Output\nimport plotly.express as px\n\n# Read the airline data into pandas dataframe\nspacex_df = pd.read_csv(\"spacex_launch_dash.csv\")\nspacex_df.drop(columns=['Unnamed: 0', 'Mission Outcome'], inplace=True)\nmax_payload = spacex_df['Payload Mass (kg)'].max()\nmin_payload = spacex_df['Payload Mass (kg)'].min()\n\n# Get unique launch sites for drop down menu \nunique_launch_sites = spacex_df['Launch Site'].unique().tolist()\nlaunch_sites = []\nlaunch_sites.append({'label': 'All Sites', 'value': 'All Sites'})\nfor launch_site in unique_launch_sites:\n launch_sites.append({'label': launch_site, 'value': launch_site})\n\n# Create a dash application\napp = dash.Dash(__name__)\n\n# Create an app layout\napp.layout = html.Div(children=[# Header \n html.H1('SpaceX Launch Records Dashboard',\n style={'textAlign': 'center', 'color': '#503D36','font-size': 40}),\n html.Br(),\n\n # TASK 1: Add a dropdown list to enable Launch Site selection\n # ->Set default select value as 'ALL sites'\n html.Div(dcc.Dropdown(\n id='site-dropdown',\n options=launch_sites,\n value='All Sites',\n placeholder='Select a launch site here',\n searchable=True,\n clearable=True)\n ),\n html.Br(),\n\n # TASK 2: Add a pie chart to show the total successful launches count for all sites\n html.Div(dcc.Graph(id='success-pie-chart')),\n html.Br(),\n\n # TASK 3: Add a slider to select payload range\n # -> Set default value to be max & min payload \n html.P(\"Payload range (Kg):\"),\n html.Div(dcc.RangeSlider(id='payload-slider', \n min=0, max=10000, step=1000,\n value=[min_payload,max_payload],\n marks={\n 0:{'label':'0 (min)', 'style':{'font-size':15, 'font-weight':'bold'}},\n 2500:'2500',\n 5000:'5000',\n 7500:'7500',\n 9600: {'label':'9600 (max)', 'style':{'font-size':15, 'font-weight':'bold'}},\n 10000:'1000'\n })\n ),\n html.Div(id='retun-payload-range'),\n html.Br(),\n\n # TASK 4: Add a scatter chart to show the correlation between payload and launch success\n html.Div(dcc.Graph(id='success-payload-scatter-chart')),\n ])\n\n# TASK 2:\n# Add a callback function to output a pie chart in response to drop down selection\n@app.callback(\n Output(component_id='success-pie-chart', component_property='figure'),\n Input(component_id='site-dropdown', component_property='value')\n )\ndef output_pie(site): #input value \n if (site =='All Sites'):\n all_sites = spacex_df[spacex_df['class'] == 1].reset_index(drop=True) # All Success only for all sites.\n all_sites.rename(columns={'class': 'count'}, inplace=True)\n fig = px.pie(\n all_sites, \n values='count', \n names='Launch Site', \n title='Total Success Launches by Site',\n color_discrete_sequence=px.colors.sequential.RdBu\n )\n else:\n selected_site = spacex_df[spacex_df['Launch Site']==site].reset_index(drop=True)\n site_sucessRate = selected_site.groupby(['Launch Site', 'class']).size().reset_index()\n site_sucessRate.rename(columns={0:'count'}, inplace=True)\n site_sucessRate.replace([0,1],['Fail', 'Successs'], inplace=True)\n fig = px.pie(\n site_sucessRate, \n values='count', \n names='class', \n title='Total Success Launches for site '+site,\n )\n return fig \n\n# TASK 3:\n# Add a callback function that returns the selected pay load range\n@app.callback(\n Output('retun-payload-range', 'children'),\n Input('payload-slider', 'value'))\ndef output_payload_range(payload_range):\n return 'You have selected range {}'.format(payload_range)\n\n# TASK 4:\n# Add a callback function to output a scatter plot in response payload range\n@app.callback(\n Output('success-payload-scatter-chart', 'figure'),\n [Input('site-dropdown', 'value'), Input('payload-slider', 'value')]) #multiple inputs\ndef output_scatter(site, payload_range):\n low,high = payload_range\n df = spacex_df\n filtered_df = df[df['Payload Mass (kg)'].between(low,high)]\n\n if site =='All Sites':\n fig = px.scatter(filtered_df, \n x='Payload Mass (kg)', \n y='class', \n size='Payload Mass (kg)',\n color='Booster Version Category', \n title='Success Rate for All Sites by Payload Range')\n else:\n filtered_df = filtered_df[filtered_df['Launch Site']==site]\n fig = px.scatter(filtered_df, \n x='Payload Mass (kg)', \n y='class', \n size='Payload Mass (kg)',\n color='Booster Version Category', \n title='Success Rate for Site {} by Payload Range'.format(site))\n return fig\n\n# Run the app\nif __name__ == '__main__':\n app.run_server(debug=True)","sub_path":"Applied capstone/spacex_dash_app.py","file_name":"spacex_dash_app.py","file_ext":"py","file_size_in_byte":6430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"527980629","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport rospy\nimport math\n\nfrom visualization_msgs.msg import Marker\nfrom geometry_msgs.msg import Point\n\ndef create_marker_msg():\n m = Marker()\n m.header.frame_id = 'world'\n m.ns = 'trajectory'\n m.type = m.LINE_STRIP\n m.action = m.ADD\n m.id = 0\n\n # line width\n m.scale.x = 0.02\n\n # line color\n m.color.a = 1.0\n m.color.r = 1.0\n m.color.g = 1.0\n m.color.b = 0.0\n\n # trajectory\n z = 0.55\n L = 1.0\n mu = 0.1\n\n N = 1000\n t = np.linspace(0.0, 100.0, N)\n #'8'\n L=1\n mu=0.1\n for i in range(N):\n ref_x = L*math.cos(mu*t[i])\n ref_y = 2*L*math.sin(mu*t[i])*math.cos(mu*t[i])\n m.points.append(Point(ref_x, ref_y, z))\n\n return m\n\n # #sinusoid\n # for i in range(N):\n # ref_x = 0.05*t[i]\n # ref_y = 0.5*math.sin(5*ref_x)\n\n # m.points.append(Point(ref_x, ref_y, z))\n\n # return m\n\n #straight line\n # L=1\n # mu=0.1\n # for i in range(N):\n # ref_x = 0.1*t[i]\n # ref_y = 0.2*t[i]\n # m.points.append(Point(ref_x, ref_y, z))\n\n # return m\n\n\ndef main():\n rospy.init_node('reference_traj_publiser', anonymous=True)\n rate = rospy.Rate(10) # 10hz\n pub_traj_viz = rospy.Publisher(\n '/visualization/trajectory',\n Marker, \n queue_size=1\n )\n\n traj_marker = create_marker_msg()\n \n while not rospy.is_shutdown():\n traj_marker.header.stamp = rospy.Time.now()\n pub_traj_viz.publish(traj_marker)\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/reference_trajectory_publisher.py","file_name":"reference_trajectory_publisher.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"193355944","text":"import sys\nimport json\nfrom pyspark import SparkContext\nfrom pyspark.sql import SQLContext\nsc = SparkContext()\nsqlContext = SQLContext(sc)\n\n\norders = sqlContext.read.format(\"csv\")\\\n .option(\"header\",\"true\")\\\n .option(\"inferSchema\", \"true\")\\\n .load(\"instacart_2017_05_01/orders.csv\")\n\nproducts = sqlContext.read.format(\"csv\")\\\n .option(\"header\",\"true\")\\\n .option(\"inferSchema\", \"true\")\\\n .load(\"instacart_2017_05_01/products.csv\")\n \naisles = sqlContext.read.format(\"csv\")\\\n .option(\"header\",\"true\")\\\n .option(\"inferSchema\", \"true\")\\\n .load(\"instacart_2017_05_01/aisles.csv\")\n\ndepartments = sqlContext.read.format(\"csv\")\\\n .option(\"header\",\"true\")\\\n .option(\"inferSchema\", \"true\")\\\n .load(\"instacart_2017_05_01/departments.csv\")\n \norder_products__train = sqlContext.read.format(\"csv\")\\\n .option(\"header\",\"true\")\\\n .option(\"inferSchema\", \"true\")\\\n .load(\"instacart_2017_05_01/order_products__train.csv\")\n\n\n\norder_products__prior = sqlContext.read.format(\"csv\")\\\n .option(\"header\",\"true\")\\\n .option(\"inferSchema\", \"true\")\\\n .load(\"instacart_2017_05_01/order_products__prior.csv\")\n\n#order_products = order_products__prior.union(order_products__train)\n#\n#order_products = order_products.select(\"order_id\",\"product_id\")\n#\n#\n#\norder_products__prior1 = order_products__prior.selectExpr(\"product_id\",\"order_id as order_id_1\")\nproducts_FP = order_products__prior1.join(orders, order_products__prior1.order_id_1 == orders.order_id)\n\nproducts_FP.select(\"product_id\",\"order_id\",\"user_id\")\n#products_FP.show()\n\nimport pyspark.sql.functions as F\n\n\n\ntransactions = products_FP.groupby(\"order_id\").agg(F.collect_list('product_id'))\ntransactions = products_FP.selectExpr(\"collect_list(product_id) as items\").take(100)\n\n\n#trans = transactions.select(\"items\").take(20)\n#trans = trans.collect()\n#a = [(item) for sublist in trans for item in sublist]\n#a = sc.parallelize(a)\n#model = FPGrowth.train(a, minSupport=0.2, numPartitions=10)\n#result = model.freqItemsets().collect()\n\n#for fi in result:\n# print(fi)\n\nfrom pyspark.mllib.fpm import FPGrowth\n\nmodel = FPGrowth.train(transactions, minSupport=0.8, numPartitions=5)\nresult = model.freqItemsets().collect()\n\n#fpGrowth = FPGrowth.train(transactions, minSupport=0.1, minConfidence=0.6)\n#model = fpGrowth.fit(transactions)\n\n#model.associationRules.show(1)\n#model.freqItemsets.show(1)\n\n\n\n# transform examines the input items against all the association rules and summarize the\n# consequents as prediction\n#model.transform(transactions).show(10)\n\n\n\n\n\n\n#import pyspark.ml.stat\n#icecream = orders.join(order_products, orders.order_id == order_products.order_id)\n#icecream = icecream.select(\"order_hour_of_day\",\"product_id\")\n#icecream = icecream.join(products, icecream.product_id == products.product_id)\n#icecream = icecream.select(\"order_hour_of_day\",\"product_name\").show()\n##icecream = icecream.filter(icecream.product_name==\"Ice cream\").show()\n#from pyspark.sql.functions import col,desc\n#from pyspark.ml.stat import ChiSquareTest\n#alcohol = departments.join(products, departments.department_id == products.department_id)\n#alcohol = alcohol.select(\"product_id\",\"department\")\n#alcohol = alcohol.join(order_products, alcohol.product_id == order_products.product_id)\n#alcohol = alcohol.select(\"department\", \"order_id\")\n#alcohol = alcohol.join(orders, alcohol.order_id == orders.order_id)\n#alcohol = alcohol.select(\"order_dow\",\"order_hour_of_day\",\"department\")\n#alcohol = alcohol.filter(alcohol.department==\"alcohol\")\n#alcDail = alcohol.groupby(\"order_dow\").count().sort(desc(\"order_dow\"))\n#alcWeek = alcohol.groupby(\"order_hour_of_day\").count().sort(desc(\"order_hour_of_day\"))\n##r = ChiSquareTest.test(alcohol, \"order_dow\", \"count\")\n##print(r.pValues)\n##print(r.degreesOfFreedom)\n##print(r.statistics)\n#\n#alcohol = alcohol.filter(alcohol.department==\"alcohol\")\n#morningAlc = alcohol.select(\"order_hour_of_day\").filter(alcohol.order_hour_of_day>8).filter(alcohol.order_hour_of_day<17)\\\n#.where(alcohol.order_hour_of_day.isNotNull())\n#eveningAlc = alcohol.select(\"order_hour_of_day\").filter(alcohol.order_hour_of_day>17).filter(alcohol.order_hour_of_day<=23)\\\n#.where(alcohol.order_hour_of_day.isNotNull())\n#print( \"morning alcohol is :\", 100*morningAlc.count()/alcohol.select(\"order_hour_of_day\").count(),\"/n\",\\\n# \"evening alcohol is :\", 100*eveningAlc.count()/alcohol.select(\"order_hour_of_day\").count())\n","sub_path":"fp.py","file_name":"fp.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"558134157","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pywikibot, re, sys, argparse, json, unicodedata\n\nimport blib\nfrom blib import getparam, rmparam, tname, pname, msg, errandmsg, site\n\noutput_pages_to_delete = []\n\ndef remove_anagram_from_page(index, page, pagetitle_to_remove):\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n def errandpagemsg(txt):\n errandmsg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n\n if not blib.safe_page_exists(page, errandpagemsg):\n pagemsg(\"WARNING: Trying to remove anagram '%s' but page itself doesn't exist\" % pagetitle_to_remove)\n return\n\n notes = []\n\n text = blib.safe_page_text(page, errandpagemsg)\n if not text:\n return\n\n retval = blib.find_modifiable_lang_section(text, \"Italian\", pagemsg, force_final_nls=True)\n if retval is None:\n return\n sections, j, secbody, sectail, has_non_lang = retval\n\n subsections = re.split(\"(^==+[^=\\n]+==+\\n)\", secbody, 0, re.M)\n for k in range(2, len(subsections), 2):\n if \"===Anagrams===\" in subsections[k - 1]:\n parsed = blib.parse_text(subsections[k])\n for t in parsed.filter_templates():\n tn = tname(t)\n def getp(param):\n return getparam(t, param)\n if tn == \"anagrams\":\n if getp(\"1\") != \"it\":\n pagemsg(\"WARNING: Wrong language in {{anagrams}}: %s\" % str(t))\n return\n anagrams = blib.fetch_param_chain(t, \"2\")\n anagrams = [x for x in anagrams if x != pagetitle_to_remove]\n if anagrams:\n blib.set_param_chain(t, anagrams, \"2\")\n notes.append(\"remove anagram '%s', page deleted or renamed%s\" % (pagetitle_to_remove, annotation))\n subsections[k] = str(parsed)\n else:\n subsections[k - 1] = \"\"\n subsections[k] = \"\"\n notes.append(\"remove Anagrams section; only had '%s', which has been deleted or renamed%s\"\n % (pagetitle_to_remove, annotation))\n\n secbody = \"\".join(subsections)\n # Strip extra newlines added to secbody\n sections[j] = secbody.rstrip(\"\\n\") + sectail\n text = \"\".join(sections)\n\n return text, notes\n\ndef process_page_for_anagrams(index, page, modify_this_page):\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n def errandpagemsg(txt):\n errandmsg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n\n notes = []\n\n text = blib.safe_page_text(page, errandpagemsg)\n if not text:\n return\n\n retval = blib.find_modifiable_lang_section(text, \"Italian\", pagemsg, force_final_nls=True)\n if retval is None:\n return\n\n sections, j, secbody, sectail, has_non_lang = retval\n\n anagrams = []\n\n subsections = re.split(\"(^==+[^=\\n]+==+\\n)\", secbody, 0, re.M)\n for k in range(2, len(subsections), 2):\n if \"===Anagrams===\" in subsections[k - 1]:\n parsed = blib.parse_text(subsections[k])\n for t in parsed.filter_templates():\n tn = tname(t)\n def getp(param):\n return getparam(t, param)\n if tn == \"anagrams\":\n if getp(\"1\") != \"it\":\n pagemsg(\"WARNING: Wrong language in {{anagrams}}: %s\" % str(t))\n return\n for anagram in blib.fetch_param_chain(t, \"2\"):\n if anagram not in anagrams:\n anagrams.append(anagram)\n elif tn == \"l\":\n if getp(\"1\") != \"it\":\n pagemsg(\"WARNING: Wrong language in {{l}}: %s\" % str(t))\n return\n anagram = getp(\"2\")\n if anagram not in anagrams:\n anagrams.append(anagram)\n if modify_this_page:\n subsections[k - 1] = \"\"\n subsections[k] = \"\"\n notes.append(\"remove Anagrams section prior to renaming page%s\" % annotation)\n secbody = \"\".join(subsections)\n\n # Strip extra newlines added to secbody\n sections[j] = secbody.rstrip(\"\\n\") + sectail\n text = \"\".join(sections)\n\n for anagram in anagrams:\n def do_process_page(page, index, parsed):\n return remove_anagram_from_page(index, page, pagetitle)\n blib.do_edit(pywikibot.Page(site, anagram), index, do_process_page,\n save=args.save, verbose=args.verbose, diff=args.diff)\n\n return text, notes\n\ndef process_page_for_deletion(index, page):\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n def errandpagemsg(txt):\n errandmsg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n if not blib.safe_page_exists(page, errandpagemsg):\n pagemsg(\"Skipping because page doesn't exist\")\n return\n\n notes = []\n\n text = blib.safe_page_text(page, errandpagemsg)\n if not text:\n return\n\n retval = blib.find_modifiable_lang_section(text, \"Italian\", pagemsg)\n if retval is None:\n return\n\n sections, j, secbody, sectail, has_non_lang = retval\n if not has_non_lang:\n # Can delete the whole page, but check for non-blank section 0\n cleaned_sec0 = re.sub(\"^\\{\\{also\\|.*?\\}\\}\\n\", \"\", sections[0])\n if cleaned_sec0.strip():\n pagemsg(\"WARNING: Whole page deletable except that there's text above all sections: <%s>\" % cleaned_sec0.strip())\n return\n pagemsg(\"Page should be deleted\")\n output_pages_to_delete.append(pagetitle)\n return\n\n del sections[j]\n del sections[j-1]\n notes.append(\"remove Italian section for bad (nonexistent or misspelled) form%s\" % annotation)\n if j > len(sections):\n # We deleted the last section, remove the separator at the end of the\n # previous section.\n sections[-1] = re.sub(r\"\\n+--+\\n*\\Z\", \"\", sections[-1])\n text = \"\".join(sections)\n\n return text, notes\n\n\nparser = blib.create_argparser(\"Delete/rename Italian forms, fixing up anagrams\")\nparser.add_argument(\"--direcfile\", help=\"File listing forms to delete/rename.\", required=True)\nparser.add_argument(\"--comment\", help=\"Optional additional comment to use.\")\nparser.add_argument(\"--output-pages-to-delete\", help=\"Output file containing forms to delete.\")\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\nannotation = \" (%s)\" % args.comment if args.comment else \"\"\n\ninput_pages_to_delete = []\noutput_pages_to_delete = []\npages_to_rename = []\n\n# Separate pages to delete and rename. Do pages to delete first so we can run this in sysop mode\n# (python login.py --sysop), and it will first delete the necessary pages, then ask for the non-sysop password and\n# rename the remaining pages.\nfor index, line in blib.iter_items_from_file(args.direcfile, start, end):\n m = re.search(\"^(.*) -> (.*)$\", line)\n if m:\n frompagetitle, topagetitle = m.groups()\n pages_to_rename.append((index, frompagetitle, topagetitle))\n else:\n m = re.search(\"^(.*): delete$\", line)\n if m:\n badpagetitle = m.group(1)\n input_pages_to_delete.append((index, badpagetitle))\n else:\n errandmsg(\"Line %s: Unrecognized line: %s\" % (index, line))\n\nfor index, badpagetitle in input_pages_to_delete:\n badpage = pywikibot.Page(site, badpagetitle)\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, badpagetitle, txt))\n def errandpagemsg(txt):\n errandmsg(\"Page %s %s: %s\" % (index, badagetitle, txt))\n if not blib.safe_page_exists(badpage, errandpagemsg):\n pagemsg(\"Skipping because page doesn't exist\")\n continue\n process_page_for_anagrams(index, badpage, modify_this_page=False)\n def do_process_page(page, index, parsed):\n return process_page_for_deletion(index, page)\n blib.do_edit(badpage, index, do_process_page, save=args.save, verbose=args.verbose, diff=args.diff)\n #this_comment = 'delete bad Italian non-lemma form'\n #if args.save:\n # existing_text = blib.safe_page_text(badpage, errandpagemsg, bad_value_ret=None)\n # if existing_text is not None:\n # badpage.delete('%s (content was \"%s\")' % (this_comment, existing_text))\n # errandpagemsg(\"Deleted (comment=%s)\" % this_comment)\n #else:\n # pagemsg(\"Would delete (comment=%s)\" % this_comment)\n\nfor index, frompagetitle, topagetitle in pages_to_rename:\n frompage = pywikibot.Page(site, frompagetitle)\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, frompagetitle, txt))\n def errandpagemsg(txt):\n errandmsg(\"Page %s %s: %s\" % (index, frompagetitle, txt))\n if not blib.safe_page_exists(frompage, errandpagemsg):\n pagemsg(\"Skipping because page doesn't exist\")\n continue\n def do_process_page(page, index, parsed):\n return process_page_for_anagrams(index, page, modify_this_page=True)\n blib.do_edit(frompage, index, do_process_page,\n save=args.save, verbose=args.verbose, diff=args.diff)\n topage = pywikibot.Page(site, topagetitle)\n if blib.safe_page_exists(topage, errandpagemsg):\n errandpagemsg(\"Destination page %s already exists, not moving\" %\n topagetitle)\n continue\n this_comment = 'rename bad Italian non-lemma form'\n if args.save:\n try:\n frompage.move(topagetitle, reason=this_comment, movetalk=True, noredirect=True)\n errandpagemsg(\"Renamed to %s\" % topagetitle)\n except pywikibot.PageRelatedError as error:\n errandpagemsg(\"Error moving to %s: %s\" % (topagetitle, error))\n else:\n pagemsg(\"Would rename to %s (comment=%s)\" % (topagetitle, this_comment))\n\nmsg(\"The following pages need to be deleted:\")\nfor page in output_pages_to_delete:\n msg(page)\nif args.output_pages_to_delete:\n with open(args.output_pages_to_delete, \"w\", encoding=\"utf-8\") as fp:\n for page in output_pages_to_delete:\n print(page, file=fp)\n","sub_path":"delete_rename_it_forms.py","file_name":"delete_rename_it_forms.py","file_ext":"py","file_size_in_byte":9364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"507559964","text":"import sys\nsys.stdin = open(\"5204.txt\")\n\ndef div(LIST):\n global ans\n length = len(LIST)\n idx = length // 2\n l1 = LIST[:idx]\n l2 = LIST[idx:]\n\n if len(l1) > 1:\n l1 = div(l1)\n if len(l2) > 1:\n l2 = div(l2)\n\n if l1[-1] > l2[-1]:\n ans += 1\n return l2 + l1\n else:\n return l1 + l2\n\nfor t in range(int(input())):\n N = int(input())\n num_list = list(map(int, input().split()))\n ans = 0\n tmp = div(num_list)\n\n num_list.sort()\n n = num_list[N//2]\n\n print(f\"#{t + 1} {ans} {n}\")","sub_path":"SWEA/2019/190328/5204.py","file_name":"5204.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"651915576","text":"from sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy import create_engine\nimport simplejson as json\nimport codecs\n\nengine = create_engine(\"mysql+pymysql://allan:zPSsZYtmmjAJAcjR@localhost:3306/house\", max_overflow=5)\nBase = declarative_base()\ntb_name = \"20190525_21\"\n\n\nclass House(Base):\n __tablename__ = tb_name\n id = Column(Integer, primary_key=True)\n title = Column(String(64))\n link = Column(String(64))\n area = Column(String(64))\n location = Column(String(64))\n totalPrice = Column(String(64))\n unitPrice = Column(String(64))\n flood = Column(String(64))\n follow = Column(String(64))\n tag1 = Column(String(64))\n tag2 = Column(String(64))\n\n\ndef init_db():\n Base.metadata.create_all(engine)\n\n\ndef drop_db():\n Base.metadata.drop_all(engine)\n\n\ndef insert_data_many(insert_data):\n Session = sessionmaker(bind=engine)\n session = Session()\n session.add_all(insert_data)\n session.commit()\n\n\ndef insert_data_one_by_one(insert_data):\n Session = sessionmaker(bind=engine)\n session = Session()\n session.add(insert_data)\n session.commit()\n\n\ndef txt_to_json(name):\n # txt_name = name + \".txt\"\n # with open(txt_name, 'r', encoding='utf-8') as file:\n # data = file.read()\n #\n # data = \"[\" + data\n # data = data + \"]\"\n # data = data.replace(\",]\", \"]\")\n json_save_name = \"./data/\" + name + \"_hours.json\"\n # file = codecs.open(json_save_name, 'wb', 'utf-8')\n # file.write(data)\n\n insert_data = []\n with open(json_save_name, 'r', encoding='utf-8') as f:\n data_json = json.load(f)\n f.close()\n\n for house in data_json:\n insert_h = House()\n insert_h.title = house['title']\n insert_h.link = house['link']\n insert_h.area = house['area']\n insert_h.location = house['location']\n insert_h.totalPrice = house['totalPrice']\n insert_h.unitPrice = house['unitPrice']\n # insert_h.flood = house['flood']\n insert_h.follow = house['follow']\n # insert_h.tag1 = house['tag1']\n # insert_h.tag2 = house['tag2']\n insert_data.append(insert_h)\n\n insert_data_many(insert_data)\n\n\nif __name__ == '__main__':\n # def create_db():\n # hous_s = House()\n # hous_s.title = \"title\"\n # hous_s.area = \"area\"\n # insert_data_one_by_one(hous_s)\n init_db()\n # txt_to_json(tb_name)\n# data = read_json(\"./data/20190520_hours.json\")\n# insert_data(data)\n","sub_path":"house/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"180115718","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 22 16:26:21 2018\nThe idea is to use level order traversal. We traverse\n both trees simultaneously and compare the data whenever we dequeue and item from queue.\n@author: anu\n\"\"\"\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def identical(self,A,B):\n q1=[]\n q2=[]\n if A==None and B==None: #if both trees are none\n return 1\n if (not A) or (not B): #if one of the trees is none\n return 0\n \n q1.append(A)\n q2.append(B)\n while len(q1)!=0 and len(q2)!=0:\n ptr1=q1.pop()\n ptr2=q2.pop()\n \n if ptr1.val != ptr2.val: #compare everytime the popped value\n return 0\n \n if ptr1.left!=None and ptr2.left!=None: \n q1.insert(0,ptr1.left)\n q2.insert(0,ptr2.left)\n \n elif ptr1.left or ptr2.left: #if one of the left child is empty(**necessary step)\n return 0\n \n if ptr1.right!=None and ptr2.right!=None:\n q1.insert(0,ptr1.right)\n q2.insert(0,ptr2.right) \n \n elif ptr1.right or ptr2.right: #if one of the right child is empty(**necessary check)\n return 0\n return 1\n \ns=Solution()\nroot1 = TreeNode(1)\nroot1.left = TreeNode(2)\nroot1.right = TreeNode(3)\nroot1.right.right=TreeNode(6)\nroot1.left.left = TreeNode(4)\nroot1.left.right = TreeNode(5)\nroot1.left.left.left=TreeNode(7) \n\nroot2 = TreeNode(1)\nroot2.left = TreeNode(2)\nroot2.right = TreeNode(3)\nroot2.right.right=TreeNode(6)\nroot2.left.left = TreeNode(4)\nroot2.left.right = TreeNode(5)\nroot2.left.left.left=TreeNode(7) \nprint(s.identical(root1,root2))\n \n ","sub_path":"Tree Datastructure/check Identical Binary tree.py","file_name":"check Identical Binary tree.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"101446681","text":"'''\ndef sum(n):\n if n==0:\n return 0\n else:\n return n+sum(n-1)\nprint(sum(3))\n'''\n\n'''\ndef f1(n):\n if n > 0:\n print(n)\n f1(n - 1)\n\n\nf1(5)\n'''\ndef f1(n):\n if n>0:\n return n+f1(n-1)\n else:\n return 0\nprint(f1(5))","sub_path":"python/func-recursion/study.py","file_name":"study.py","file_ext":"py","file_size_in_byte":264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"161391493","text":"#!/usr/bin/env python3\n\nimport tkinter as tk\nimport random\nimport os\n\n#variables\n\ni = 1\n\nanswers = list(range(11))\nanswers[0]=\"I have never seen a thin person drinking Diet Coke.\";\nanswers[1]=\"If Obama resigns from office NOW, thereby doing a great \\nservice to the country—I will give him free lifetime golf \\nat any one of my courses!\";\nanswers[2]=\"Robert I'm getting a lot of heat for saying you should dump \\nKristen- but I'm right. If you saw the Miss Universe girls \\nyou would reconsider.\";\nanswers[3]=\"Windmills are the greatest threat in the US to both bald and \\ngolden eagles. Media claims fictional 'global warming' is \\nworse\";\nanswers[4]=\"The concept of global warming was created by and for the Chinese \\nin order to make U.S. manufacturing non-competitive.\";\nanswers[5]=\"I will build a great wall – and nobody builds walls better than \\nme, believe me – and I’ll build them very inexpensively. I \\nwill build a great, great wall on our southern border, \\nand I will make Mexico pay for that wall. Mark my words.\";\nanswers[6]=\"I’ve said if Ivanka weren’t my daughter, perhaps I’d be dating her.\";\nanswers[7]=\"My fingers are long and beautiful, as, it has \\nbeen well documented, are various other parts of my body.\";\nanswers[8]=\"Look at those hands, are they small hands? \\nAnd, [Republican rival Marco Rubio] referred to my hands: \\n‘If they’re small, something else must be small.’ \\nI guarantee you there’s no problem. I guarantee.\";\nanswers[9]=\"I was down there, and I watched our police \\nand our firemen, down on 7-Eleven, down at the World Trade Center, \\nright after it came down\";\nanswers[10]=\"Grab them by the pussy. You can do anything.\";\n\n#functions\n\ndef meme():\n\tparent = tk.Toplevel()\n\timageFile01 = tk.PhotoImage(file=\"bin/donald/micha_meme\")\n\tchild = tk.Label(parent, image=imageFile01)\n\tchild.image = imageFile01\n\tchild.grid(row=0, column=0)\n\ndef callbackDonald(event=None):\n\n\tglobal i\n\n\tplaintextfile = open(\"log.dat\", \"a\")\n\tentryText = donaldEntry.get()\n\tdonaldEntry.delete(0, \"end\")\n\t#answers-start\n\n\trandomNumber = random.randint(0, 11)\n\n\tif randomNumber == 11:\n\t\tmeme()\n\t\twriteContentDonald = \"Donald Trump: Whoever this Micha guy is, he seems pretty cool!\"\n\t\ti=i+1\n\telif \"tschuess\" in entryText:\n\t\twriteContentDonald = \"Donald Trump: Time to drain the swamp!\"\n\t\ti=i+1\n\telse:\n\t\tanswer = \"Donald Trump: \"+answers[randomNumber]\n\t\twriteContentDonald = answer\n\t\tif randomNumber in [1,2,3,9]:\n\t\t\ti=i+3\n\t\telif randomNumber in [5,8]:\n\t\t\ti=i+4\n\t\telif randomNumber in [4,7]:\n\t\t\ti=i+2\n\t\telse:\n\t\t\ti=i+1\n\n\t#answers-end\n\twriteContentYou = \"\\nDu: \"+entryText\n\tplaintextfile.write(writeContentYou)\n\ti=i+1\n\twriteContentMe = \"\\n\"+writeContentDonald\n\tplaintextfile.write(writeContentMe)\n\tplaintextfile.close()\n\tplaintextfile = open(\"log.dat\", \"r\")\n\tplaintext = plaintextfile.read()\n\tplaintextfile.close()\n\ttext.set(plaintext)\n\n\twhile i > 40:\n\t\ttry:\n\t\t\tplaintextfile = open(\"log.dat\", \"w\")\n\t\t\tplaintextfile.write(writeContentMe)\n\t\t\tplaintextfile.close()\n\t\t\ti=1\n\t\t\tbreak\n\t\texcept OSError:\n\t\t\ti=41\n\n#init gui\n\ndonald = tk.Tk()\ndonald.title(\"Can't Stump The Trump\")\n\n#gui design\n\ntext = tk.StringVar()\nplaintextfile = open(\"log.dat\", \"w\")\nplaintextfile.write(\"Donald Trump: Make America Great Again\")\nplaintextfile.close()\nplaintextfile = open(\"log.dat\", \"r\")\nplaintext = plaintextfile.read()\ntext.set(plaintext)\nplaintextfile.close()\navdonald = tk.PhotoImage(file=\"avatars/randoms/donald\")\navatar = tk.Label(donald, image=avdonald)\navatar.image = avdonald\navatar.grid(row=0, column=0, rowspan=5)\ndonaldChat = tk.Label(donald, textvariable=text, anchor=\"c\", relief=\"sunken\", width=80, height=40)\ndonaldChat.grid(row=1, column=1, rowspan=10, columnspan=4)\ndonaldEntry = tk.Entry(donald, width=70)\ndonaldEntry.grid(row=11, column=1, rowspan=2, columnspan=3)\ndonaldSend = tk.Button(donald, text=\"Send!\", command=callbackDonald, width=10)\ndonaldSend.grid(row=11, column=4, rowspan=2, columnspan=1)\n\ndonald.bind(\"\", callbackDonald)\ndonald.mainloop()\n","sub_path":"pyBots/randoms/donald.py","file_name":"donald.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"14225422","text":"def apply_iscsi_settings(self):\n 'Update the iSCSI target alias and CHAP settings'\n update = False\n target = self.target\n body = dict()\n if ((self.name is not None) and (self.name != target['alias'])):\n update = True\n body['alias'] = self.name\n if (self.chap_secret is not None):\n update = True\n body.update(dict(enableChapAuthentication=True, chapSecret=self.chap_secret))\n elif target['chap']:\n update = True\n body.update(dict(enableChapAuthentication=False))\n if (update and (not self.check_mode)):\n try:\n request((self.url + ('storage-systems/%s/iscsi/target-settings' % self.ssid)), method='POST', data=json.dumps(body), headers=HEADERS, **self.creds)\n except Exception as err:\n self.module.fail_json(msg=('Failed to update the iSCSI target settings. Array Id [%s]. Error [%s].' % (self.ssid, to_native(err))))\n return update","sub_path":"Data Set/bug-fixing-5/eee51486fd3327c1cfa21dc7566afa7debab5ebf--fix.py","file_name":"eee51486fd3327c1cfa21dc7566afa7debab5ebf--fix.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"573396038","text":"from os import walk\nfrom os import path\nfrom os import makedirs\nimport numpy as np\nimport librosa\n\ndef main(dataset_main_path, name_class_combo, fs, snippet_length, snippet_hop, block_size, hop_size, mel_length):\n print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%') \n j = 0\n for a_combo in name_class_combo:\n a_class = a_combo[1]\n temp_folder = a_class + \"_\" + str(snippet_length) + \"ms_\" + str(snippet_hop) + \"ms\"\n snippet_path = dataset_main_path + \"/\" + temp_folder + \"/\" + a_combo[0]\n \n save_path = snippet_path + \"_MelSpectrogram_block\" + str(block_size) + \"_hop\" + str(hop_size) + \"_mel\" + str(mel_length) \n dir = path.dirname(save_path + \"/dummy.aaa\")\n if not path.exists(dir):\n makedirs(dir)\n \n snippet_names = []\n for (dirpath, dirnames, filenames) in walk(snippet_path):\n snippet_names.extend(filenames)\n break\n \n for a_snippet_name in snippet_names:\n a_snippet_path = snippet_path + \"/\" + a_snippet_name\n x, _ = librosa.load(a_snippet_path, sr = fs)\n S = librosa.feature.melspectrogram(y = x, sr = fs, n_fft = block_size, hop_length = hop_size, n_mels = mel_length)\n #S = S / S.max()\n np.savetxt(save_path +\"/\" + a_snippet_name[0:-4] + '.txt', S, fmt='%10.5f')\n \n j = j + 1\n print(a_combo[0], \"'s spectrogram is done\", j)\n\n\n\n","sub_path":"Create Input/getMelSpectrogram.py","file_name":"getMelSpectrogram.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"363780678","text":"#!/usr/bin/env python\n# coding=utf-8\n'''\n\tconfig \n'''\nfrom __future__ import absolute_import, unicode_literals\nimport os\nimport yaml\nimport logging\nPROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))\n# get config info\nwith open(os.path.join(PROJECT_DIR, 'config', 'config.yaml')) as f:\n config = yaml.load(f)\n# log\ndef logger_init(name, filepath, level=logging.DEBUG):\n logger = logging.getLogger(name)\n logger.setLevel(level)\n ch = logging.FileHandler(filepath)\n formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n return logger\nlogger = logger_init('access', os.path.join(PROJECT_DIR, 'log', 'access.log'),config['logger']['level'])\n# websocket server connect\nconnection = config['connection']\n# currency\ncurrency = config['currency']\n\n\n\n\n","sub_path":"config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413101189","text":"# coding=utf-8\n# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom __future__ import (absolute_import, division, generators, nested_scopes, print_function,\n unicode_literals, with_statement)\n\nimport os\nimport tarfile\nimport unittest\nfrom contextlib import contextmanager\n\nfrom pants.base.project_tree import Dir, Link\nfrom pants.engine.fs import FilesContent, PathGlobs, Snapshot, create_fs_rules\nfrom pants.util.meta import AbstractClass\nfrom pants_test.engine.scheduler_test_base import SchedulerTestBase\n\n\nclass DirectoryListing(object):\n \"\"\"TODO: See #4027.\"\"\"\n\n\nclass ReadLink(object):\n \"\"\"TODO: See #4027.\"\"\"\n\n\nclass FSTest(unittest.TestCase, SchedulerTestBase, AbstractClass):\n\n _original_src = os.path.join(os.path.dirname(__file__), 'examples/fs_test/fs_test.tar')\n\n @contextmanager\n def mk_project_tree(self, ignore_patterns=None):\n \"\"\"Construct a ProjectTree for the given src path.\"\"\"\n project_tree = self.mk_fs_tree(ignore_patterns=ignore_patterns)\n with tarfile.open(self._original_src) as tar:\n tar.extractall(project_tree.build_root)\n yield project_tree\n\n @staticmethod\n def specs(relative_to, *filespecs):\n return PathGlobs.create(relative_to, include=filespecs)\n\n def assert_walk_dirs(self, filespecs, paths, ignore_patterns=None):\n self.assert_walk_snapshot('dirs', filespecs, paths, ignore_patterns=ignore_patterns)\n\n def assert_walk_files(self, filespecs, paths, ignore_patterns=None):\n self.assert_walk_snapshot('files', filespecs, paths, ignore_patterns=ignore_patterns)\n\n def assert_walk_snapshot(self, field, filespecs, paths, ignore_patterns=None):\n with self.mk_project_tree(ignore_patterns=ignore_patterns) as project_tree:\n scheduler = self.mk_scheduler(rules=create_fs_rules(), project_tree=project_tree)\n result = self.execute(scheduler, Snapshot, self.specs('', *filespecs))[0]\n self.assertEquals(sorted([p.path for p in getattr(result, field)]), sorted(paths))\n\n def assert_content(self, filespecs, expected_content):\n with self.mk_project_tree() as project_tree:\n scheduler = self.mk_scheduler(rules=create_fs_rules(), project_tree=project_tree)\n result = self.execute(scheduler, FilesContent, self.specs('', *filespecs))[0]\n actual_content = {f.path: f.content for f in result.dependencies}\n self.assertEquals(expected_content, actual_content)\n\n def assert_digest(self, filespecs, expected_files):\n with self.mk_project_tree() as project_tree:\n scheduler = self.mk_scheduler(rules=create_fs_rules(), project_tree=project_tree)\n result = self.execute(scheduler, Snapshot, self.specs('', *filespecs))[0]\n # Confirm all expected files were digested.\n self.assertEquals(set(expected_files), set(f.path for f in result.files))\n self.assertTrue(result.fingerprint is not None)\n\n def assert_fsnodes(self, filespecs, subject_product_pairs):\n with self.mk_project_tree() as project_tree:\n scheduler = self.mk_scheduler(rules=create_fs_rules(), project_tree=project_tree)\n request = self.execute_request(scheduler, Snapshot, self.specs('', *filespecs))\n\n # Validate that FilesystemNodes for exactly the given subjects are reachable under this\n # request.\n fs_nodes = [n for n, _ in scheduler.product_graph.walk(roots=request.roots)\n if type(n) is \"TODO: need a new way to filter for FS intrinsics\"]\n self.assertEquals(set((n.subject, n.product) for n in fs_nodes), set(subject_product_pairs))\n\n def test_walk_literal(self):\n self.assert_walk_files(['4.txt'], ['4.txt'])\n self.assert_walk_files(['a/b/1.txt', 'a/b/2'], ['a/b/1.txt', 'a/b/2'])\n self.assert_walk_files(['c.ln/2'], ['c.ln/2'])\n self.assert_walk_files(['d.ln/b/1.txt'], ['d.ln/b/1.txt'])\n self.assert_walk_files(['a/3.txt'], ['a/3.txt'])\n self.assert_walk_files(['z.txt'], [])\n\n def test_walk_literal_directory(self):\n self.assert_walk_dirs(['c.ln'], ['c.ln'])\n self.assert_walk_dirs(['a'], ['a'])\n self.assert_walk_dirs(['a/b'], ['a/b'])\n self.assert_walk_dirs(['z'], [])\n self.assert_walk_dirs(['4.txt', 'a/3.txt'], [])\n\n def test_walk_siblings(self):\n self.assert_walk_files(['*.txt'], ['4.txt'])\n self.assert_walk_files(['a/b/*.txt'], ['a/b/1.txt'])\n self.assert_walk_files(['c.ln/*.txt'], ['c.ln/1.txt'])\n self.assert_walk_files(['a/b/*'], ['a/b/1.txt', 'a/b/2'])\n self.assert_walk_files(['*/0.txt'], [])\n\n def test_walk_recursive(self):\n self.assert_walk_files(['**/*.txt.ln'], ['a/4.txt.ln', 'd.ln/4.txt.ln'])\n self.assert_walk_files(['**/*.txt'], ['4.txt',\n 'a/3.txt',\n 'a/b/1.txt',\n 'c.ln/1.txt',\n 'd.ln/3.txt',\n 'd.ln/b/1.txt'])\n self.assert_walk_files(['**/*.txt'], ['a/3.txt',\n 'a/b/1.txt',\n 'c.ln/1.txt',\n 'd.ln/3.txt',\n 'd.ln/b/1.txt',\n '4.txt'])\n self.assert_walk_files(['**/3.t*t'], ['a/3.txt', 'd.ln/3.txt'])\n self.assert_walk_files(['**/*.zzz'], [])\n\n def test_walk_single_star(self):\n self.assert_walk_files(['*'], ['4.txt'])\n\n def test_walk_parent_link(self):\n self.assert_walk_files(['c.ln/../3.txt'], ['c.ln/../3.txt'])\n\n def test_walk_recursive_all(self):\n self.assert_walk_files(['**'], ['4.txt',\n 'a/3.txt',\n 'a/4.txt.ln',\n 'a/b/1.txt',\n 'a/b/2',\n 'c.ln/1.txt',\n 'c.ln/2',\n 'd.ln/3.txt',\n 'd.ln/4.txt.ln',\n 'd.ln/b/1.txt',\n 'd.ln/b/2'])\n\n def test_walk_ignore(self):\n # Ignore '*.ln' suffixed items at the root.\n self.assert_walk_files(['**'],\n ['4.txt',\n 'a/3.txt',\n 'a/4.txt.ln',\n 'a/b/1.txt',\n 'a/b/2',],\n ignore_patterns=['/*.ln'])\n # Whitelist one entry.\n self.assert_walk_files(['**'],\n ['4.txt',\n 'a/3.txt',\n 'a/4.txt.ln',\n 'a/b/1.txt',\n 'a/b/2',\n 'c.ln/1.txt',\n 'c.ln/2',],\n ignore_patterns=['/*.ln', '!c.ln'])\n\n def test_walk_recursive_trailing_doublestar(self):\n self.assert_walk_files(['a/**'], ['a/3.txt',\n 'a/4.txt.ln',\n 'a/b/1.txt',\n 'a/b/2'])\n self.assert_walk_files(['d.ln/**'], ['d.ln/3.txt',\n 'd.ln/4.txt.ln',\n 'd.ln/b/1.txt',\n 'd.ln/b/2'])\n self.assert_walk_dirs(['a/**'], ['a/b'])\n\n def test_walk_recursive_slash_doublestar_slash(self):\n self.assert_walk_files(['a/**/3.txt'], ['a/3.txt'])\n self.assert_walk_files(['a/**/b/1.txt'], ['a/b/1.txt'])\n self.assert_walk_files(['a/**/2'], ['a/b/2'])\n\n def test_walk_recursive_directory(self):\n self.assert_walk_dirs(['*'], ['a', 'c.ln', 'd.ln'])\n self.assert_walk_dirs(['*/*'], ['a/b', 'd.ln/b'])\n self.assert_walk_dirs(['**/*'], ['a', 'c.ln', 'd.ln', 'a/b', 'd.ln/b'])\n self.assert_walk_dirs(['*/*/*'], [])\n\n def test_remove_duplicates(self):\n self.assert_walk_files(['*', '**'], ['4.txt',\n 'a/3.txt',\n 'a/4.txt.ln',\n 'a/b/1.txt',\n 'a/b/2',\n 'c.ln/1.txt',\n 'c.ln/2',\n 'd.ln/3.txt',\n 'd.ln/4.txt.ln',\n 'd.ln/b/1.txt',\n 'd.ln/b/2'])\n self.assert_walk_files(['**/*.txt', 'a/b/1.txt', '4.txt'], ['4.txt',\n 'a/3.txt',\n 'c.ln/1.txt',\n 'd.ln/3.txt',\n 'a/b/1.txt',\n 'd.ln/b/1.txt'])\n self.assert_walk_dirs(['*', '**'], ['a', 'c.ln', 'd.ln', 'a/b', 'd.ln/b'])\n\n def test_files_content_literal(self):\n self.assert_content(['4.txt', 'a/4.txt.ln'], {'4.txt': 'four\\n', 'a/4.txt.ln': 'four\\n'})\n\n def test_files_content_directory(self):\n with self.assertRaises(Exception):\n self.assert_content(['a/b/'], {'a/b/': 'nope\\n'})\n with self.assertRaises(Exception):\n self.assert_content(['a/b'], {'a/b': 'nope\\n'})\n\n def test_files_content_symlink(self):\n self.assert_content(['c.ln/../3.txt'], {'c.ln/../3.txt': 'three\\n'})\n\n def test_files_digest_literal(self):\n self.assert_digest(['a/3.txt', '4.txt'], ['a/3.txt', '4.txt'])\n\n @unittest.skip('Skipped to expedite landing #3821; see: #4027.')\n def test_nodes_file(self):\n self.assert_fsnodes(['4.txt'], [\n (Dir(''), DirectoryListing),\n ])\n\n @unittest.skip('Skipped to expedite landing #3821; see: #4027.')\n def test_nodes_symlink_file(self):\n self.assert_fsnodes(['c.ln/2'], [\n (Dir(''), DirectoryListing),\n (Link('c.ln'), ReadLink),\n (Dir('a'), DirectoryListing),\n (Dir('a/b'), DirectoryListing),\n ])\n self.assert_fsnodes(['d.ln/b/1.txt'], [\n (Dir(''), DirectoryListing),\n (Link('d.ln'), ReadLink),\n (Dir('a'), DirectoryListing),\n (Dir('a/b'), DirectoryListing),\n ])\n\n @unittest.skip('Skipped to expedite landing #3821; see: #4027.')\n def test_nodes_symlink_globbed_dir(self):\n self.assert_fsnodes(['*/2'], [\n # Scandir for the root.\n (Dir(''), DirectoryListing),\n # Read links to determine whether they're actually directories.\n (Link('c.ln'), ReadLink),\n (Link('d.ln'), ReadLink),\n # Scan second level destinations: `a/b` is matched via `c.ln`.\n (Dir('a'), DirectoryListing),\n (Dir('a/b'), DirectoryListing),\n ])\n\n @unittest.skip('Skipped to expedite landing #3821; see: #4027.')\n def test_nodes_symlink_globbed_file(self):\n self.assert_fsnodes(['d.ln/b/*.txt'], [\n # NB: Needs to scandir every Dir on the way down to track whether\n # it is traversing a symlink.\n (Dir(''), DirectoryListing),\n # Traverse one symlink.\n (Link('d.ln'), ReadLink),\n (Dir('a'), DirectoryListing),\n (Dir('a/b'), DirectoryListing),\n ])\n","sub_path":"tests/python/pants_test/engine/test_fs.py","file_name":"test_fs.py","file_ext":"py","file_size_in_byte":11393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"22170452","text":"\"\"\" Calculate information contents and parameters of a BSC.\n\nThis program is intended for used in course, Principle of Information and Coding Theory.\nUsage details can be displayed by passing command line argument `--help`.\n\nNote: All information contents calculated are bit-wise, i.e. in (information-)bit per (binary-)bit.\n\nrevise:\n通过修改教师提供的代码\n屏蔽掉其他的输出,只保留\n 输入消息序列的信息熵(信息比特/二元消息)\n 输出消息序列的信息熵(信息比特/二元消息)\n 平均互信息量(信息比特/二元消息)\n这三个输出即可\n\n\"\"\"\n\n# Standard library\nimport sys\nimport argparse\nimport time\nimport csv\nfrom pathlib import Path\n\n# Non-standard library\nimport numpy as np\n\n__author__ = \"Guo, Jiangling\"\n__email__ = \"tguojiangling@jnu.edu.cn\"\n__version__ = \"2020101.1549\"\n\n\ndef main():\n \"\"\"Entry point of this program.\"\"\"\n args = parse_sys_args()\n workflow(args.X, args.Y, args.OUTPUT, verbose=args.verbose)\n\n###\n# The main work flow\n###\n\n\ndef workflow(x_file_name, y_file_name, out_file_name, verbose=False):\n \"\"\"The main workflow.\"\"\"\n\n # Number of binary bits in one symbol.\n N = 8\n\n x = read_file_as_bytes(x_file_name)\n y = read_file_as_bytes(y_file_name)\n\n ## --- Core computation: begin\n start_time = time.time()\n\n joint_p_xy = calc_joint_p_xy(x, y)\n H_x = calc_H_p(calc_p_x(joint_p_xy)) / N\n H_y = calc_H_p(calc_p_y(joint_p_xy)) / N\n joint_H_xy = calc_joint_H_xy(joint_p_xy) / N\n cond_H_xy = calc_cond_H_xy(joint_p_xy) / N\n cond_H_yx = calc_cond_H_yx(joint_p_xy) / N\n I_xy = H_x - cond_H_xy\n\n # Calculate error probability of the BSC.\n err = np.bitwise_xor(x, y)\n p_BSC = count_binary_1(err) / (x.size * N)\n\n elapsed_time = time.time() - start_time\n ## --- Core computation: end\n\n if verbose:\n p_x0 = 1 - (count_binary_1(x) / (x.size * N))\n p_y0 = 1 - (count_binary_1(y) / (y.size * N))\n print('Computation Time: %.5f sec' % (elapsed_time))\n print(' BSC input (X): %d bytes, \"%s\"' % (x.size, x_file_name))\n print(' BSC output (Y): %d bytes, \"%s\"' % (y.size, y_file_name))\n print(' H(X) =', H_x, 'bit/bit, p(x=0) =', p_x0)\n print(' H(Y) =', H_y, 'bit/bit, p(y=0) =', p_y0)\n print(' H(XY) =', joint_H_xy, 'bit/2-bit')\n print('H(X|Y) =', cond_H_xy, 'bit/bit')\n print('H(Y|X) =', cond_H_yx, 'bit/bit')\n print('I(X;Y) =', I_xy, 'bit/bit')\n print('(BSC)p =', p_BSC)\n\n write_results(out_file_name, [\n x_file_name, y_file_name, H_x, H_y, I_xy])\n\n return H_x\n\n###\n# Computation functions\n###\n\n\ndef calc_joint_p_xy(x, y):\n (joint_p_xy, xedges, yedges) = np.histogram2d(\n x, y, bins=range(257), density=True)\n return joint_p_xy\n\n\ndef calc_p_y(joint_p_xy):\n \"\"\"Calculate p(y).\"\"\"\n return np.sum(joint_p_xy, axis=0)\n\n\ndef calc_p_x(joint_p_xy):\n \"\"\"Calculate p(x).\"\"\"\n return np.sum(joint_p_xy, axis=1)\n\n\ndef calc_I_p(P):\n \"\"\"Calculate self-information from given probability distribution.\"\"\"\n P = replace_0_with_eps(P)\n return -np.log2(P)\n\n\ndef calc_H_p(P):\n \"\"\"Compute entropy from given probability distribution.\"\"\"\n return np.sum(P*calc_I_p(P))\n\n\ndef calc_joint_H_xy(joint_p_xy):\n \"\"\"Calculate joint entropy H(XY).\"\"\"\n return np.sum(joint_p_xy * calc_I_p(joint_p_xy))\n\n\ndef calc_cond_H_xy(joint_p_xy):\n \"\"\"Calculate conditional entropy H(X|Y).\"\"\"\n p_y = calc_p_y(joint_p_xy)\n p_y = replace_0_with_eps(p_y)\n\n # Extend p_y vertically to 255 rows:\n # p_y_matrix =\n # [ [ p(y_0), p(y_1), ..., p(y_255) ],\n # [ p(y_0), p(y_1), ..., p(y_255) ],\n # ...\n # [ p(y_0), p(y_1), ..., p(y_255) ] ]\n p_y_matrix = np.repeat([p_y], joint_p_xy.shape[0], axis=0)\n\n return np.sum(joint_p_xy * calc_I_p(joint_p_xy / p_y_matrix))\n\n\ndef calc_cond_H_yx(joint_p_xy):\n \"\"\"Calculate conditional entropy H(Y|X).\"\"\"\n p_x = calc_p_x(joint_p_xy)\n p_x = replace_0_with_eps(p_x)\n\n # Transpose p_x and extend it horizontally to 255 columns:\n # p_x_matrix =\n # [ [ p(x_0), p(x_0), ..., p(x_0) ],\n # [ p(x_1), p(x_1), ..., p(x_1) ],\n # ...\n # [ p(x_255), p(x_255), ..., p(x_255) ] ]\n p_x_matrix = np.repeat(np.array([p_x]).T, joint_p_xy.shape[1], axis=1)\n\n return np.sum(joint_p_xy * calc_I_p(joint_p_xy / p_x_matrix))\n\n\ndef count_binary_1(x):\n # Create a Look-Up Table for number of binary '1' in each byte.\n LUT_num_of_1 = np.array([bin(byte).count(\"1\") for byte in range(256)])\n num_of_1 = np.sum(LUT_num_of_1[x])\n return num_of_1\n\n\ndef replace_0_with_eps(P):\n \"\"\"Replace zeros with the smallest numbers.\"\"\"\n # For probabilities, it makes virtually no difference, but for computation it can prevent some undesired results such as 0*log2(0)=nan.\n return np.where(P == 0, np.spacing(1), P)\n\n###\n# I/O\n###\n\n\ndef read_file_as_bytes(in_file_name):\n \"\"\"Read a file as bytes and return a uint8 array.\"\"\"\n return np.fromfile(in_file_name, dtype='uint8')\n\n\ndef write_results(out_file_name, data):\n \"\"\"Write a row of data into a CSV file.\"\"\"\n\n # Write the header for all columns, if the output file does not exist.\n if not Path(out_file_name).is_file():\n with open(out_file_name, 'w', newline='') as out_file:\n csvwriter = csv.writer(out_file, quoting=csv.QUOTE_ALL)\n csvwriter.writerow(\n ['X', 'Y', 'H(X)', 'H(Y)', 'I(X;Y)'])\n\n with open(out_file_name, 'a', newline='') as out_file:\n csvwriter = csv.writer(out_file, quoting=csv.QUOTE_ALL)\n csvwriter.writerow(data)\n\n###\n# Parse command line arguments.\n###\n\n\ndef parse_sys_args():\n \"\"\"Parse command line arguments.\"\"\"\n\n # Define syntax for command line arguments.\n parser = argparse.ArgumentParser(\n description='Calculate information for BSC.')\n parser.add_argument('X', help='path to the channel input file')\n parser.add_argument('Y', help='path to the channel output file')\n parser.add_argument(\n 'OUTPUT', help='path to the output file to append results')\n parser.add_argument('-v', '--verbose', action='store_true',\n help='display detailed messages')\n\n if len(sys.argv) == 1:\n # No arguments specified.\n parser.print_help()\n parser.exit()\n else:\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ICT00-课程设计-文档/src/byteChannel_calc.py","file_name":"byteChannel_calc.py","file_ext":"py","file_size_in_byte":6418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"634352101","text":"def updateInventory(arr1, arr2):\n # All inventory must be accounted for or you're fired!\n arr = arr1 + arr2\n names = []\n toReturn = []\n\n # convert to dict\n items = {}\n for count, name in arr:\n if name in items:\n items[name] += count\n else: \n items[name] = count\n names.append(name)\n \n names.sort()\n\n # populate list to return\n for name in names:\n toReturn.append([items[name],name])\n \n # print toReturn\n for i in toReturn:\n print(i)\n\n\n\n\n\n\n# Example inventory lists\ncurInv = [\n [21, \"Bowling Ball\"],\n [2, \"Dirty Sock\"],\n [1, \"Hair Pin\"],\n [5, \"Microphone\"]\n];\n\nnewInv = [\n [2, \"Hair Pin\"],\n [3, \"Half-Eaten Apple\"],\n [67, \"Bowling Ball\"],\n [7, \"Toothpaste\"]\n];\n\nupdateInventory(curInv, newInv);\n","sub_path":"Inventory Update/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"607108475","text":"import sys\n\nfrom time import sleep\nfrom random import randint, choice\nfrom InstagramAPI import InstagramAPI\nfrom json_loader import get_account\nfrom json_loader import get_settings\nfrom db_manager import db_manager\n\nfrom instapy import InstaPy\n\nclass img_bot:\n def __init__(self):\n self.api = None\n self.pic_api = None\n self.db = None\n self.photo = None\n self.conn = None\n self.tags = None\n self.similar_acc = None\n\n def db_connect(self, subreddit):\n path, img_path = get_settings(subreddit)\n\n self.db = db_manager(path)\n self.db.table = subreddit\n self.conn = self.db.create_connect()\n self.db.count_row(self.conn)\n return img_path\n\n def start_session(self):\n \"\"\"\n Startes a session for each account in the json file. By creating a random schedule\n of functions to go through before moving to the next account.\"\"\"\n accounts = get_account()\n for account in accounts:\n delay = randint(7,18)\n print(\"\\nSessions started for user: \", account[\"username\"])\n subreddit = account[\"subreddit\"]\n # These are list which get replaced with every loop\n self.similar_acc = account[\"similar_accounts\"]\n self.tags = account[\"tags\"]\n self.pic_api = InstagramAPI(account[\"username\"], account[\"password\"])\n self.api = InstaPy(username=account[\"username\"], password=account[\"password\"], multi_logs=True)\n self.api.login()\n sleep(delay)\n img_path = self.db_connect(subreddit)\n self.schedule()\n sleep(delay)\n self.pic_api.login()\n self.post_image(img_path)\n self.end_session()\n print(\"Session done for user: \", account[\"username\"])\n\n def schedule(self):\n \"\"\"\n Chooses what functions to run.\n Sleeps for a minimum of 10 minutes to avoid bans.\n \"\"\"\n runs = randint(1,8)\n functions = [self.follow_people, self.interact_feed, self.unfollow_inactive,\n self.interact_tags]\n while runs > 0:\n try:\n choice(functions)()\n except:\n continue\n cooldown = randint(601, 1800)\n sleep(cooldown)\n runs -= 1\n return\n\n def follow_people(self):\n \"\"\"Follow people from a list of similar acccounts\"\"\"\n follow = randint(20, 150)\n pictures = randint(1,5)\n interact = randint(20, 45)\n print(\"Started following users. Total number to follow: \", follow)\n self.api.set_user_interact(amount=pictures, randomize=True, percentage=interact, media='Photo')\n self.api.follow_user_followers(self.similar_acc, amount=follow, randomize=True, sleep_delay=600)\n return\n\n\n def unfollow_inactive(self):\n \"\"\"Unfollows inactive users \"\"\"\n unfollow = randint(20, 150)\n print(\"Started unfollwing people. Total number to unfollow: \", unfollow)\n self.api.set_dont_unfollow_active_users(enabled=True, posts=3)\n self.api.unfollow_users(amount=unfollow, onlyNotFollowMe=True, sleep_delay=600)\n return\n\n def interact_feed(self):\n \"\"\"Like pictures in the feed and go into profiles and like pictures.\"\"\"\n likes = randint(2,35)\n interact = randint(20, 45)\n pictures = randint(1, 5)\n print(\"Started interacting with feed. Total likes to give: \", likes)\n self.api.set_user_interact(amount=pictures, randomize=True, percentage=interact, media='Photo')\n self.api.like_by_feed(amount=likes, randomize=True, interact=True)\n return\n\n def interact_tags(self):\n \"\"\"Interact with users based off tags.\"\"\"\n interact = randint(20, 45)\n tag_likes = randint(5, 30)\n pictures = randint(1, 5)\n print(\"Started looking at tags. Total likes to give: \", tag_likes)\n self.api.set_user_interact(amount=pictures, randomize=True, percentage=interact, media='Photo')\n self.api.like_by_tags(self.tags, amount=tag_likes, interact=True)\n return\n\n def end_session(self):\n self.db.close_connection(self.conn)\n self.pic_api.logout()\n self.api.end()\n\n def post_image(self, path):\n \"\"\"Post a random picture from database and delete row from the database \"\"\"\n\n row = self.db.get_random_row(self.conn, 1)\n\n id = row[0]\n img_path = path + row[1] + '0.jpg'\n description = row[2]\n # Try uploading the picture and if that's not working then just delete the image and db entry\n while True:\n try:\n self.pic_api.uploadPhoto(img_path, caption=description)\n print(\"Image uploaded: \" + row)\n print(\"Removing from database\" + str(id))\n self.db.delete_row(self.conn, row)\n break\n except:\n print(\"Problem detected. Deleted from database: \" + str(id), sys.exc_info()[0])\n self.db.delete_row(self.conn, row)\n return\n","sub_path":"img_bot.py","file_name":"img_bot.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"614267716","text":"import pkg_resources\n\n__name__ = 'Another World'\n__description__ = 'This is another example plugin for Joseph'\n__version__ = 'V0.1'\n__license__ = 'LICENSE'\n__readme__ = 'README.md'\n__author__ = 'Niek Keijzer'\n__website__ = 'www.example.com'\n\n\ndef run():\n database = {}\n\n for ep in pkg_resources.iter_entry_points(group='database'):\n database.update({ep.name: ep.load()})\n\n try:\n db = database['database']()\n except ImportError:\n # Do something without permissions\n pass\n else:\n main()\n\n\ndef main():\n print('hello from another plugin')\n","sub_path":"joseph/plugins/another_world/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"332075512","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom odoo import api, models, osv,fields\r\n# from openerp import osv,fields,models, api\r\nfrom odoo.tools.translate import _\r\nfrom datetime import datetime\r\n\r\n\r\nclass model_contract(models.Model):\r\n\r\n _name= \"hr.model.contract\"\r\n _description=u\"Modèle de contrat\"\r\n\r\n\r\n @api.onchange('hr_convention_id')\r\n def on_change_convention_id(self):\r\n if self.hr_convention_id :\r\n return {'domain':{'hr_secteur_id':[('hr_convention_id','=',self.hr_convention_id.id)]}}\r\n else :\r\n return {'domain':{'hr_secteur_id':[('hr_convention_id','=',False)]}}\r\n\r\n\r\n @api.onchange('hr_secteur_id')\r\n def on_change_secteur_id(self):\r\n if self.hr_secteur_id :\r\n return {'domain':{'categorie_salariale':[('hr_secteur_activite_id','=', self.hr_secteur_id.id)]}}\r\n else :\r\n return {'domain':{'categorie_salariale':[('hr_secteur_activite_id','=',False)]}}\r\n \r\n\r\n\r\n @api.onchange(\"categorie_salariale\")\r\n def change_categorie(self):\r\n res = {'value':{\r\n 'salaire_base':0,\r\n }\r\n }\r\n if self.categorie_salariale and self.categorie_salariale.salaire_base:\r\n self.salaire_base= self.categorie_salariale.salaire_base\r\n else :\r\n self.salaire_base= 0\r\n\r\n \r\n\r\n name= fields.Char(\"Designation\",size=128,required=True)\r\n salaire_base= fields.Integer(\"Salaire de base\",required=True)\r\n prime_ids= fields.One2many(\"hr.payroll.prime.montant\",\"model_contract_id\",\"Primes\")\r\n categorie_salariale= fields.Many2one(\"hr.categorie.salariale\",\"Categorie salariale\",required=True,\r\n domain=\"[('hr_secteur_activite_id', '=', secteur_activite_id)]\")\r\n titre_poste= fields.Many2one(\"hr.job\",\"Titre du Poste\",required=True)\r\n type_contract= fields.Many2one(\"hr.contract.type\",\"Type de conntract\",required=True)\r\n structure_salariale= fields.Many2one('hr.payroll.structure',\"Structure salariale\",required=True)\r\n convention_id= fields.Many2one(\"hr.convention\",\"Convention\",required=True)\r\n secteur_activite_id= fields.Many2one(\"hr.secteur.activite\",\"Secteur d'activité\",required=True)\r\n\r\n\r\nclass contract_generate(models.Model):\r\n\r\n api.multi\r\n def generate_contract(self):\r\n contract_obj = self.env[\"hr.contract\"]\r\n prime_obj= self.env['hr.payroll.prime.montant']\r\n for employee in self.employee_ids:\r\n vals={\r\n 'name': \"Contract %s\"%employee.name,\r\n \"wage\": self.model_contract_id.salaire_base,\r\n \"employee_id\":employee.id,\r\n \"sursalaire\": 0,\r\n \"categorie_salariale_id\": self.model_contract_id.categorie_salariale.id,\r\n 'job_id': self.model_contract_id.titre_poste.id,\r\n 'struct_id': self.model_contract_id.structure_salariale.id,\r\n 'hr_convention_id': self.model_contract_id.convention_id.id,\r\n 'hr_secteur_id': self.model_contract_id.secteur_activite_id.id,\r\n 'type_id': self.model_contract_id.type_contract.id,\r\n }\r\n\r\n contract = contract_obj.create(vals)\r\n for prime in self.model_contract_id.prime_ids :\r\n prime_values={\r\n 'prime_id':prime.prime_id.id,\r\n 'montant_prime':prime.montant_prime,\r\n 'contract_id':contract.id,\r\n }\r\n prime_montant_id = prime_obj.create(prime_values)\r\n \r\n _name=\"hr.contract.generate\"\r\n\r\n name= fields.Char(\"Name\",size=128,required=True)\r\n model_contract_id= fields.Many2one(\"hr.model.contract\",'Model',required=True)\r\n date_generate= fields.Datetime(\"Date de génération\")\r\n employee_ids= fields.Many2many(\"hr.employee\",\"hr_model_contract_rel\",\"hr_model_contract_id\",\"employee_id\",\"Employees\")\r\n\r\n\r\nclass hr_payroll_prime_montant(models.Model):\r\n _inherit = 'hr.payroll.prime.montant' \r\n _name=\"hr.payroll.prime.montant\"\r\n\r\n\r\n model_contract_id= fields.Many2one(\"hr.model.contract\",\"Modèle de contrat\")\r\n","sub_path":"hr_contract_model/models/hr_contract_model.py","file_name":"hr_contract_model.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"407014289","text":"import vigenereCipher, vigenereHacker, random\n# this function takes a given string and strips it of all non letter chars\n# also coverts all lower case letters to upper case\ndef alpha_only(plaintext):\n final = ''\n for char in plaintext:\n if char.isalpha() == True:\n final += char.upper()\n return final\n\n#this function insert was retrived from:\n#https://stackoverflow.com/questions/4022827/insert-some-string-into-given-string-at-given-index-in-python\n#by Sim Mak\n# this function inserts a sting in the middle of another given sting at a\n# certian position\ndef insert (source_str, insert_str, pos):\n return source_str[:pos]+insert_str+source_str[pos:]\n\ndef antiKasiski(key, plaintext):\n alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n plaintext = alpha_only(plaintext)\n encrypted = vigenereCipher.encryptMessage(key, plaintext)\n\n # get the repeating sequnces\n a = vigenereHacker.findRepeatSequencesSpacings(encrypted)\n\n #saving this string for later to be used in insert function\n final = encrypted\n\n#this loop goes through the repeated sequnces and for every time in the string it\n# appers that isnt the first time it will insert a random letter between it\n for key in a:\n length = len(encrypted) - len(key)\n x = len(key)\n count =0\n for i in range(0, length):\n cluster = encrypted[i:i+x]\n if cluster == key:\n if count == 0:\n count +=1\n else:\n # puts rand letter into the string\n int = random.randint(0, 25)\n letter = alphabet[int]\n\n final = insert(final, letter, i)\n return final\n\n#print(antiKasiski('WICK', 'THOSEPOLICEOFFICERSOFFEREDHERARIDEHOMETHEYTELLTHEMAJOKETHOSEBARBERSLENTHERALOTOFMONEY'))\n","sub_path":"02_Encryption/07_Vigenere_Hacker/preproc.py","file_name":"preproc.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"170995135","text":"import sys\n\nimport subprocess\n\nimport os\nimport requests\nimport json\n\nconf = None\n\n\ndef load_conf(file_path):\n global conf\n try:\n with open(file_path) as f:\n conf = json.loads(f.read())\n except Exception as e:\n print(str(e))\n print('Not found %s, or configuration file not in JSON format' % file_path)\n sys.exit(1)\n\n\ndef generate_command(trail):\n o_trail = json.loads(trail)\n cmd = []\n for param in o_trail:\n cmd.append('--%s=%s' % (param['name'], param['value']))\n return cmd\n\n\ndef parse_metric(metric):\n return dict({\n \"value\": metric\n })\n\n\ndef run():\n argv = sys.argv\n conf_path = argv[1]\n trail_id = argv[2]\n trail = argv[3]\n\n load_conf(conf_path)\n print(conf)\n\n # call the objective function and get the output\n cmd = generate_command(trail)\n\n parameter_list = [conf['model'][\"python-version\"], conf['model'][\"entry\"]] + cmd\n # parameter_list = parameter_list + values\n os.chdir(conf['model']['project-root'])\n proc = subprocess.Popen(parameter_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = str(proc.communicate()[0])\n\n # format the output\n start = 2\n end = len(output)-3\n metric = float(output[start:end])\n metric = parse_metric(metric)\n\n # print(metric)\n\n response_url = conf['response_url']\n r = requests.post(\n url=response_url,\n json={\n \"trail_id\": trail_id,\n \"metric\": metric\n }\n )\n # print(r.text)\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"advisorclient/run_trail.py","file_name":"run_trail.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"118391834","text":"name = input('Please input your name:')\nscore = input('Please input python score:')\n\nprint(type(name))\nprint(type(score))\n\nnumstr = input(\"Please your fumela:\")\nnumber = eval(numstr)\nprint(\"result: %6.3f\" % number)\n\nn1, n2, n3 = eval(input(\"請輸入3個數字(需要用逗號分隔):\"))\n\naverage = (n1 + n2 + n3)/3\nprint(\"3個數字的平均: %6.2f\" % average)\n","sub_path":"20191120/s3-1.py","file_name":"s3-1.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"549101791","text":"import tweepy\nimport pandas as pd\n\napi_key = pd.read_pickle('auth/twitter_auth_key.pickle')\n\nauth = tweepy.OAuthHandler(api_key['consumer_key'], api_key['consumer_secret'])\nauth.set_access_token(api_key['access_token'], api_key['access_secret'])\n\napi = tweepy.API(auth)\n\ntweets = tweepy.Cursor(api.search,q=\"Amazon\",count=100,result_type=\"popular\",include_entities=True,lang=\"en\").items()\nnew_ids = set([tweet.id for tweet in tweets])\n# print(len(new_ids))\n# for id in new_ids:\n# print(id,type(id))\n\nold_ids = set(pd.Series.from_csv('hist_tweets.csv',sep=';').tolist())\n\nall_ids = old_ids.union(new_ids)\n\nprint(len(all_ids))\n\nall_ids = pd.Series(list(all_ids))\nall_ids.to_csv('hist_tweets.csv',sep=';')\n","sub_path":"twitter_filter/tweet_tk/twitter_hist.py","file_name":"twitter_hist.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"571423963","text":"#!/usr/bin/env python3\n\"\"\"\nbuilds a modified version of the LeNet-5 architecture using tensorflow.\n\"\"\"\n\nimport tensorflow as tf\n\n\n# https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D\n# tf.keras.layers.Conv2D(\n# filters,\n# kernel_size,\n# strides=(1, 1),\n# padding='valid',\n# data_format=None,\n# dilation_rate=(1, 1),\n# activation=None,\n# use_bias=True,\n# kernel_initializer='glorot_uniform',\n# bias_initializer='zeros',\n# kernel_regularizer=None,\n# bias_regularizer=None,\n# activity_regularizer=None,\n# kernel_constraint=None,bias_constraint=None,\n# **kwargs )\n\n# https://www.tensorflow.org/api_docs/python/tf/keras/layers/MaxPool2D\n# tf.keras.layers.MaxPool2D(\n# pool_size=(2, 2),\n# strides=None,\n# padding='valid',\n# data_format=None,\n# **kwargs )\n\n# tf.keras.layers.Dense(\n# units,\n# activation=None,\n# use_bias=True,\n# kernel_initializer='glorot_uniform',\n# bias_initializer='zeros',\n# kernel_regularizer=None,\n# bias_regularizer=None,\n# activity_regularizer=None,\n# kernel_constraint=None,\n# bias_constraint=None,\n# **kwargs )\n\n# tf.keras.layers.Softmax(\n# axis=-1,\n# **kwargs )\n\ndef lenet5(x, y):\n \"\"\"\n builds a modified version of the LeNet-5 architecture using tensorflow\n :param x: x is a tf.placeholder of shape (m, 28, 28, 1) containing the\n input images for the network\n m is the number of images\n :param y: y is a tf.placeholder of shape (m, 10) containing the one-hot\n labels for the network\n :return:\n \"\"\"\n # el initializer 3000\n init = tf.contrib.layers.variance_scaling_initializer()\n\n # la mierda que recibe inputs\n primer_layer = tf.layers.Conv2D(filters=6, kernel_size=[5, 5],\n padding='same', kernel_initializer=init,\n activation='relu')\n\n x = primer_layer(x)\n\n # ahora vamos con un max poolincibiribiri\n segundo_layer = tf.layers.MaxPooling2D(pool_size=(2, 2),\n strides=(2, 2))\n\n x = segundo_layer(x)\n\n # ahora vamos con otra puta convolutional\n tercer_layer = tf.layers.Conv2D(filters=16, kernel_size=[5, 5],\n padding='valid',\n kernel_initializer=init,\n activation='relu')\n\n x = tercer_layer(x)\n\n # ahora vamos con otra piscina la mas chimba\n cuarto_layer = tf.layers.MaxPooling2D(pool_size=(2, 2),\n strides=(2, 2))\n\n x = cuarto_layer(x)\n\n # esta mierda es para pasar las imagenes a 1D porque la vaina no\n # funciona en otras dimensions\n quinto_layer = tf.layers.Flatten()\n\n x = quinto_layer(x)\n\n # ahora vamos con la vieja confiable de un fully connected - orgia total.\n sexto_layer = tf.layers.Dense(units=120, activation='relu',\n kernel_initializer=init)\n\n x = sexto_layer(x)\n\n # otra vieja confiable\n septimo_layer = tf.layers.Dense(units=84, activation='relu',\n kernel_initializer=init)\n\n x = septimo_layer(x)\n\n # una ultima capa sin activacion no se porque putas\n # https://stackoverflow.com/questions/44540769/tensorflow-cnn-dense-\n # layer-as-softmax-layer-input\n # aqui recomiendan hacerlo aparte como si eso fuera chistoso, pero es\n # porque la vieja quiere mostrar el resultado sin aplicarle el softmax\n # para ver los numeritos feitos\n ultimo_layer_sin_activacion = tf.layers.Dense(units=10,\n kernel_initializer=init)\n\n x = ultimo_layer_sin_activacion(x)\n\n ultimo_layer_con_softmax = tf.nn.softmax(x)\n\n # toca definir el loss para retornarlo\n loss = tf.losses.softmax_cross_entropy(y, x)\n\n # como se optimiza la enseñanza del bb\n optimizer = tf.train.AdamOptimizer().minimize(loss)\n\n # el accuracy\n pred = tf.argmax(x, 1)\n eq = tf.equal(pred, tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(eq, tf.float32))\n\n return ultimo_layer_con_softmax, optimizer, loss, accuracy\n","sub_path":"supervised_learning/0x07-cnn/4-lenet5.py","file_name":"4-lenet5.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"369741222","text":"# Sample code from the TorchVision 0.3 Object Detection Finetuning Tutorial\n# http://pytorch.org/tutorials/intermediate/torchvision_tutorial.html\n\nimport os\nimport numpy as np\nimport torch\nfrom PIL import Image\n\nimport torchvision\nfrom torchvision.models.detection.faster_rcnn import FastRCNNPredictor\nfrom torchvision.models.detection.mask_rcnn import MaskRCNNPredictor\n\nimport sys\nsys.path.append(\"./detection\")\nfrom engine import train_one_epoch, evaluate\nimport utils\nimport transforms as T\nimport cv2\nimport cv2_util\n\nimport random\n\n\nclass PennFudanDataset(object):\n def __init__(self, root, transforms):\n self.root = root\n self.transforms = transforms\n # load all image files, sorting them to\n # ensure that they are aligned\n self.imgs = list(sorted(os.listdir(os.path.join(root, \"PNGImages\"))))\n self.masks = list(sorted(os.listdir(os.path.join(root, \"PedMasks\"))))\n\n def __getitem__(self, idx):\n # load images ad masks\n img_path = os.path.join(self.root, \"PNGImages\", self.imgs[idx])\n mask_path = os.path.join(self.root, \"PedMasks\", self.masks[idx])\n img = Image.open(img_path).convert(\"RGB\")\n # note that we haven't converted the mask to RGB,\n # because each color corresponds to a different instance\n # with 0 being background\n mask = Image.open(mask_path)\n\n mask = np.array(mask)\n # instances are encoded as different colors\n obj_ids = np.unique(mask)\n # first id is the background, so remove it\n obj_ids = obj_ids[1:]\n\n # split the color-encoded mask into a set\n # of binary masks\n masks = mask == obj_ids[:, None, None]\n\n # get bounding box coordinates for each mask\n num_objs = len(obj_ids)\n boxes = []\n for i in range(num_objs):\n pos = np.where(masks[i])\n xmin = np.min(pos[1])\n xmax = np.max(pos[1])\n ymin = np.min(pos[0])\n ymax = np.max(pos[0])\n boxes.append([xmin, ymin, xmax, ymax])\n\n boxes = torch.as_tensor(boxes, dtype=torch.float32)\n # there is only one class\n labels = torch.ones((num_objs,), dtype=torch.int64)\n masks = torch.as_tensor(masks, dtype=torch.uint8)\n\n image_id = torch.tensor([idx])\n area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])\n # suppose all instances are not crowd\n iscrowd = torch.zeros((num_objs,), dtype=torch.int64)\n\n target = {}\n target[\"boxes\"] = boxes\n target[\"labels\"] = labels\n target[\"masks\"] = masks\n target[\"image_id\"] = image_id\n target[\"area\"] = area\n target[\"iscrowd\"] = iscrowd\n\n if self.transforms is not None:\n img, target = self.transforms(img, target)\n\n return img, target\n\n def __len__(self):\n return len(self.imgs)\n\n\ndef get_model_instance_segmentation(num_classes):\n # load an instance segmentation model pre-trained pre-trained on COCO\n model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)\n\n # get number of input features for the classifier\n in_features = model.roi_heads.box_predictor.cls_score.in_features\n # replace the pre-trained head with a new one\n model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)\n\n # now get the number of input features for the mask classifier\n in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels\n hidden_layer = 256\n # and replace the mask predictor with a new one\n model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask,\n hidden_layer,\n num_classes)\n\n return model\n\n\ndef get_transform(train):\n transforms = []\n transforms.append(T.ToTensor())\n if train:\n transforms.append(T.RandomHorizontalFlip(0.5))\n return T.Compose(transforms)\n\n\ndef random_color():\n b = random.randint(0,255)\n g = random.randint(0,255)\n r = random.randint(0,255)\n \n return (b,g,r)\n\n\ndef toTensor(img):\n assert type(img) == np.ndarray,'the img type is {}, but ndarry expected'.format(type(img))\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n img = torch.from_numpy(img.transpose((2, 0, 1)))\n return img.float().div(255) # 255也可以改为256\n\n\ndef PredictImg( image, model,device):\n # img, _ = dataset_test[0]\n img = cv2.imread(image)\n result = img.copy()\n dst=img.copy()\n img=toTensor(img)\n\n names = {'0': 'background', '1': 'train'}\n # put the model in evaluati\n # on mode\n model.eval()\n with torch.no_grad():\n prediction = model([img.to(device)])\n\n boxes = prediction[0]['boxes']\n labels = prediction[0]['labels']\n scores = prediction[0]['scores']\n masks=prediction[0]['masks']\n \n m_bOK=False\n for idx in range(boxes.shape[0]):\n if scores[idx] >= 0.8:\n m_bOK=True\n color=random_color()\n mask=masks[idx, 0].mul(255).byte().cpu().numpy()\n thresh = mask\n contours, hierarchy = cv2_util.findContours(\n thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE\n )\n cv2.drawContours(dst, contours, -1, color, -1)\n\n x1, y1, x2, y2 = int(boxes[idx][0]), int(boxes[idx][1]), int(boxes[idx][2]), int(boxes[idx][3])\n name = names.get(str(labels[idx].item()))\n cv2.rectangle(result,(x1,y1),(x2,y2),color,thickness=2)\n cv2.putText(result, text=name, org=(x1, y1+10), fontFace=cv2.FONT_HERSHEY_SIMPLEX, \n fontScale=0.5, thickness=1, lineType=cv2.LINE_AA, color=color)\n\n dst1 = cv2.addWeighted(result, 0.7, dst, 0.3,0)\n\n if m_bOK:\n cv2.imwrite(\"result.png\", dst1)\n cv2.imshow('result', dst1)\n cv2.waitKey()\n cv2.destroyAllWindows()\n \n\ndef main():\n # train on the GPU or on the CPU, if a GPU is not available\n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n # our dataset has two classes only - background and person\n num_classes = 2 # 需要修改种类\n train_num = 1200 # 训练集数目\n # use our dataset and defined transformations\n dataset = PennFudanDataset('PennFudanPed2', get_transform(train=True))\n dataset_test = PennFudanDataset('PennFudanPed2', get_transform(train=False))\n\n # split the dataset in train and test set\n indices = torch.randperm(len(dataset)).tolist()\n dataset = torch.utils.data.Subset(dataset, indices[:train_num]) # 训练集张数\n dataset_test = torch.utils.data.Subset(dataset_test, indices[train_num:]) # 测试集张数\n\n # define training and validation data loaders\n data_loader = torch.utils.data.DataLoader(\n dataset, batch_size=2, shuffle=True, num_workers=4,\n collate_fn=utils.collate_fn) # batch_size\n\n data_loader_test = torch.utils.data.DataLoader(\n dataset_test, batch_size=1, shuffle=False, num_workers=4,\n collate_fn=utils.collate_fn)\n\n # get the model using our helper function\n model = get_model_instance_segmentation(num_classes)\n\n # move model to the right device\n model.to(device)\n\n # construct an optimizer\n params = [p for p in model.parameters() if p.requires_grad]\n optimizer = torch.optim.SGD(params, lr=0.002,\n momentum=0.9, weight_decay=0.0005) # 学习率\n # and a learning rate scheduler\n lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer,\n step_size=3,\n gamma=0.1)\n\n model_without_ddp = model \n # let's train it for 10 epochs\n num_epochs = 5 # 训练次数\n \n for epoch in range(num_epochs):\n # train for one epoch, printing every 10 iterations\n train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq=10)\n # update the learning rate\n lr_scheduler.step()\n # evaluate on the test dataset\n evaluate(model, data_loader_test, device=device)\n\n # utils.save_on_master({\n # 'model': model_without_ddp.state_dict(),\n # 'optimizer': optimizer.state_dict(),\n # 'lr_scheduler': lr_scheduler.state_dict()},\n # os.path.join('./', 'model_{}.pth'.format(epoch)))\n\n utils.save_on_master({\n 'model': model_without_ddp.state_dict()},\n os.path.join('./model/', 'train_seg_model_epoch_5.pth'))\n\n print(\"That's it!\")\n PredictImg(\"3.jpg\", model, device)\n\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"Maskrcnn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"554891649","text":"import urllib.request\nimport json\nimport shutil\nimport tempfile\nimport subprocess\n\nfrom pathlib import Path\nfrom base import BaseTool\n\n\nclass FlexInstaller(BaseTool):\n def download(self, local: Path):\n with urllib.request.urlopen('https://api.github.com/repos/JohnCoates/flexdecrypt/releases/latest') as response:\n info = json.loads(response.read())\n\n url = next(asset['browser_download_url']\n for asset in info['assets'] if asset['name'] == 'flexdecrypt.deb')\n\n with urllib.request.urlopen(url) as response, tmp.open('wb') as fp:\n shutil.copyfileobj(response, fp)\n\n def deploy(self, local: Path):\n remote = '/tmp/flexdecrypt.deb'\n subprocess.call(self.scp(str(local), remote, direction='up'))\n subprocess.call(self.ssh('dpkg', '-i', remote))\n subprocess.call(self.ssh('rm', remote))\n subprocess.call(self.ssh('apt-get', 'install', '-y', 'zip'))\n\n\nif __name__ == \"__main__\":\n import argparse\n import sys\n parser = argparse.ArgumentParser()\n parser.add_argument('port', type=int)\n parser.add_argument('-o', '--output', dest='output', action='store')\n parser.add_argument('-H', '--host', dest='host', action='store')\n parser.add_argument('-u', '--user', dest='user', action='store')\n\n opt = parser.parse_args()\n\n if opt.host and opt.user:\n i = FlexInstaller(opt.port, host=opt.host, user=opt.user)\n else:\n i = FlexInstaller(opt.port)\n\n cwd = Path(tempfile.gettempdir())\n tmp = cwd / 'flexdecrypt.deb'\n sys.stderr.write('downloading latest FlexDecrypt from GitHub\\n')\n i.download(tmp)\n sys.stderr.write('downloaded\\n')\n sys.stderr.write('deploying to iOS\\n')\n i.deploy(tmp)\n sys.stderr.write('done\\n')\n\n\n","sub_path":"backend/fruit/get-flex.py","file_name":"get-flex.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"602932032","text":"import logging\n\nimport numpy as np\nfrom ..geometry import order_channels_by_distance\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_waveforms(rec, neighbors, index, get_score, proj, spike_size,\n n_features, geom, nnt, th):\n\n \"\"\"Extract waveforms from detected spikes\n\n Parameters\n ----------\n recordings: matrix (observations, number of channels)\n Multi-channel recordings\n neighbors: matrix (number of channels, number of channel)\n Neighbors matrix\n index: matrix (number of spikes, 3)\n Spike index matrix, as returned from any of the detectors\n get_score: bool\n Whether or not to calculate scores, if False returns an array with 0s\n proj:\n ?\n spike_size:\n ?\n n_features:\n ?\n n_features:\n ?\n\n Returns\n -------\n score: list\n List with n_channels elements, each element contains the data whose\n main channel is the i channel where i is the index in the list\n clr_index: list\n List with n_channels elements, each element contains the indexes\n for the spikes indicating whether it was a clear spike or not\n spike_times: list\n List with n_channels elements, each element contains the spike time\n\n Notes\n -----\n Le'ts consider a single channel recording V, where V is a vector of\n length 1 x T. When a spike is detected at time t, then (V_(t-R),\n V_(t-R+1), ..., V_t, V_(t+1),...V_(t+R)) is going to be a waveform.\n (a small snippet from the recording around the spike time)\n \"\"\"\n # column ids for index matrix\n SPIKE_TIME, MAIN_CHANNEL = 0, 1\n\n R = spike_size\n _, n_channels = rec.shape\n score = list()\n clr_idx = list()\n spike_time = list()\n\n # loop over every channel\n for c in range(n_channels):\n\n # get spikes whose main channel is the current channel\n idx = index[:, MAIN_CHANNEL] == c\n\n # check if there is at least one spike for the current channel\n nc = np.sum(idx)\n\n # get the indices for channel c neighbors\n (ch_idx, ) = np.where(neighbors[c])\n\n # if there are spikes for channel c, process them...\n if nc > 0:\n\n # get spike times\n spike_time_c = index[idx, SPIKE_TIME]\n\n # append to spike_times\n spike_time.append(spike_time_c)\n\n if get_score == 1:\n # get waveforms\n wf = np.zeros((nc, 2*R+1, ch_idx.shape[0]))\n\n for j in range(nc):\n wf[j] = rec[spike_time_c[j]+np.arange(-R, R+1)][:, ch_idx]\n\n temp, c_order = order_channels_by_distance(c, ch_idx, geom)\n clr_idx_c = nnt.nn_triage(wf[:,:,c_order], th)\n nc_clear = np.sum(clr_idx_c)\n\n else:\n nc_clear = 0\n\n if nc_clear > 0:\n clr_idx.append(np.where(clr_idx_c)[0])\n\n # get score\n wf = wf[clr_idx_c]\n score.append(np.swapaxes(np.matmul(np.reshape(np.swapaxes(wf, 1, 2), (-1, 2*R+1)), proj)\n .reshape((wf.shape[0], wf.shape[2], -1)), 1, 2))\n else:\n logger.debug('Spikes detected with main channel {c}, '\n 'but get_score is False, returning zeros in '\n 'score and clr_idx...'.format(c=c))\n clr_idx.append(np.zeros(0, 'int32'))\n score.append(np.zeros((0, n_features, np.sum(ch_idx))))\n\n # otherwise return zeros...\n else:\n logger.debug('No spikes detected with main channel {c}, '\n 'returning zeros...'.format(c=c))\n spike_time.append(np.zeros(0, 'int32'))\n clr_idx.append(np.zeros(0, 'int32'))\n score.append(np.zeros((0, n_features, np.sum(ch_idx))))\n\n return score, clr_idx, spike_time\n","sub_path":"src/yass/preprocess/waveform.py","file_name":"waveform.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"596189821","text":"import sqlalchemy as sa\nfrom .base import metadata\nimport datetime\n\nchats = sa.Table(\n \"chats\", \n metadata,\n\n sa.Column(\"db_id\", sa.Integer, primary_key=True, unique=True),\n sa.Column(\"id\", sa.Integer, index=True, unique=True, nullable=False),\n sa.Column(\"username\", sa.String, default=None),\n sa.Column(\"title\", sa.String, nullable=False),\n sa.Column(\"invite_link\", sa.String),\n\n sa.Column(\"is_banned\", sa.Boolean, default=False),\n\n # Data\n sa.Column(\"is_parse_smoothie\", sa.Boolean, default=False),\n\n sa.Column(\"created_at\", sa.DateTime, default=datetime.datetime.utcnow),\n sa.Column(\"updated_at\", sa.DateTime, default=datetime.datetime.utcnow)\n)","sub_path":"src/support/db/chats.py","file_name":"chats.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"411017976","text":"\n# This function s called within the function latLonToExif. It converts a float representing a GPS latitude or longitude value\n# in the degrees decimal minutes format to degrees minutes seconds format and returns the three\n# values in a list.\n# e.g 5258.674 is 52 degrees 58.674 minutes. This converts to 52 degrees 58 minutes 40.44 seconds.\n# The returned list is [52,58,40.44]. Note seconds will be rounded to 2 decimal points. This may\n# introduce error into the final result. This may have to be corrected in after testing \ndef GGA_latLonToDegMinSec(latLon):\n \n decimalMinutes = round(latLon%100,3)\n #print(\"decimalMinutes: \")\n #print(decimalMinutes)\n degrees = int((latLon-decimalMinutes)/100)\n #print(\"dergees: \")\n #print(degrees)\n degDecMin= [degrees,decimalMinutes]\n #print(\"degDecMin: \")\n #print(degDecMin) \n return degDecMin\n\n# This function takes an NMEA GGA lat/lon string DDMM.m (degrees and decimal minutes) \n# and converts it to a string that is in Exif format 'Degrees/1,Minutes/1,Seconds/100'\n# e.g 5852.674 will be returned as '58/1,52/1,4044/100'\n#\ndef latLonToExif(latLonString):\n latLon = float(latLonString)\n if(latLon < 0):\n latLon*=-1\n degDecMin = GGA_latLonToDegMinSec(latLon)\n degrees = str(degDecMin[0])\n dec_min = str(degDecMin[1]) \n exifLatLon = degrees+\",\"+dec_min\n #exifLatLon = degrees+' deg '+minutes+'\\' '+seconds+'\\'\\' '\n return exifLatLon\n\n\n\n\n#This function takes a datetime.time(h,m,s) object and converts it into a unix timestamp string\n# of the form \"hh:mm:ss\". i.e datetime.time(11,34,28) -> '11:34:28' \ndef gpsTimeToExif(datetime):\n \n utc_string = str(datetime.hour)+':'+str(datetime.minute)+':'+str(datetime.second) \n return utc_string \n\n","sub_path":"gpsToExif.py","file_name":"gpsToExif.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"378457007","text":"#import numpy as np\n#import cv2\n#\n# # Read the main image\n#\n#inputImage = cv2.imread(\"messi.png\")\n#\n# # Convert it to grayscale\n#\n#inputImageGray = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)\n#\n# # Line Detection\n#\n#edges = cv2.Canny(inputImageGray,100,200,apertureSize = 3)\n#\n#minLineLength = 500 \n#maxLineGap = 5 \n#\n#lines = cv2.HoughLinesP(edges,1,np.pi/180,90,minLineLength,maxLineGap)\n#\n#for x in range(0, len(lines)):\n# for x1,y1,x2,y2 in lines[x]:\n# cv2.line(inputImage,(x1,y1),(x2,y2),(0,128,0),2)\n#\n##cv2.putText(inputImage,\"Tracks Detected\", (500,250), font, 0.5, 255)\n#\n# # Show result\n# \n#cv2.imwrite('messi_result.png',inputImage)\n##cv2.imshow(\"Trolley_Problem_Result\", inputImage)\n#\n#\n\n\n\n\n\n\n\t\nimport numpy as np \nimport cv2\n\ninputImage = cv2.imread(\"messi.png\")\ninputImageGray = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(inputImageGray,150,200,apertureSize = 3)\nminLineLength = 30\nmaxLineGap = 5\nlines = cv2.HoughLinesP(edges,cv2.HOUGH_PROBABILISTIC, np.pi/180, 30, minLineLength,maxLineGap)\nfor x in range(0, len(lines)):\n for x1,y1,x2,y2 in lines[x]:\n #cv2.line(inputImage,(x1,y1),(x2,y2),(0,128,0),2, cv2.LINE_AA)\n pts = np.array([[x1, y1 ], [x2 , y2]], np.int32)\n cv2.polylines(inputImage, [pts], True, (0,255,0))\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\ncv2.putText(inputImage,\"Tracks Detected\", (500, 250), font, 0.5, 255)\ncv2.imwrite('final.png',inputImage)\ncv2.imshow(\"Trolley_Problem_Result\", inputImage)\n#cv2.imshow('edge', edges)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n","sub_path":"python code/Hough.py","file_name":"Hough.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"497917833","text":"# Filename: Program5-20.py\r\n# Author: N. Anim\r\n# Date: Mar. 7, 2016\r\n# Purpose: To demonstarte the use and functioning of a counter\r\n# (or for) loop.\r\n# The algorithm is in Figure 5-21.\r\n# This script demonstrates the use of nested loops.\r\n# This particular script simulates a clock.\r\n\r\n\r\n\r\n# The hours loop\r\nhours = 0\r\nwhile (hours < 24):\r\n minutes = 0\r\n while (minutes < 60):\r\n seconds = 0\r\n while (seconds < 60):\r\n print(hours,':',minutes,':',seconds)\r\n seconds += 1\r\n minutes += 1\r\n hours += 1\r\n\r\n","sub_path":"Programs/Program5-20.py","file_name":"Program5-20.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"373625548","text":"\n\n# Make and run OASN files for varying discrete source locations. \n# To Do: define bottom paramters and intervals\n# define outFileName\n# define water sound speed layers\n# input settings for each block\n\n\nimport numpy as np\nimport types\nimport os\nimport subprocess\nimport time\nimport random\n\n\n# define options\noptions = 'N J 0'\n\n# define frequencies\nfreqs = np.array([109,109,1,0]) # [min freq, max freq, # of freqs, integration contour offset]\n#9m dpeth: 109 163 232 385\n#54m depth:112 148 201 283\n# define sound speed layers\nsspfile=\"swellex_ssp.csv\"\n\nlayers = np.loadtxt(sspfile, delimiter=\",\") # import ssp for envrironment from file\n\n#roughness_layer = 3\n#roughness_param = [-0.2, 19.1, 2.5]\n\n# define array\narrayfile=\"vla_array.csv\"\n\narray = np.loadtxt(arrayfile, delimiter=\",\") # import ssp for envrironment from file\n\narray_temp1 = [int(inc) for inc in array[:,3]]\narray_temp2 = [int(inc) for inc in array[:,4]]\n\narr = np.ndarray(array.shape,dtype = object)\narr[:,0:3] = array[:,0:3]\narr[:,3] = array_temp1\narr[:,4] = array_temp2\n\n\n# define sources\nsrc = types.SimpleNamespace()\n\nsrc.src = np.array([0, 0, 0, 1]) # [surf. noise src strength, white noise level, deep src level, # of discr. srcs]\n\nif src.src[0] != 0: #if there is sea surface noise\n src.seacs = np.array([1400,1e8]) # [cmins, cmaxs]\n src.seawav = np.array([400,400,100]) # [samples in cont., discr, evanes.]\n\nif src.src[2] != 0: #if there is deep noise source\n src.dscs = np.array([1400,1e8]) # [cmins, cmaxs]\n src.dswav = np.array([400,400,100]) # [samples in cont., discr, evanes.]\n \nif src.src[3] != 0: #if there is discrete source\n # [depth(m), x-coord(km), y-coord(km), source level]\n src_ycoor = 0\n src_xcoor = np.linspace(0,10,1001)\n src_zcoor = 9 #54\n src_level = 155\n \n src.ndcs = np.array([1300,1600]) # [cmins, cmaxs]\n src.ndwav = np.array([-1,0,0]) # [# of sampling points,first sampling point, last sampling point]; [-1,0,0] for auto\n \n #repeat for each discrete source\n \n# define signal replicas \n\nif 'R' in options:\n reps = types.SimpleNamespace()\n\n reps.zs = np.array([50,50,1]) # depths of sampling of replicas\n reps.xs = np.array([1,1,1]) # x-coord of sampling \n reps.ys = np.array([0,0,1]) # y-coord of sampling\n\n reps.cvals = np.array([1400,1e8]) # [cmins, cmaxs]\n reps.wavs = np.array([-1,0,0]) # [# of sampling points,first sampling point, last sampling point]; [-1,0,0] for auto\n\nii = 0\n\n# define function to write a line\ndef line(var):\n s = ''\n for ii in range(len(var)):\n sii = '{'+str(ii)+'} '\n s = ''.join([s,sii])\n return s[0:-1].format(*var)\n\n\n### start writing input files\nallDirs = []\n\nfor ii in range(src_xcoor.shape[0]): # for each source location\n for jj in range(1): # create 30 small random perturbations to the location\n \n outFileName = str(round(src_xcoor[ii],2)) + 'km' + '.dat'\n\n if not os.path.isdir(outFileName[0:-4]):\n os.mkdir(outFileName[0:-4])\n\n allDirs.append(outFileName[0:-4])\n\n outFile = open(outFileName[0:-4] + '/' + outFileName, 'w')\n\n # Begin writing file:\n\n # Block 1: Title\n outFile.write('ICEX_32array ' + outFileName[0:-4] + '\\n')\n\n # Block 2: Options\n outFile.write(options + '\\n')\n\n # Block 3: Frequencies\n outFile.write(line(freqs) + '\\n')\n\n outFile.write('\\n')\n\n # Block 4: Environment\n\n #number of layers\n outFile.write(str(layers.shape[0]) + '\\n')\n\n #environment layers\n layers[np.isnan(layers)] = 0.\n\n for kk in range(layers.shape[0]):\n outFile.write(line(layers[kk,:]) + '\\n')\n \n\n outFile.write('\\n')\n\n # Block 5: Array\n outFile.write(str(arr.shape[0]) + '\\n')\n for irec in range(arr.shape[0]):\n outFile.write(line(arr[irec,:]) + '\\n') \n\n outFile.write('\\n')\n\n # Block 6: Sources\n outFile.write(line(src.src) + '\\n')\n \n outFile.write('\\n')\n\n # Block 7: Sea Surface\n if src.src[0] != 0: #if there is sea surface noise\n outFile.write(line(src.seacs) + '\\n')\n outFile.write(line(src.seawav) + '\\n')\n \n outFile.write('\\n')\n\n # Block 8: Deep Noise\n if src.src[2] != 0: #if there is deep noise source\n outFile.write(line(src.dscs) + '\\n')\n outFile.write(line(src.dswav) + '\\n')\n \n outFile.write('\\n') \n \n # Block 9: Discrete Sources\n if src.src[3] != 0: #if there is discrete source \n disc_src = np.array([src_zcoor,src_xcoor[ii],src_ycoor,src_level])\n outFile.write(line(disc_src) + '\\n')\n outFile.write(line(src.ndcs) + '\\n')\n outFile.write(line(src.ndwav) + '\\n')\n\n outFile.write('\\n')\n\n # Block 10: Signal replicas\n if 'R' in options:\n outFile.write(line(reps.zs[0:-1]) + ' ' + str(int(reps.zs[-1])) + '\\n')\n outFile.write(line(reps.xs[0:-1]) + ' ' + str(int(reps.xs[-1])) + '\\n')\n outFile.write(line(reps.ys[0:-1]) + ' ' + str(int(reps.ys[-1])) + '\\n')\n\n outFile.write('\\n')\n\n outFile.write(line(reps.cvals) + '\\n')\n outFile.write(line(reps.wavs) + '\\n')\n\n\n# Run OASN\n\nbaseDir = os.getcwd()\n\nos.chdir(baseDir)\nif not os.path.isdir('chk_files'):\n os.mkdir('chk_files')\n\nproc_list = []\nlogs = []\n\n# print('Checking for OASN')\noasn_check = subprocess.Popen('which oasn'.split())\noasn_check.wait()\n\n# print(str(oasn_check.poll()==0))\n# print(str(oasn_check.poll()))\n\nif oasn_check.returncode == 0:\n print('OASN found!')\n for ii in range(len(allDirs)):\n os.chdir(baseDir + '/' + allDirs[ii])\n \n logs = open('oasn_log_'+str(ii+1)+'.txt','w')\n print(('oasn {'+str(ii)+'}').format(*allDirs))\n proc = subprocess.Popen(('oasn {'+str(ii)+'}').format(*allDirs).split(),stdout=logs,stderr=logs)\n proc.wait()\n print(' Return code: ' + str(proc.returncode))\n\n if not proc.returncode == 0:\n print('Trying once more: ')\n\n print(('oasn {'+str(ii)+'}').format(*allDirs))\n proc = subprocess.Popen(('oasn {'+str(ii)+'}').format(*allDirs).split(),stdout=logs,stderr=logs)\n proc.wait()\n print(' Return code: ' + str(proc.returncode))\n\t\n if proc.returncode == 0:\n os.rename(baseDir + '/' + allDirs[ii] + '/' + allDirs[ii] + '.chk', baseDir + '/chk_files/' + allDirs[ii] + '.chk')\n\n logs.close()\n time.sleep(0.05)\n\n \nos.chdir(baseDir)\nprint('Done!')\n\n\n","sub_path":"swellex/varysrc_gen_files.py","file_name":"varysrc_gen_files.py","file_ext":"py","file_size_in_byte":6669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"494139689","text":"import os, random, time, copy\nimport numpy\nimport os.path as path\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.optim import lr_scheduler \nimport torchvision\nfrom torchvision import datasets, models, transforms\nimport pickle\nimport pathlib\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\nfrom zplib.curve import interpolate\nfrom zplib.image import pyramid\nfrom keypoint_annotation import keypoint_annotation_model\nimport elegant\nfrom elegant import worm_spline\n#since all the worms will be in the same orientation/worm pixels, hardcode in a worm_frame_mask\ndef to_tck(widths):\n x = numpy.linspace(0, 1, len(widths))\n smoothing = 0.0625 * len(widths)\n return interpolate.fit_nonparametric_spline(x, widths, smoothing=smoothing)\n\ndef get_avg_widths():\n elegant_path = pathlib.Path(elegant.__file__)\n width_trends_path = elegant_path.parent /'width_data/width_trends.pickle'\n WIDTH_TRENDS = pickle.load(open(width_trends_path,'rb'))\n AVG_WIDTHS = numpy.array([numpy.interp(5, WIDTH_TRENDS['ages'], wt) for wt in WIDTH_TRENDS['width_trends']])\n AVG_WIDTHS_TCK = to_tck(AVG_WIDTHS)\n return AVG_WIDTHS_TCK\n\n\"\"\"WIDTH_TRENDS = pickle.load(open('/home/nicolette/.conda/envs/nicolette/lib/python3.7/site-packages/elegant/width_data/width_trends.pickle', 'rb'))\nAVG_WIDTHS = numpy.array([numpy.interp(5, WIDTH_TRENDS['ages'], wt) for wt in WIDTH_TRENDS['width_trends']])\nAVG_WIDTHS_TCK = to_tck(AVG_WIDTHS)\"\"\"\n\nAVG_WIDTHS_TCK = get_avg_widths()\n\n\nclass LossofRegmentation(nn.Module):\n def __init__(self, downscale=2, scale=(0,1,2,3), image_shape=(960,512), mask_error=True):\n super(LossofRegmentation, self).__init__()\n self.scale = scale\n self.reglLoss = nn.L1Loss(reduction='sum')\n #self.segLoss = nn.BCELoss(reduction='sum')\n self.downscale = downscale\n image_size = (int(image_shape[0]/downscale), int(image_shape[1]/downscale))\n widths_tck = (AVG_WIDTHS_TCK[0], AVG_WIDTHS_TCK[1]/downscale, AVG_WIDTHS_TCK[2])\n mask = worm_spline.worm_frame_mask(widths_tck, image_size) #make worm mask for training\n self.mask = mask\n self.mask_error = mask_error\n\n def forward(self, Keypoint0, Output):\n \n K0loss = 0 \n ##image1 mask image2 output\n for i in self.scale: \n s = 2**i \n N,C,H,W = Keypoint0[i].size()\n scaled_mask = pyramid.pyr_down(self.mask, downscale=s)\n m = numpy.array([[scaled_mask]*C]*N) #get mask into the same dimension as keypoint should be (N, 1, H, W)\n tensor_mask = torch.tensor(m) #make the mask into a tensor\n if self.mask_error:\n l = self.reglLoss(Output[('Keypoint0',i)][tensor_mask>0], Keypoint0[i][tensor_mask>0])/(N*C*H*W)\n else:\n l = self.reglLoss(Output[('Keypoint0',i)], Keypoint0[i])/(N*C*H*W)\n print('Loss: {}, scale: {}'.format(l, i))\n K0loss += l\n\n return K0loss\n\n\ndef training_wrapper(dataloaders, dataset_sizes, loss_1_to_2, base_lr = 0.0001 ,scale=[0,1,2,3], \n start_epo = 0, total_epoch_nums=25, work_dir='./', device='cpu'):\n\n log_filename = os.path.join(work_dir,'train.log') \n for i, keypoint in enumerate(['ant_pharynx', 'post_pharynx', 'vulva_kp', 'tail']):\n #for i, keypoint in enumerate(['post_pharynx', 'vulva_kp']):\n since = time.time()\n curr_time = datetime.now()\n print('------------------------{} Training {} ------------------------'.format(curr_time, keypoint))\n print('base_lr: {}\\t scale: {}\\t start_epo: {}\\t total_epoch_nums: {}\\t device: {}\\t work_dir: {}\\t'.format(\n base_lr, scale, start_epo, total_epoch_nums, device, work_dir))\n print('dataloader sizes: {}:{}\\t {}:{}\\t'.format('train', dataset_sizes['train'], 'val', dataset_sizes['val']))\n fn = open(log_filename, 'a')\n fn.write('------------------------{} Training {} ------------------------\\n'.format(curr_time, keypoint))\n #fn.write('base_lr: {}\\t scale: {}\\t start_epo: {}\\t total_epoch_nums: {}\\t device: {}\\t work_dir: {}\\n'.format(\n # base_lr, scale, start_epo, total_epoch_nums, device, work_dir))\n fn.write('dataloader sizes: {}:{}\\t {}:{}\\n'.format('train', dataset_sizes['train'], 'val', dataset_sizes['val']))\n fn.close()\n #initialize model\n initModel = keypoint_annotation_model.WormRegModel(34, scale, pretrained=True)\n initModel.to(device)\n #define loss function\n loss_1_to_2 = loss_1_to_2\n optimizer = torch.optim.Adam([{'params': initModel.parameters()}], lr=base_lr)\n exp_lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=int(total_epoch_nums/10), gamma=0.5)\n\n #train the model\n model_ft = train_reg(initModel, dataloaders, dataset_sizes, loss_1_to_2, optimizer, exp_lr_scheduler, i, keypoint, \n start_epo=0, num_epochs=total_epoch_nums, work_dir=work_dir, device=device)\n\n print('----------------------------------------------------------------------------')\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n \n fn = open(log_filename,'a')\n fn.write('Training complete in {:.0f}m {:.0f}s\\n'.format(time_elapsed // 60, time_elapsed % 60))\n fn.close()\n\ndef train_reg(model, dataloaders, dataset_sizes, loss_1_to_2, optimizer, scheduler, \n keypoint_idx, keypoint_name, start_epo = 0, num_epochs=25, work_dir='./', device='cpu'):\n \n save_dir = os.path.join(work_dir, keypoint_name)\n if not os.path.exists(save_dir): os.makedirs(save_dir)\n\n log_filename = os.path.join(save_dir,'train.log') \n since = time.time()\n\n best_model_wts = copy.deepcopy(model.state_dict())\n best_loss = float('inf')\n\n for epoch in range(start_epo ,num_epochs): \n print('\\nEpoch {}/{}'.format(epoch+1, num_epochs))\n print('-' * 10)\n fn = open(log_filename,'a')\n fn.write('\\nEpoch {}/{}\\n'.format(epoch+1, num_epochs))\n fn.write('--'*5+'\\n')\n fn.close()\n\n \n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n print(phase)\n fn = open(log_filename,'a') \n fn.write(phase+'\\n')\n fn.close()\n \n if phase == 'train':\n model.train() # Set model to training mode\n else: model.eval() # Set model to evaluate mode\n\n #running_loss, running_lossk0, running_lossk1, running_lossk2, running_lossk3 = 0.0, 0.0, 0.0, 0.0, 0.0\n running_loss, running_lossk0, running_acc = 0.0, 0.0, 0.0\n\n # Iterate over data.\n img, keypoint_maps, out = None, None, None\n iterCount,sampleCount = 0, 0\n for sample in dataloaders[phase]:\n img, keypoint_maps = sample \n keypoint0 = keypoint_maps[keypoint_idx] \n img = img.to(device)\n for i in range(len(keypoint0)):\n keypoint0[i] = keypoint0[i].to(device)\n #keypoint1[i] = keypoint1[i].to(device)\n #keypoint2[i] = keypoint2[i].to(device)\n #keypoint3[i] = keypoint3[i].to(device)\n \n \n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n # track history if only in train \n with torch.set_grad_enabled(phase=='train'):\n if phase=='train': # backward + optimize only if in training phase\n model.train() \n output = model(img) \n k0loss = loss_1_to_2(keypoint0, output)\n loss = k0loss\n loss.backward()\n optimizer.step()\n acc = accuracy([keypoint0[0]], output)\n \n else: \n model.eval() \n output = model(img) \n k0loss = loss_1_to_2(keypoint0, output)\n loss = k0loss\n acc = accuracy([keypoint0[0]], output)\n\n # statistics \n iterCount += 1\n sampleCount += img.size(0) \n running_loss += loss.item() * img.size(0) \n running_lossk0 += k0loss.item() * img.size(0)\n running_acc += acc\n #running_lossk1 += k1loss.item() * img.size(0)\n #running_lossk2 += k2loss.item() * img.size(0) \n #running_lossk3 += k3loss.item() * img.size(0)\n accprint2screen_avgLoss = running_acc/sampleCount\n k0print2screen_avgLoss = running_lossk0/sampleCount\n #k1print2screen_avgLoss = running_lossk1/sampleCount\n #k2print2screen_avgLoss = running_lossk2/sampleCount\n #k3print2screen_avgLoss = running_lossk3/sampleCount\n print2screen_avgLoss = running_loss/sampleCount\n \n if iterCount%50==0:\n print('\\t{}/{} loss: {:.4f} \\t k0loss: {:.4f}\\t acc: {:.4f}'.format(iterCount, len(dataloaders[phase]), print2screen_avgLoss, k0print2screen_avgLoss, accprint2screen_avgLoss))\n fn = open(log_filename,'a') \n fn.write('\\t{}/{} loss: {:.4f} \\t k0loss: {:.4f}\\t acc: {:.4f}\\n'.format(iterCount, len(dataloaders[phase]), print2screen_avgLoss, k0print2screen_avgLoss, accprint2screen_avgLoss))\n fn.close()\n \n epoch_loss = running_loss / dataset_sizes[phase]\n k0epoch_loss = running_lossk0 / dataset_sizes[phase]\n accepoch_loss = running_acc / dataset_sizes[phase]\n #k1epoch_loss = running_lossk1 / dataset_sizes[phase]\n #k2epoch_loss = running_lossk2 / dataset_sizes[phase]\n #k3epoch_loss = running_lossk3 / dataset_sizes[phase]\n \n print('\\tloss: {:.6f} \\tk0loss: {:.6f}\\t acc: {:.6f}'.format(epoch_loss, k0epoch_loss, accepoch_loss))\n fn = open(log_filename,'a')\n fn.write('\\tloss: {:.6f} \\tk0loss: {:.6f} acc: {:.6f}\\n'.format(epoch_loss, k0epoch_loss, accepoch_loss))\n fn.close()\n \n keypoint_maps = [keypoint0[0]]\n\n plot_output(img, keypoint_maps, output, epoch, phase, save_dir)\n \n # deep copy the model\n cur_model_wts = copy.deepcopy(model.state_dict())\n path_to_save_paramOnly = os.path.join(save_dir, 'epoch-{}.paramOnly'.format(epoch+1))\n torch.save(cur_model_wts, path_to_save_paramOnly)\n \n if phase=='val' and epoch_loss0\n print(mask.shape)\n #mask = numpy.array([[mask]*C]*N) #get mask into the same dimension as keypoint should be (N, 1, H, W)\n\n for sampleIndex in range(len(keypoint_maps[0])):\n kp_map = keypoint_maps[0][sampleIndex].cpu().numpy()\n gt = kp_map[0]\n gt[~mask] = -1 #since we don't care about things outside of the worm pixels, set everything outside to -1\n gt_kp = numpy.unravel_index(numpy.argmax(gt), gt.shape)\n #gt_kp = numpy.where(gt == numpy.max(gt[mask]))\n\n out_kp_map = out[('Keypoint0',0)][sampleIndex].cpu().detach().numpy()\n pred = out_kp_map[0]\n pred[~mask] = -1 #since we don't care about things outside of the worm pixels, set everything outside to -1\n #out_kp = numpy.where(pred == numpy.max(pred[mask]))\n out_kp = numpy.unravel_index(numpy.argmax(pred), pred.shape)\n\n #dist = numpy.sqrt((gt_kp[0][0]-out_kp[0][0])**2 + (gt_kp[1][0]-out_kp[1][0])**2)\n dist = numpy.sqrt((gt_kp[0]-out_kp[0])**2 + (gt_kp[1]-out_kp[1])**2)\n print(\"GT: {}, Out: {}, dist: {:.0f} \".format(gt_kp, out_kp, dist))\n acc += dist\n print(\"avg acc: \", acc/N)\n return acc\n\n\ndef plot_output(imgList, keypoint_maps, out, epoch, phase, save_dir='./'):\n figWinNumHeight, figWinNumWidth, subwinCount = 4, 4, 1\n plt.figure(figsize=(22,20), dpi=88, facecolor='w', edgecolor='k') # figsize -- inch-by-inch\n plt.clf()\n print(imgList.min())\n print(imgList.max())\n acc = 0\n N,C,H,W = keypoint_maps[0].size()\n print(N,C,H,W)\n s = int(960/H)#get the mask\n widths_tck = (AVG_WIDTHS_TCK[0], AVG_WIDTHS_TCK[1]/s, AVG_WIDTHS_TCK[2])\n mask = worm_spline.worm_frame_mask(widths_tck, (H, W)) #make worm mask\n mask = mask>0\n\n\n for sampleIndex in range(min(4, len(imgList))):\n # visualize image\n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n image = imgList[sampleIndex].cpu().numpy()#.squeeze().transpose((1,2,0)) \n plt.imshow(image[0], cmap='gray') \n plt.axis('off')\n plt.title('Image of worm')\n \n #keypoint 0\n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = keypoint_maps[0][sampleIndex].cpu().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(0)+\" GT\")\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint0',0)][sampleIndex].cpu().detach().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(0))\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint0',0)][sampleIndex].cpu().detach().numpy()\n per50 = numpy.percentile(kp_map[0], 50)\n kp_map[0][~mask] = 0\n \n plt.imshow((kp_map[0]>per50).astype(numpy.float32)*1, cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(0))\n\n \"\"\"#Keypoint 1\n \n subwinCount+=1\n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = keypoint_maps[1][sampleIndex].cpu().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(1)+\" GT\")\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint1',0)][sampleIndex].cpu().detach().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(1))\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint1',0)][sampleIndex].cpu().detach().numpy()\n per90 = numpy.percentile(kp_map[0], 95)\n \n plt.imshow((kp_map[0]>per90).astype(numpy.float32)*1, cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(1))\n \n #Keypoint 2 \n subwinCount+=1\n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = keypoint_maps[2][sampleIndex].cpu().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(2)+\" GT\")\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint2',0)][sampleIndex].cpu().detach().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(2))\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint2',0)][sampleIndex].cpu().detach().numpy()\n per90 = numpy.percentile(kp_map[0], 95)\n \n plt.imshow((kp_map[0]>per90).astype(numpy.float32)*1, cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(2))\n \n #keypoint 3\n subwinCount+=1\n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = keypoint_maps[3][sampleIndex].cpu().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(3)+\" GT\")\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint3',0)][sampleIndex].cpu().detach().numpy()#.squeeze().transpose((1,2,0))\n plt.imshow(kp_map[0], cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(3))\n \n plt.subplot(figWinNumHeight,figWinNumWidth,subwinCount)\n subwinCount += 1\n kp_map = out[('Keypoint3',0)][sampleIndex].cpu().detach().numpy()\n per90 = numpy.percentile(kp_map[0], 95)\n \n plt.imshow((kp_map[0]>per90).astype(numpy.float32)*1, cmap='jet')\n plt.axis('on')\n plt.colorbar()\n plt.title('Keypoint '+str(3))\"\"\"\n \n\n\n save_path = os.path.join(save_dir, ('epoch '+str(epoch)+' output '+phase+'.png'))\n plt.savefig(save_path)\n plt.close()","sub_path":"keypoint_annotation/keypoint_training.py","file_name":"keypoint_training.py","file_ext":"py","file_size_in_byte":21237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"587531924","text":"from models.resnet import resnet18\nfrom data_loader.data_loader import LMDBDataSet\nimport torch.nn as nn\nimport torch\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom models.gan_resnet import ResNetEncoder64x64, ResNetGenerator64x64, ResNetPixelDiscriminator64x64, ResNetDiscriminator64x64\nfrom models.loss import LossManager, ganBCELoss, reconstructionL1Loss\nfrom collections import OrderedDict\nimport numpy as np\nfrom tqdm import tqdm\nclass CustomResnetModel(nn.Module):\n def __init__(self, n_channels):\n super(CustomResnetModel, self).__init__()\n self.resnet = resnet18(pretrained=False, progress=True, num_classes=2, in_channels=n_channels)\n \n def forward(self, images):\n return self.resnet(images)\nclass CustomModel(nn.Module):\n def __init__(self, n_channels):\n super(CustomModel, self).__init__()\n self.net = nn.Sequential(\n nn.Conv2d(n_channels, 32, 7, padding=3),\n nn.ReLU(),\n nn.BatchNorm2d(32),\n nn.Dropout(0.3),\n nn.Conv2d(32, 64, 5,padding=2),\n nn.ReLU(),\n nn.BatchNorm2d(64),\n\n nn.Conv2d(64, 64, 5,padding=2),\n nn.ReLU(),\n nn.BatchNorm2d(64),\n nn.MaxPool2d(3),\n\n nn.Conv2d(64, 128, 5,padding=2),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n nn.Dropout(0.3),\n nn.Conv2d(128, 128, 5,padding=2),\n nn.ReLU(),\n nn.BatchNorm2d(128),\n nn.MaxPool2d(3),\n\n nn.Conv2d(128, 256, 3,padding=1),\n nn.ReLU(),\n nn.BatchNorm2d(256),\n nn.Dropout(0.3),\n nn.Conv2d(256, 256, 3,padding=1),\n nn.ReLU(),\n nn.BatchNorm2d(256),\n nn.MaxPool2d(3),\n\n nn.Conv2d(256, 256, 2),\n nn.ReLU(),\n nn.BatchNorm2d(256),\n nn.Conv2d(256, 2, 1)\n\n\n )\n def forward(self, images):\n result = self.net(images)\n return result.view(images.shape[0], -1)\n\nclass ComplexModel(nn.Module):\n def __init__(self, n_channels, state_dim):\n super(ComplexModel, self).__init__()\n self.state_dim = state_dim\n self.encoder = ResNetEncoder64x64(n_channels, state_dim)\n self.generator = ResNetGenerator64x64(n_channels, state_dim)\n self.discriminator = ResNetDiscriminator64x64(n_channels, state_dim)\n self.pixel_discriminator = ResNetPixelDiscriminator64x64(n_channels)\n self.predictor = nn.Sequential(\n nn.Linear(state_dim, 20),\n nn.LeakyReLU(),\n nn.Linear(20, 20),\n nn.LeakyReLU(),\n nn.Linear(20, 2)\n )\n def encode(self, images):\n return self.encoder(images)\n def generate(self, state):\n return self.generator(state)\n def discriminate(self, images, state):\n return self.discriminator(images, state)\n def pixelDiscriminate(self, real_images, fake_images):\n return self.pixel_discriminator(real_images, fake_images)\n def predict(self, state):\n return self.predictor(state)\n def getParams(self):\n discriminator_params = []\n other_params = []\n for net in [self.pixel_discriminator, self.discriminator]:\n if net is not None:\n discriminator_params += list(net.parameters())\n for net in [self.predictor, self.encoder, self.generator]:\n if net is not None:\n other_params += list(net.parameters())\n return discriminator_params, other_params\n\n def generateRandomState(self, batch_size, device, z_mean=0.0, z_var=0.3):\n '''\n Generating gaussian random states\n :param batch_size: (int)\n :param z_mean: (float) default 0.0\n :param z_var: (float) default 0.3\n '''\n random_z = torch.rand(batch_size, self.state_dim).requires_grad_(False)\n random_z = random_z * 2 - 1.0\n return random_z.to(device)\n\ndef computeLoss(inputs, labels, net, criterion):\n predicts = net(inputs)\n loss = criterion(predicts, labels.view(-1))\n _, indices = torch.max(predicts, dim=1)\n accurancy = (indices == labels).sum().float() / labels.shape[0]\n\n return loss, accurancy\ndef trainGan():\n device = \"cuda:0\"\n batch_size = 64\n test_batch_size = 128\n num_epoch = 100\n model = ComplexModel(11, 200).to(device)\n \n # create loss manager\n discrim_loss_history = OrderedDict()\n other_loss_history = OrderedDict()\n discriminator_loss_manager = LossManager(model, loss_history=discrim_loss_history)\n other_loss_manager = LossManager(model, loss_history=other_loss_history)\n best_error = np.inf\n log_folder = \".\"\n best_model_path = \"{}/model.pth\".format(log_folder)\n discriminator_params, other_params = model.getParams()\n \n other_optimizer = torch.optim.Adam(other_params, lr=0.0001, weight_decay=1e-4)\n discriminator_optimizer = torch.optim.Adam(discriminator_params, lr=0.0001, weight_decay=1e-4)\n\n criterion = nn.CrossEntropyLoss().to(device)\n train_dataset = LMDBDataSet(\"dataset/train\", 0.0, 1.0)\n test_dataset = LMDBDataSet(\"dataset/test\", 0.0, 1.0)\n\n train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=4)\n test_loader = DataLoader(test_dataset, batch_size=test_batch_size, num_workers=4)\n\n for epoch in range(num_epoch):\n pbar = tqdm(total=len(train_loader))\n # re-initialize loss manager\n discriminator_loss_manager.newEpoch()\n other_loss_manager.newEpoch()\n for minibatch_num, (inputs, labels) in enumerate(train_loader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n other_optimizer.zero_grad()\n other_loss_manager.resetLosses()\n discriminator_optimizer.zero_grad()\n discriminator_loss_manager.resetLosses()\n\n # generate true, false labels with the correct dimension\n false_label = torch.ones(inputs.size(0), 1, requires_grad=False, device=device)\n true_label = torch.zeros(inputs.size(0), 1, requires_grad=False, device=device)\n # generate the represented state z randomly\n random_state = model.generateRandomState(inputs.size(0), device)\n\n state = model.encode(inputs)\n random_images = model.generate(random_state)\n images_recon = model.generate(state)\n\n pred_labels = model.predict(state)\n\n #### train the discriminator\n # train BiGAN discriminator\n encoder_result = model.discriminate(inputs.detach(), state.detach())\n generator_result = model.discriminator((random_images).detach(), random_state.detach())\n ganBCELoss(encoder_result, generator_result, false_label, true_label, 1.0,\n discriminator_loss_manager, True, name='train_D_loss')\n\n # train comparing discriminator\n real_pixel_result = model.pixelDiscriminate(inputs.detach(),inputs.detach())\n fake_pixel_result = model.pixelDiscriminate(inputs.detach(),images_recon.detach())\n \n ganBCELoss(fake_pixel_result, real_pixel_result, false_label, true_label, 1.0,\n discriminator_loss_manager, True, name='train_pixel_D_recon_loss')\n # backward\n loss_discriminator = discriminator_loss_manager.computeTotalLoss()\n loss_discriminator.backward()\n discriminator_optimizer.step()\n\n #### train the others\n # train G,E by BiGAN\n encoder_result = model.discriminator(inputs.detach(), state)\n generator_result = model.discriminator(random_images, random_state.detach())\n ganBCELoss(encoder_result, generator_result, false_label, true_label, 1.0,\n other_loss_manager, False, name='train_G_E_loss')\n \n fake_pixel_result = model.pixelDiscriminate(inputs.detach(), images_recon)\n \n ganBCELoss(fake_pixel_result,\n None, false_label,\n true_label, 2.0, other_loss_manager, False, name='train_pixel_G_E_recon_loss')\n\n # predict loss\n pred_loss = criterion(pred_labels, labels.view(-1))\n other_loss_manager.addToLosses(\"train_predict_loss\", 10.0, pred_loss)\n # backward\n other_loss = other_loss_manager.computeTotalLoss()\n other_loss.backward(retain_graph=True)\n other_optimizer.step()\n discriminator_loss_manager.updateLossHistory()\n other_loss_manager.updateLossHistory()\n pbar.update(1)\n pbar.close()\n\n # valuation\n with torch.no_grad(): # ensure no grad is computed\n accuracy_total = 0.0\n total_loss = 0.0\n for minibatch_num, (inputs, labels) in enumerate(test_loader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n\n state = model.encode(inputs)\n images_recon = model.generate(state)\n pred_labels = model.predict(state)\n val_loss = reconstructionL1Loss(images_recon, inputs, is_clip=False,\n clip_min_value=0) # + reconstructionL1Loss(next_obs, next_obs_recon)\n other_loss_manager.addToLosses('val_recon_loss', 1.0, val_loss)\n pred_loss = criterion(pred_labels, labels.view(-1))\n other_loss_manager.addToLosses('val_predict_loss', 1.0, pred_loss)\n total_loss = val_loss.data + pred_loss.data\n _, indices = torch.max(pred_labels, dim=1)\n accuracy_total += (indices == labels).sum().float() / labels.shape[0]\n other_loss_manager.updateLossHistory()\n # Save best model\n if total_loss < best_error:\n best_error = total_loss\n torch.save(model.state_dict(), best_model_path)\n # Then we print the results for this epoch:\n print(\"epoch: {}/{}\".format(epoch, num_epoch))\n discriminator_loss_manager.printLoss()\n print()\n other_loss_manager.printLoss()\n print(\"test accuracy: {}\".format(accuracy_total/len(test_loader)))\ndef train():\n device = \"cuda:0\"\n batch_size = 128\n test_batch_size = 256\n num_epoch = 50\n net = CustomModel(11).to(device)\n criterion = nn.CrossEntropyLoss().to(device)\n optimizer = optim.Adam(net.parameters(), lr=0.001, weight_decay=1e-4)\n train_dataset = LMDBDataSet(\"dataset/train\", 0.0, 1.0)\n test_dataset = LMDBDataSet(\"dataset/test\", 0.0, 1.0)\n train_loader = DataLoader(train_dataset, batch_size=batch_size, num_workers=4)\n test_loader = DataLoader(test_dataset, batch_size=test_batch_size, num_workers=4)\n\n\n for epoch in range(num_epoch): # loop over the dataset multiple times\n train_loss = 0.0\n train_accuracy = 0.0\n train_count = 0\n test_loss = 0.0\n test_accuracy = 0.0\n test_count = 0\n # train\n for i, (inputs, labels) in enumerate(train_loader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n # zero the parameter gradients\n optimizer.zero_grad()\n\n loss, accurancy = computeLoss(inputs, labels, net, criterion)\n train_accuracy += accurancy\n train_loss += loss.data\n train_count += 1\n loss.backward()\n optimizer.step()\n # test\n with torch.no_grad():\n for i, (inputs, labels) in enumerate(test_loader):\n inputs = inputs.to(device)\n labels = labels.to(device)\n loss, accurancy = computeLoss(inputs, labels, net, criterion)\n test_accuracy += accurancy\n test_loss += loss.data\n test_count += 1\n print(\"epoch: {}, train loss : {:8f}, train accuracy: {:8f}, test loss : {:8f}, test accuracy: {:8f}\".format(epoch, train_loss/train_count, train_accuracy/train_count, test_loss/test_count, test_accuracy/test_count))\n\n\n\n print('Finished Training')\n\n\nif __name__ == \"__main__\":\n trainGan()","sub_path":"medical_ml/train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":12323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"301331558","text":"first_die = 6\nsecond_die = 4\n\nhighest_sum = first_die + second_die + 1 #12 = 6+6 #í range er talið uppað en ekki með seinustu tölu\nlowest_sum = 2; #1+1\n\nmost_frequent_sum = 0\nlhs = 1\nrhs = 1\n\nmax_counter = [0]\n\nfor current_sum in range(lowest_sum, highest_sum):\n\tcurrent_sum_counter = 0\n\tfor first_die_iterator in range(1, first_die+1): #checka 1-6 í 6 hliða tening samhengi\n\t\tfor second_die_iterator in range(1, second_die+1): #checka 1-6 í 6 hliða tening samhengi\n\t\t\tif((first_die_iterator+second_die_iterator) == current_sum):\n\t\t\t\tcurrent_sum_counter += 1\t\t\t\t\n\t\t\tif(current_sum_counter > max_counter[-1]):\n\t\t\t\tdel max_counter[:]\n\t\t\t\tmax_counter.append(current_sum)\t\t\t\t\t\t\t\t\n\n\t\t\telif(current_sum_counter == max_counter[-1]):\n\t\t\t\tmax_counter.append(current_sum)\n\n\nprint(max_counter)\n\n\n\"\"\"\ndebug:\n\nprint(first_die_iterator, \"+\", second_die_iterator, \" are equal to: \", current_sum , \"current summ counter: \", current_sum_counter, \"maxx counter: \", max_counter)\n\"\"\"","sub_path":"dice_cup.py","file_name":"dice_cup.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"607009826","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"The setup script.\"\"\"\n\nimport setuptools\n\nwith open(\"README.rst\", \"r\") as fh:\n long_description = fh.read()\n\nrequirements = [\n 'firecloud', 'pandas'\n]\n\nsetup_requirements = [\n # put setup requirements (distutils extensions, etc.) here\n]\n\ntest_requirements = [\n 'unittest'\n]\n\nsetuptools.setup(\n name='kco',\n version='0.1.0',\n description=\"KCO FireCloud Tools\",\n author=\"KCO Team\",\n author_email='kco-help@broadinstitute.org',\n url='https://github.com/broadinstitute/kco',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=setuptools.find_packages(include=['kco']),\n include_package_data=True,\n install_requires=requirements,\n license=\"BSD license\",\n zip_safe=False,\n keywords='FireCloud',\n classifiers=[\n 'License :: OSI Approved :: BSD License',\n 'Intended Audience :: Developers',\n 'Intended Audience :: Science/Research',\n 'Natural Language :: English',\n 'Operating System :: MacOS :: MacOS X',\n 'Operating System :: Microsoft :: Windows',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Scientific/Engineering :: Bio-Informatics'\n ],\n test_suite='tests',\n tests_require=test_requirements,\n setup_requires=setup_requirements,\n python_requires='>= 3',\n entry_points={\n 'console_scripts': [\n 'kco=kco.__main__:main'\n ]\n }\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"600671240","text":"from rest_framework import serializers\nfrom drf_queryfields import QueryFieldsMixin\nfrom django.contrib.auth.models import User\nfrom v1.models import *\n\nclass UserSerializer(QueryFieldsMixin, serializers.HyperlinkedModelSerializer):\n class Meta:\n model = User\n fields = ('url', 'id', 'username', 'first_name', 'last_name')\n\nclass TagSerializer(QueryFieldsMixin, serializers.ModelSerializer):\n class Meta:\n model = Tag\n fields = ('url', 'id', 'name')\n\nclass CategorySerializer(QueryFieldsMixin, serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('url', 'id', 'name')\n\nclass PostSerializer(QueryFieldsMixin, serializers.ModelSerializer):\n category = CategorySerializer()\n tags = TagSerializer(many=True)\n \n class Meta:\n model = Post\n fields = (\n 'url', \n 'id', \n 'author', \n 'category', \n 'title',\n 'description',\n 'tags',\n 'byline',\n 'slug',\n 'background_image',\n 'content',\n 'updated_on',\n 'created_on',\n 'publish_on'\n )","sub_path":"v1/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"362073222","text":"from boto.mturk.connection import MTurkConnection\nfrom boto.mturk.question import QuestionContent,Question,QuestionForm,Overview,AnswerSpecification,SelectionAnswer,FormattedContent,FreeTextAnswer\n \n\"\"\"\nThe purpose of this class is to generate a HIT that provides the turker with a set of one or more sentences that form an incomplete story\nIt also provides them with a list of continueing sentences in which they are required to vote on the best fitting\n\"\"\"\nclass VotingSentenceHit(object):\n\n def __init__(self, _access_id, _secret_key, _host, _story_sentences, _vote_sentences):\n \"\"\"\n Purpose: Initialize the HIT\n Parameters: _access_id, _secret_key and _host to connect to MTurk, _story_sentences is a list of sentences that make up the story \n _vote_sentences is a list of sentences on which the turker should vote\n \"\"\"\n self.access_id = _access_id\n self.secret_key = _secret_key\n self.host = _host\n self.story_sentences = _story_sentences\n self.vote_sentences = _vote_sentences\n self.title = 'Vote on the best sentence to end the given story.'\n self.description = ('An incomplete story is provided, vote on a set of given sentences to best continue the story.')\n self.keywords = 'story, sentence, writing, creative'\n\n \"\"\"\n This function connects to Mturk and generates the hit corresponding to the given story and sentence choices\n \"\"\"\n def generate_hit(self, num_assignments, hit_duration, hit_reward):\n \"\"\"\n Purpose: Generate and publish the HIT\n Parameters: num_assignments is the number of avaliable assignments for hit, \n hit_duration is the duration of the hit in seconds (60*5 for 5 minutes),\n hit_reward is the reward given per hit in dollars (0.05 is 5 cents)\n \"\"\"\n # CONNECT TO MTURK\n\n mtc = MTurkConnection(aws_access_key_id = self.access_id,\n aws_secret_access_key = self.secret_key,\n host = self.host)\n\n # BUILD OVERVIEW \n \n overview = Overview()\n\n overview.append_field('Title', 'The following one or more sentences constitute an incomplete story.')\n story = \"\"\n for sentence in self.story_sentences:\n story += sentence + \" \"\n overview.append(FormattedContent(story))\n \n # BUILD QUESTION 1: Copy the first sentence of the story \n \n qc1 = QuestionContent()\n qc1.append_field('Title','Copy verbatim the first sentence of the provided incomplete story. Please keep all capitalization and punctuation as given. Your sumbission will automatically be rejected if any character is incorrect.')\n fta1 = FreeTextAnswer()\n q1 = Question(identifier='verify_sentence', content = qc1, answer_spec = AnswerSpecification(fta1), is_required = True)\n\n # BUILD QUESTION 2: Vote on the best sentence to continue the story\n \n sentence_options = []\n for i, sentence in enumerate (self.vote_sentences):\n selection = (sentence, str(i))\n sentence_options.append(selection)\n qc2 = QuestionContent()\n qc2.append_field('Title','Choose the best sentence to end the story.')\n fta2 = SelectionAnswer(min=1, max=1,style='radiobutton',\n selections=sentence_options,\n type='text',\n other=False)\n q2 = Question(identifier='vote_sentence', content = qc2, answer_spec = AnswerSpecification(fta2), is_required = True)\n\n # BUILD THE QUESTION FORM \n \n question_form = QuestionForm()\n question_form.append(overview)\n question_form.append(q1)\n question_form.append(q2)\n \n # CREATE THE HIT \n \n mtc.create_hit(questions = question_form,\n max_assignments = num_assignments,\n title = self.title,\n description = self.description,\n keywords = self.keywords,\n duration = hit_duration,\n reward = hit_reward)","sub_path":"mturk_vote_end_sentence.py","file_name":"mturk_vote_end_sentence.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"371684290","text":"from flask import render_template\n\nfrom jwt import encode\nfrom uuid import uuid4\nfrom flask import Flask\nfrom flask import request\nfrom flask import make_response\nfrom flask import send_from_directory\nfrom flask_swagger_ui import get_swaggerui_blueprint\n\nimport redis\nimport datetime\nimport requests\n\napp = Flask(__name__)\n\n\ndb = redis.Redis(host='client_redis', port=6381, decode_responses=True)\n\nJWT_SECREATE_DATABASE=\"SECRET\"\nCDN_HOST = \"http://localhost:3000\"\nJWT_SECRET=\"HELLO\"\nJWT_SESSION_TIME=30\nSESSION_TIME = 180\nWEB_HOST = \"http://localhost:3001\"\nINVALIDATE = -1\nSESSION_ID = \"session-id\"\nUSER_COUNTER = \"user_counter\"\nUSERLOGIN=\"userlogin\"\nUSERPASSWORD=\"userpassword\"\nUSER='user'\nFILENAMES=\"filenames\"\n\ndb.set(\"users:\"+\"admin\",\"admin\")\n\n\nSWAGGER_URL = '/swagger'\nAPI_URL = '/static/swagger.json'\nSWAGGERUI_BLUEPRINT = get_swaggerui_blueprint(\n SWAGGER_URL,\n API_URL,\n config={\n 'app_name': \"Seans-Python-Flask-REST-Boilerplate\"\n }\n)\n\napp.register_blueprint(SWAGGERUI_BLUEPRINT, url_prefix=SWAGGER_URL)\n\n@app.route('/swagger')\ndef swagger():\n return \"/static/swagger.json\"\n\n@app.route('/')\ndef index():\n return render_template('login.html',WEB_HOST=WEB_HOST)\n\n@app.route('/auth', methods=['POST'])\ndef auth():\n response = make_response('', 303)\n login = request.form.get('login')\n password = request.form.get('password')\n if db.get(\"users:\"+login)==password:\n session_id = str(uuid4())\n #db.hset(user,SESSION_ID,session_id)\n #db.hset(session_id,FILENAMES,\"\")\n db.hset(\"session:\"+session_id, \"username\", login)\n print(\"SESSION ID\",session_id)\n response.set_cookie(SESSION_ID, session_id, max_age=SESSION_TIME)\n response.headers[\"Location\"] = \"/file_manage\"\n else:\n response.set_cookie(SESSION_ID, \"INVALIDATE\", max_age=INVALIDATE)\n response.headers[\"Location\"] = \"/\"\n return response\n\ndef findCorrectUserByLogin(login):\n for user in users:\n logindb=db.hget(user,USERLOGIN)\n if logindb==login:\n return user\n return None\n\ndef findCorrectUserByID(id):\n for user in users:\n iddb=db.hget(user,SESSION_ID)\n if iddb==id:\n return user\n return None\n\n@app.route('/format_error',methods=[\"GET\"])\ndef format_error():\n return render_template('format_error.html',WEB_HOST=WEB_HOST)\n\n@app.route('/file_manage',methods=['GET'])\ndef upload():\n session_id = request.cookies.get(SESSION_ID)\n if session_id:\n #if session_id in session:\n # fid, content_type = session[session_id]\n #else:\n # fid, content_type = '', 'text/plain'\n\n content_type=\"application/pdf\"\n #fileNames=getFileNames()\n #print(fileNames)\n login = db.hget(\"session:\" + session_id, \"username\")\n allfids= db.hvals(\"files:\"+login)\n print(allfids)\n download_tokens=[]\n filenames=[]\n for fidx in allfids:\n download_tokens.append(create_download_token(fidx).decode())\n filenames.append(db.hget(\"filename:\"+login,fidx))\n #download_token = create_download_token(fid).decode('ascii')\n upload_token = create_upload_token().decode('ascii')\n return render_template(\"file_manage.html\",allfids=allfids,content_type=content_type,CDN_HOST=CDN_HOST,upload_token=upload_token,download_tokens=download_tokens,WEB_HOST=WEB_HOST,filenames=filenames)\n return redirect(\"/\")\n\ndef getFileNames():\n filesName=requests.get(CDN_HOST+\"/files\")\n return filesName.json()\n\ndef create_download_token(fid):\n exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=JWT_SESSION_TIME)\n return encode({\"iss\":\"CLIENT\", \"exp\":exp}, JWT_SECRET, \"HS256\")\n\ndef create_upload_token():\n exp = datetime.datetime.utcnow() + datetime.timedelta(seconds=JWT_SESSION_TIME)\n return encode({\"iss\":\"CLIENT\", \"exp\":exp}, JWT_SECRET, \"HS256\")\n\n@app.route('/rejestracja',methods=['GET'])\ndef rejestracja():\n return render_template('rejestracja.html',WEB_HOST=WEB_HOST)\n\n\n@app.route('/userRegistration',methods=['POST'])\ndef userRegistration():\n #user_prefix = str(db.incr(USER_COUNTER))\n #new_user = user_prefix + USER\n #users.append(new_user)\n login=request.form['login'].rstrip()\n password=request.form['password'].rstrip()\n db.set(\"users:\"+login,password)\n #db.hset(new_user,USERPASSWORD,password)\n print(\"HELLO\")\n return redirect(\"/\")\n\n@app.route('/error',methods=['GET'])\ndef wrong():\n return render_template('error.html')\n\n@app.route('/logout')\ndef logout():\n response = make_response('', 303)\n response.set_cookie(SESSION_ID, \"INVALIDATE\", max_age=INVALIDATE)\n response.headers[\"Location\"] = \"/\"\n return response\n\n\n@app.route('/callback')\ndef uploaded():\n session_id = request.cookies.get(SESSION_ID)\n print(\"SESSION ID\", session_id)\n fid = request.args.get('fid')\n err = request.args.get('error')\n\n filename=request.args.get('namefile')\n print(filename)\n if not session_id:\n return redirect(\"/\")\n if err:\n if err==\"Invalid format file\":\n return redirect(\"/format_error\")\n return f\"APP Upload failed: {err}\", 400\n if not fid:\n return f\"APP Upload successfull, but no fid returned\", 500\n #content_type = request.args.get('content_type','text/plain')\n #session[session_id] = (fid, content_type)\n new_fied_prefix = str(db.incr(JWT_SECREATE_DATABASE))\n new_fied= new_fied_prefix + fid\n login = db.hget(\"session:\"+session_id,\"username\")\n db.hset(\"files:\"+login,new_fied, fid)\n db.hset(\"filename:\"+login,fid,filename)\n #filenames=db.hget(session_id,FILENAMES)\n #filenames.append()\n #print(\"FILENAMES\")\n #print(filenames)\n #db.hset(session_id,FILENAMES,filenames)\n return redirect(\"/file_manage\")\n\ndef redirect(location):\n response = make_response('', 303)\n response.headers[\"Location\"] = location\n return response","sub_path":"Projekt 1/client/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"205421614","text":"import json\nimport os\nimport sys\nimport boto3\nfrom boto3.dynamodb.conditions import Key, Attr\nfrom datetime import datetime\n\nhere = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(os.path.join(here, \"vendored\"))\n\nimport requests\n\nTOKEN = os.environ['TELEGRAM_TOKEN']\nBASE_URL = \"https://api.telegram.org/bot{}\".format(TOKEN)\nSEND_MESSAGE_URL = \"/sendMessage\"\n\nSTART_COMMAND = \"/start\"\nSTATUS_COMMAND = \"/status\"\nPHOTO_COMMAND = \"/photo\"\nWATER_COMMAND = \"/water\"\n\nDEVICE_ID = \"\" # Enter your plantId here e.g. \"yoshi\"\nWHITELIST = [] # Enter the list of Telegram IDs to whitelist here as comma separated strings e.g. [\"123\", \"456\"]\n\n\ndef handle_message(event, _):\n try:\n data = json.loads(event[\"body\"])\n chat_id = data[\"message\"][\"chat\"][\"id\"]\n user_id = str(data[\"message\"][\"from\"][\"id\"])\n\n message = str(data[\"message\"][\"text\"]).split(\" \")\n command = message[0].split(\"@\")\n\n is_relevant_msg = False\n if len(command) > 1:\n target = command[1][:-10]\n if target == DEVICE_ID:\n is_relevant_msg = True\n else:\n is_relevant_msg = True\n command = command[0]\n\n if is_relevant_msg:\n if command == START_COMMAND:\n if is_user_verified(user_id):\n handle_start(chat_id)\n else:\n handle_invalid_user(chat_id, START_COMMAND)\n\n if command == STATUS_COMMAND:\n if is_user_verified(user_id):\n handle_status(chat_id)\n else:\n handle_invalid_user(chat_id, STATUS_COMMAND)\n\n if command == PHOTO_COMMAND:\n if is_user_verified(user_id):\n handle_photo(chat_id)\n else:\n handle_invalid_user(chat_id, PHOTO_COMMAND)\n\n if command == WATER_COMMAND:\n if is_user_verified(user_id):\n handle_water(chat_id, message)\n else:\n handle_invalid_user(chat_id, WATER_COMMAND)\n\n except Exception as e:\n print(e)\n\n return {\"statusCode\": 200}\n\n\ndef handle_start(chat_id):\n response = \"Hello\"\n data = {\"text\": response.encode(\"utf8\"), \"chat_id\": chat_id}\n url = BASE_URL + SEND_MESSAGE_URL\n requests.post(url, data)\n\n\ndef handle_status(chat_id):\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('iotea_last_vitals')\n\n res = table.query(\n Limit=1,\n ScanIndexForward=False,\n KeyConditionExpression=Key('plantID').eq(DEVICE_ID)\n )\n\n item = res['Items'][0]\n humidity = item['humidity']\n temp = item['temperature']\n moisture = item['moisturePer']\n time = datetime.utcfromtimestamp(timestamp_to_seconds(item['ts']))\n\n response = \"Hello!\\n\" \\\n \"My last checkup was at {time}\\n\" \\\n \"Moisture Level: {moisture}%\\n\" \\\n \"Temperature: {temp}\\N{DEGREE SIGN}C\\n\" \\\n \"Humidity: {humidity}%\".format(\n time=time,\n moisture=moisture,\n temp=temp,\n humidity=humidity\n )\n\n data = {\"text\": response.encode(\"utf8\"), \"chat_id\": chat_id}\n url = BASE_URL + SEND_MESSAGE_URL\n requests.post(url, data)\n\n\ndef handle_photo(chat_id):\n response = \"Sending photo of plant...\"\n data = {\"text\": response.encode(\"utf8\"), \"chat_id\": chat_id}\n url = BASE_URL + SEND_MESSAGE_URL\n requests.post(url, data)\n\n\ndef handle_water(chat_id, message):\n response = \"\"\n invalid_thresh = False\n\n dynamodb = boto3.resource('dynamodb')\n table = dynamodb.Table('iotea_thresholds')\n\n res = table.query(\n Limit=1,\n ScanIndexForward=False,\n KeyConditionExpression=Key('plant_id').eq(DEVICE_ID)\n )\n current_thresh = res['Items'][0]['threshold']\n\n if len(message) == 1:\n response = \"The threshold for {plant} is currently {thresh}%\".format(\n plant=DEVICE_ID,\n thresh=current_thresh\n )\n elif len(message) == 2:\n try:\n new_thresh = int(message[1])\n if 0 <= new_thresh <= 100:\n table.update_item(\n Key={'plant_id': DEVICE_ID},\n UpdateExpression=\"set threshold = :r\",\n ExpressionAttributeValues={':r': new_thresh}\n )\n\n response = \"The threshold for {plant} has been changed from {current_thresh}% to {new_thresh}%\".format(\n plant=DEVICE_ID,\n current_thresh=current_thresh,\n new_thresh=new_thresh\n )\n else:\n invalid_thresh = True\n except ValueError:\n invalid_thresh = True\n else:\n invalid_thresh = True\n\n if invalid_thresh:\n response = \"Invalid threshold received.\"\n\n data = {\"text\": response.encode(\"utf8\"), \"chat_id\": chat_id}\n url = BASE_URL + SEND_MESSAGE_URL\n requests.post(url, data)\n\n\ndef handle_invalid_user(chat_id, command):\n response = \"Sorry, you are not authorised to use {}\".format(command)\n data = {\"text\": response.encode(\"utf8\"), \"chat_id\": chat_id}\n url = BASE_URL + SEND_MESSAGE_URL\n requests.post(url, data)\n\n\ndef is_user_verified(user_id):\n return user_id in WHITELIST\n\n\ndef timestamp_to_seconds(ts):\n return ts / 1000\n","sub_path":"bot/src/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":5439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"97299237","text":"import os\nimport sys\nsys.path.insert(1, os.path.join(sys.path[0], '../utils'))\nimport numpy as np\nimport argparse\nimport h5py\nimport math\nimport time\nimport logging\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\nimport _pickle as cPickle\nimport librosa\n\nimport torch\ntorch.backends.cudnn.benchmark=True\ntorch.manual_seed(0)\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.utils.data\n \nfrom utilities import get_filename\nfrom models import *\nfrom pytorch_utils import (move_data_to_device, count_parameters, count_flops)\nimport config\n\n\"\"\"\nMODEL_TYPE=\"Cnn14\"\nCHECKPOINT_PATH=\"/vol/vssp/msos/qk/workspaces/pub_audioset_tagging_cnn_transfer/checkpoints_for_paper/Cnn14_mAP=0.431.pth\"\nCUDA_VISIBLE_DEVICES=1 python3 pytorch/inference_template.py inference --window_size=1024 --hop_size=320 --mel_bins=64 --fmin=50 --fmax=14000 --model_type=$MODEL_TYPE --checkpoint_path=$CHECKPOINT_PATH --cuda\n\"\"\"\n\ndef inference(args):\n\n # Arugments & parameters\n window_size = args.window_size\n hop_size = args.hop_size\n mel_bins = args.mel_bins\n fmin = args.fmin\n fmax = args.fmax\n model_type = args.model_type\n checkpoint_path = args.checkpoint_path\n device = torch.device('cuda') if args.cuda and torch.cuda.is_available() else torch.device('cpu')\n filename = args.filename\n\n sample_rate = config.sample_rate\n classes_num = config.classes_num\n\n # Model\n Model = eval(model_type)\n model = Model(sample_rate=sample_rate, window_size=window_size, \n hop_size=hop_size, mel_bins=mel_bins, fmin=fmin, fmax=fmax, \n classes_num=classes_num)\n \n checkpoint = torch.load(checkpoint_path, map_location=device)\n model.load_state_dict(checkpoint['model'])\n\n # Parallel\n print('GPU number: {}'.format(torch.cuda.device_count()))\n model = torch.nn.DataParallel(model)\n\n if 'cuda' in str(device):\n model.to(device)\n \n if True:\n waveform = np.zeros(sample_rate * 10)\n else:\n audio_path = \"/vol/vssp/msos/qk/test9/YwfSPbhnpOlQ.wav\"\n (waveform, _) = librosa.core.load(audio_path, sr=sample_rate, mono=True)\n\n waveform = waveform[None, :]\n waveform = move_data_to_device(waveform, device)\n\n # Forward\n model.eval()\n batch_output_dict = model(waveform, None)\n\n clipwise_output = batch_output_dict['clipwise_output'].data.cpu().numpy()[0]\n sorted_indexes = np.argsort(clipwise_output)[::-1]\n\n embedding = batch_output_dict['embedding'].data.cpu().numpy()[0]\n print(embedding.shape)\n\n for k in range(10):\n print('{}, {}'.format(np.array(config.labels)[sorted_indexes[k]], \n clipwise_output[sorted_indexes[k]]))\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='Example of parser. ')\n subparsers = parser.add_subparsers(dest='mode')\n\n parser_inference = subparsers.add_parser('inference') \n parser_inference.add_argument('--window_size', type=int, required=True)\n parser_inference.add_argument('--hop_size', type=int, required=True)\n parser_inference.add_argument('--mel_bins', type=int, required=True)\n parser_inference.add_argument('--fmin', type=int, required=True)\n parser_inference.add_argument('--fmax', type=int, required=True) \n parser_inference.add_argument('--model_type', type=str, required=True)\n parser_inference.add_argument('--checkpoint_path', type=str, required=True)\n parser_inference.add_argument('--cuda', action='store_true', default=False)\n \n args = parser.parse_args()\n args.filename = get_filename(__file__)\n\n if args.mode == 'inference':\n inference(args)\n\n else:\n raise Exception('Error argument!')\n","sub_path":"pytorch/inference_template.py","file_name":"inference_template.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"164547975","text":"\"\"\"\n Selection Sort\n Properties:\n Not stable\n O(1) extra space\n Θ(n2) comparisons\n Θ(n) swaps\n Not adaptive\n\"\"\"\n#to use comma seperated input uncomment below line\n#x = [int(i) for i in input().strip().split(\",\")]\n\nx=[10,9,8,7,6,5,4,3,2,1]\nfor i in range(len(x)-1):\n minn = i\n for j in range(i+1,len(x)):\n if(x[j] < x[minn]):\n minn=j\n if(minn!=i):\n x[i],x[minn] = x[minn],x[i]\nprint(x)\n","sub_path":"Selection_sort.py","file_name":"Selection_sort.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"19178858","text":"# -*- coding: utf-8 -*-\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('banners.views',\n url(regex=r'^placement/(?P\\d+)/(?P\\d+)/$', view='placement',\n name='placement'),\n url(regex=r'^view/(?P\\d+)/(?P\\d+)/(?P[\\w\\d]+)/$',\n view='shows', name='shows'),\n url(regex=r'^view/(?P\\d+)/(?P\\d+)/$',\n view='shows', name='show'),\n url(regex=r'^click/(?P\\d+)/(?P\\d+)/(?P[\\w\\d]+)/$',\n view='clicks', name='click'),\n url(regex=r'^click/(?P\\d+)/(?P\\d+)/$',\n view='clicks', name='clicks'),\n url(regex=r'^code/(?P\\d+)/(?Pip|name)/$', view='code', name='code'),\n url(regex=r'^zones/$', view='code', name='zones'),\n)","sub_path":"banners/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"126797399","text":"#!/usr/bin/python3\r\n\"\"\"\r\n===============================================================================\r\n\r\n████████╗███████╗███████╗████████╗ ██████╗ █████╗ ███████╗███████╗███████╗\r\n╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ ██╔════╝██╔══██╗██╔════╝██╔════╝██╔════╝\r\n ██║ █████╗ ███████╗ ██║ ██║ ███████║███████╗█████╗ ███████╗\r\n ██║ ██╔══╝ ╚════██║ ██║ ██║ ██╔══██║╚════██║██╔══╝ ╚════██║\r\n ██║ ███████╗███████║ ██║ ╚██████╗██║ ██║███████║███████╗███████║\r\n ╚═╝ ╚══════╝╚══════╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝\r\n\r\n===============================================================================\r\n\"\"\"\r\n\r\nfrom models.base_model import BaseModel\r\nfrom models.state import State\r\nimport unittest\r\nimport json\r\nimport pep8\r\nimport datetime\r\n\r\n\r\nclass TestState(unittest.TestCase):\r\n \"\"\" Test State class implementation. \"\"\"\r\n def test_doc_module(self):\r\n \"\"\"Module documentation\"\"\"\r\n doc = State.__doc__\r\n self.assertGreater(len(doc), 1)\r\n\r\n def test_pep8_conformance_state(self):\r\n \"\"\" Test that models/state.py conforms to PEP8. \"\"\"\r\n pep8style = pep8.StyleGuide(quiet=True)\r\n result = pep8style.check_files(['models/state.py'])\r\n self.assertEqual(result.total_errors, 0,\r\n \"Found code style errors (and warnings).\")\r\n\r\n def test_pep8_conformance_test_state(self):\r\n \"\"\"\r\n - Test that tests/test_models/test_state.py conforms to PEP8.\r\n \"\"\"\r\n pep8style = pep8.StyleGuide(quiet=True)\r\n res = pep8style.check_files(['tests/test_models/test_state.py'])\r\n self.assertEqual(res.total_errors, 0,\r\n \"Found code style errors (and warnings).\")\r\n\r\n def test_doc_constructor(self):\r\n \"\"\" Constructor documentation. \"\"\"\r\n doc = State.__init__.__doc__\r\n self.assertGreater(len(doc), 1)\r\n\r\n def test_class(self):\r\n \"\"\" Validate the types of the attributes an class. \"\"\"\r\n with self.subTest(msg='Inheritance'):\r\n self.assertTrue(issubclass(State, BaseModel))\r\n\r\n with self.subTest(msg='Attributes'):\r\n self.assertIsInstance(State.name, str)\r\n","sub_path":"tests/test_models/test_state.py","file_name":"test_state.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"41763569","text":"import pandas as pd\nimport glob \nfrom subprocess import run\nimport os\nfrom collections import Counter\n\n\n \ndef main():\n # Import et nettoyage\n csv_path = 'data/dataset_FR_gen.csv'\n data = pd.read_csv(csv_path)\n data = data.drop([\"category\", \"topic\"], axis=1)\n data = data.dropna()\n\n # Sélection des contributeurs fiables\n data = data[data[\"file\"].apply(lambda x : \"CLEMENT\" in x or \"MONTA\" in x or \"GOULARD\" in x)]\n# data = data[data[\"file\"].apply(lambda x : \"MONTA\" in x)]\n\n\n # Supprime les noms de fichiers avec espace\n data = data.drop(data[data['file'].str.contains(\"ARN\")].index)\n\n # On enlève les chevrons qui apparaissent dans les \"\"\n transcription = data[\"transcription\"].apply(lambda x : x.replace(\"<\", \"\").replace(\">\", \"\"))\n data[\"transcription\"] = transcription\n\n # On supprime les fichiers non présents dans le tracker\n delete_untracked(data)\n\n # Save\n data.to_csv(\"data/dataset_FR_filtered.csv\", index=False)\n \n gen_trans(data)\n gen_dict()\n \nmain()","sub_path":"fine_tuning/training/gen_tracker.py","file_name":"gen_tracker.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"468836022","text":"# -*- coding: utf-8 -*-\nfrom django.contrib.auth.models import AnonymousUser\nfrom django.template import RequestContext\nfrom django.test import RequestFactory\nfrom django.utils.text import smart_split\nfrom django.utils.encoding import force_unicode\n\nfrom .conf import settings\nfrom .utils import strip_tags\n\n\ndef get_plugin_index_data(base_plugin, request):\n text_bits = []\n instance, plugin_type = base_plugin.get_plugin_instance()\n\n if instance is None:\n # this is an empty plugin\n return text_bits\n\n if hasattr(instance, 'search_fulltext'):\n # check if the plugin instance has search enabled\n search_contents = instance.search_fulltext\n elif hasattr(base_plugin, 'search_fulltext'):\n # now check in the base plugin instance (CMSPlugin)\n search_contents = base_plugin.search_fulltext\n elif hasattr(plugin_type, 'search_fulltext'):\n # last check in the plugin class (CMSPluginBase)\n search_contents = plugin_type.search_fulltext\n else:\n # enable by default\n search_contents = True\n\n for field in getattr(instance, 'search_fields', []):\n field_content = strip_tags(getattr(instance, field, ''))\n\n if field_content:\n field_content = force_unicode(field_content)\n text_bits.extend(smart_split(field_content))\n\n if search_contents:\n plugin_contents = instance.render_plugin(context=RequestContext(request))\n\n if plugin_contents:\n plugin_contents = strip_tags(plugin_contents)\n text_bits.extend(smart_split(plugin_contents))\n\n return text_bits\n\n\ndef get_request(language=None):\n \"\"\"\n Returns a Request instance populated with cms specific attributes.\n \"\"\"\n request_factory = RequestFactory(HTTP_HOST=settings.ALLOWED_HOSTS[0])\n request = request_factory.get(\"/\")\n request.session = {}\n request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE\n # Needed for plugin rendering.\n request.current_page = None\n request.user = AnonymousUser()\n return request\n","sub_path":"aldryn_search/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"285327831","text":"################################################################################\n# Utility functions.\n################################################################################\ndef get_tvtk_class_names():\n \"\"\"Returns 4 lists:\n 1. A list of all the TVTK class names that are not abstract.\n 2. A list of the TVTK sources (have only outputs and no inputs)\n 3. A list of the TVTK filters (both inputs and outputs)\n 4. A list of the TVTK sinks (only inputs and no outputs)\n \"\"\"\n # Shut of VTK warnings for the time being.\n o = vtk.vtkObject\n w = o.GetGlobalWarningDisplay()\n o.SetGlobalWarningDisplay(0) # Turn it off.\n all = []\n src = []\n filter = []\n sink = []\n for name in dir(vtk):\n if name.startswith('vtk') and not name.startswith('vtkQt'):\n klass = getattr(vtk, name)\n try:\n c = klass()\n except TypeError:\n continue\n tvtk_name = get_tvtk_name(name)\n all.append(tvtk_name)\n has_input = has_output = False\n if hasattr(klass, 'GetNumberOfInputPorts'):\n if c.GetNumberOfInputPorts() > 0:\n has_input = True\n if hasattr(klass, 'GetNumberOfOutputPorts'):\n if c.GetNumberOfOutputPorts() > 0:\n has_output = True\n if has_input:\n if has_output:\n filter.append(tvtk_name)\n else:\n sink.append(tvtk_name)\n elif has_output:\n src.append(tvtk_name)\n o.SetGlobalWarningDisplay(w)\n result = (all, src, filter, sink)\n for x in result:\n x.sort()\n return result\n","sub_path":"LIVE/dj_demo/mysite/test_segment_base/tvtk_doc_0.py","file_name":"tvtk_doc_0.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"155497919","text":"def representingL(A, B):\n # This is the representation of L from the homework\n # which will be later used to calculate Fibonacci sequence in O(log n) complexity\n a = (A[0][0] * B[0][0]) + (A[0][1] * B[1][0])\n b = (A[0][0] * B[0][1]) + (A[0][1] * B[1][1])\n c = (A[1][0] * B[0][0]) + (A[1][1] * B[1][0])\n d = (A[1][0] * B[0][1]) + (A[1][1] * B[1][1])\n A[0][0] = a\n A[0][1] = b\n A[1][0] = c\n A[1][1] = d\n\n\ndef Pow(A, n):\n if n == 0 or n == 1:\n return\n Pow(A, n // 2)\n representingL(A, A)\n B = [[1, 1], [1, 0]]\n if n % 2 != 0:\n representingL(A, B)\n\n\ndef fibPow(n):\n\n if n == 0:\n return 0\n if n == 1:\n return 1\n else:\n A = [[1, 1], [1, 0]]\n Pow(A, n - 1)\n return A[0][0]\n\n\ndef main():\n print(fibPow(28))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Assignment2/assign2.py","file_name":"assign2.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"612365987","text":"\"\"\"\nAoC\n\"\"\"\nimport time\n\nstart_secs = time.time()\nprint('')\n\ndef all_zero(arr):\n tot = arr[0] + arr[1] + arr[2] + arr[3] + arr[4] + arr[5] + arr[6]\n return tot == 0\n\ndef get_future_pos(t,pos,positions):\n new_pos = t + pos\n if new_pos < positions:\n return new_pos\n else:\n new_pos = ( (t+pos) % positions )\n return new_pos\n\ndef get_positions(t):\n global pos_temp\n global discs\n for i in range(len(discs)):\n pos_temp[i] = get_future_pos(t+i+1,discs[i][0],discs[i][1])\n return pos_temp\n\n# read in input file\nl=[]\nmy_file = open(\"inp2.txt\", \"r\", encoding='utf-8')\nlines = my_file.readlines()\nfor line in lines:\n l.append(line.strip())\n\ndiscs = [ [0,0] for i in range(len(l)) ] # [ pos, positions ]\npos_temp = [ 0 for i in range(len(l)) ]\nfor s in l:\n arr = s.split(' ')\n disc_num = int(arr[1].replace('#','')) - 1\n positions = int(arr[3])\n pos = int(arr[11].replace('.',''))\n discs[disc_num][0] = pos\n discs[disc_num][1] = positions\n\nfor step in range(3000000):\n res = get_positions(step)\n if all_zero(res):\n print(step)\n break\n \n\nprint('')\nend_secs = time.time()\nprint('--- ' + str(end_secs-start_secs) + ' secs ---')\n","sub_path":"2016/day15/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"74995355","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom fitter import Fitter\nimport os\n\n\n# In[4]:\n\n\ndata_path = os.getcwd()\ndata_path = data_path.replace(\"code\", \"data\")\ndata_path = data_path.replace(\"notebooks\", \"input\")\n\nos.chdir(data_path)\n\n\n# In[5]:\n\n\n\njob_data = pd.read_csv(\"nyc-jobs.csv\")\n\n\n# In[ ]:\n\n\n\n\n\n# In[32]:\n\n\njob_data = job_data[[\"Salary Range To\", \"Salary Frequency\"]]\njob_data = job_data[job_data[\"Salary Frequency\"] == \"Annual\"]\n\n\n# In[33]:\n\n\nplot_data = np.array(job_data[\"Salary Range To\"])\n\n\n# In[34]:\n\n\nplt.hist(plot_data, bins = 30)\nlen(plot_data)\n\n\n# In[78]:\n\n\nsampled_data = np.random.choice(plot_data, 500, replace = False)\n\n\n# In[80]:\n\n\nplt.hist(sampled_data, bins = 30)\n\n\n# In[83]:\n\n\nf = Fitter(plot_data)\nf.fit()\n\n\n# In[84]:\n\n\nf.summary()\n\n\n# In[93]:\n\n\nf_params = f.fitted_param[\"f\"]\nf_params\n\n\n# In[96]:\n\n\nf.fitted_pdf['gamma']\n\n","sub_path":"code/scripts/fitter-test-nyc-jobs.py","file_name":"fitter-test-nyc-jobs.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"488619281","text":"import json\n\n\n# check if working as wished, find out if there's anything wrong, fix it\ndef write_file(data):\n with open('data.txt', 'w') as fp:\n json.dump(data, fp)\n #fp.close()\n\n\n# check if working as wished, find out if there's anything wrong, fix it\ndef read_file(f):\n with open(f, 'r') as fp:\n string = fp.read()\n if len(string) > 1:\n data = json.loads(string)\n return data\n else:\n data = {}\n return data\n","sub_path":"saves.py","file_name":"saves.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"649523544","text":"import re\nimport six\nimport unicodedata\nfrom math import radians, sin, cos, acos\nfrom django import VERSION\nfrom django.contrib.gis.geos import Point\ntry:\n from django.utils.encoding import force_unicode as force_text\nexcept (NameError, ImportError):\n from django.utils.encoding import force_text\nfrom django.utils.safestring import mark_safe, SafeText\n\nearth_radius_km = 6371.009\n\n\ndef geo_distance(a, b):\n \"\"\"Distance between two geo points in km. (p.x = long, p.y = lat)\"\"\"\n a_y = radians(a.y)\n b_y = radians(b.y)\n delta_x = radians(a.x - b.x)\n cos_x = (sin(a_y) * sin(b_y) +\n cos(a_y) * cos(b_y) * cos(delta_x))\n return acos(cos_x) * earth_radius_km\n\n\nto_und_rgx = re.compile(r\"[']\")\nslugify_rgx = re.compile(r'[^-\\w._~]', re.UNICODE)\nmulti_dash_rgx = re.compile(r'-{2,}')\ndash_und_rgx = re.compile(r'[-_]_')\nund_dash_rgx = re.compile(r'[-_]-')\nstarting_chars_rgx = re.compile(r'^[-._]*')\nending_chars_rgx = re.compile(r'[-.]*$')\n\n\ndef default_slugify(obj, value):\n value = force_text(value)\n value = unicodedata.normalize('NFKC', value.strip().lower())\n value = re.sub(to_und_rgx, '_', value)\n value = re.sub(slugify_rgx, '-', value)\n value = re.sub(multi_dash_rgx, '-', value)\n value = re.sub(dash_und_rgx, '_', value)\n value = re.sub(und_dash_rgx, '_', value)\n value = re.sub(starting_chars_rgx, '', value)\n value = re.sub(ending_chars_rgx, '', value)\n return mark_safe(value)\n\nif VERSION < (1, 10):\n from django.utils.functional import allow_lazy\n default_slugify = allow_lazy(default_slugify, six.text_type, SafeText)\nelse:\n from django.utils.functional import keep_lazy\n default_slugify = keep_lazy(six.text_type, SafeText)(default_slugify)\n","sub_path":"cities/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"627786155","text":"#Author: Xinran\r\nimport csv\r\n# Input data\r\ninputDataName = 'pos'\r\n# inputData = 'neg'\r\n# Output data\r\ndata_out = []\r\nvar_data_out=[]\r\n\r\n# store the label message\r\npos_label_list = [ ['' for col in range(5)] for row in range(27)]\r\nneg_label_list = [ ['' for col in range(5)] for row in range(27)]\r\n\r\ndef get_one_message_data(line, start_index, msg_num,label_list,bit = 27):\r\n for i in range(start_index,start_index+bit):\r\n if(line[i]!=''):\r\n #print(neg_label_list[i - start_index][msg_num - 1])\r\n if (label_list[i - start_index][msg_num - 1] == '0'):\r\n return str((-1) * int(line[i]))\r\n return line[i]\r\n return None\r\n\r\ndef decimal_to_ternary(dec, base = 3):\r\n tempStr = ''\r\n temp = dec\r\n while (temp > 0):\r\n ord = temp % base\r\n tempStr = str(ord) + tempStr\r\n temp = int(temp / base)\r\n #print(tempStr)\r\n if(len(tempStr)<3):\r\n for i in range(0,3-len(tempStr)):\r\n tempStr = str(0) + tempStr\r\n return tempStr\r\n\r\n# open the label file, read in the data\r\nwith open('messageLabel.csv') as messageLabel:\r\n label_csv = csv.reader(messageLabel)\r\n headers = next(label_csv)\r\n count = 0\r\n for line in label_csv:\r\n for i in range(1,6):\r\n pos_label_list[count][i - 1] = line[i]\r\n for i in range(6,11):\r\n neg_label_list[count][i - 6] = line[i]\r\n count += 1\r\n\r\n\r\n# select input data\r\nif inputDataName == 'pos':\r\n datafile = 'positiveMessageFirstBatchData.csv'\r\n label = pos_label_list\r\nelif inputDataName == 'neg':\r\n datafile = 'negativeMessageFirstBatchData.csv'\r\n label = neg_label_list\r\n\r\n# open the input file\r\nwith open(datafile) as inputData:\r\n input_csv = csv.reader(inputData)\r\n headers = next(input_csv)\r\n ac1_index = headers.index('AC1')\r\n ac2_index = headers.index('AC2')\r\n for line in input_csv:\r\n # Delete the invalid data\r\n # when the AC1 and AC2 are both incorrect\r\n if(line[ac1_index]!='2' or line[ac2_index]!='1'):\r\n continue\r\n\r\n # Get the data of every message\r\n # 5 message in total\r\n # print(line)\r\n msg_data_list = []\r\n for i in range(1,6):\r\n start_index = headers.index('M'+str(i)+'_000_1')\r\n msg_data = get_one_message_data(line,start_index,i,label)\r\n msg_data_list.append(msg_data)\r\n data_out.append(msg_data_list)\r\n\r\n #Get the data of every variation\r\n var_data_list = []\r\n #print(line)\r\n\r\n for i in range(0,27):\r\n data_num =decimal_to_ternary(i)\r\n tmp = 0\r\n nullValue=True\r\n for j in range(1,6):\r\n data_index = headers.index('M' +str(j)+ '_'+data_num+'_1')\r\n if(line[data_index] != ''):\r\n nullValue=False\r\n if (label[i][j-1] == '0'):\r\n tmp += (-1) * int(line[data_index])\r\n else:\r\n tmp += int(line[data_index])\r\n #print(str(tmp)+' , '+str(j)+ '_'+str(data_num))\r\n # else:\r\n # tmp = None\r\n if not nullValue:\r\n var_data_list.append(tmp)\r\n else:\r\n var_data_list.append('')\r\n\r\n var_data_out.append(var_data_list)\r\n\r\nwith open(inputDataName+'_msg_output.csv','w') as msg_f:\r\n msg_csv = csv.writer(msg_f)\r\n header = ['M'+str(i) for i in range(1,6)]\r\n msg_csv.writerow(header)\r\n for line in data_out:\r\n msg_csv.writerow(line)\r\n\r\nwith open(inputDataName+'_var_output.csv','w') as var_f:\r\n var_csv = csv.writer(var_f)\r\n header = [decimal_to_ternary(i) for i in range(27)]\r\n var_csv.writerow(header)\r\n for line in var_data_out:\r\n var_csv.writerow(line)\r\n\r\nwith open(inputDataName+'_item_output.txt','w') as var_f:\r\n var_csv = csv.writer(var_f)\r\n header = ['gesture','dist','shading','y']\r\n var_csv.writerow(header)\r\n for line in var_data_out:\r\n for i in range(0,27):\r\n if line[i]!='':\r\n dataNum = decimal_to_ternary(i)\r\n dataTuple = [dataNum[0],dataNum[1],dataNum[2],line[i]]\r\n var_csv.writerow(dataTuple)\r\n","sub_path":"SU17Data/pre-process.py","file_name":"pre-process.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"393187252","text":"import seaborn as sns\n\n\ndef discrete_qualitative_colors(n_colors: int = 6, reverse: bool = False):\n \"\"\"\n A discrete qualitative color palette\n\n Parameters\n ----------\n n_colors : int\n number of colors\n reverse : boolean\n reverse colors or not\n\n Returns\n -------\n list of RGB tuples\n \"\"\"\n\n return _qualitative_colors(n_colors=n_colors, reverse=reverse)\n\n\ndef _qualitative_colors(n_colors=3, as_cmap=False, reverse=False):\n qualitative = [\n \"#004B87\",\n \"#0D0B0C\",\n \"#B04A5A\",\n \"#61829CFF\",\n \"#B2AAA2\",\n \"#532026FF\",\n ]\n assert n_colors <= len(\n qualitative\n ), f\"color palette only has {len(qualitative)}\"\n if reverse:\n qualitative = qualitative[::-1]\n return sns.color_palette(qualitative, as_cmap=as_cmap, n_colors=n_colors)\n","sub_path":"palettes/qualitative.py","file_name":"qualitative.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"81872052","text":"# Nolan Harris\n# Nph2tx\n\ndef mymap(func, lst):\n '''variable new_list makes a copy of the list to manipulate it, then adds the function to it and returns it'''\n new_list = [lst[:]]\n x = func\n comb = new_list.x\n return comb\n\n\ndef myreduce(func, lst):\n '''turns lst into a list'''\n\n other_list = [lst[:]]\n y = func\n combination = other_list.y\n\n if func in lst > 1:\n return combination * func\n\n\n\n\n\n\n\n","sub_path":"CS1110/CS1110/map_reduce.py/map_reduce.py","file_name":"map_reduce.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"2067626","text":"# Functio to find the maximal sum\n# This can be solved efficiently using dynamic programming\n# From the bottom up, find the maximal element and find corresponding maximal element on the above level and so on\n# untill you reach the tip of the pyramiddatetime A combination of a date and a time. Attributes: ()\n# You can read about a similar C# implementation here https://www.mathblog.dk/project-euler-18/\ndef findMaxSum(arr):\n\tfor i in range(0,len(arr)):\n\t\tarr[i]=arr[i].split()\n\n\tfor i in range(0,len(arr)):\n\t\tfor j in range(0, len(arr[i])):\n\t\t\tarr[i][j]=int(arr[i][j])\n\twhile(len(arr)>1):\n\t\tv=arr[-2]\n\t\tw=arr[-1]\n\t\tfor i in range(0,len(v)):\n\t\t\tv[i]+=max(w[i],w[i+1])\n\t\tarr.pop()\n\treturn arr[0][0]\n\nif __name__ == \"__main__\":\n\tn=int(input())\n\ttri = []\n\tfor i in range(n):\n\t\ttri.append(input())\n\tprint(findMaxSum(tri))","sub_path":"Question 6/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"174118081","text":"from collections import OrderedDict\r\nimport random\r\nfrom django_lazifier.utils.builtin_types.obj import Obj\r\nfrom django_lazifier.utils.builtin_types.str import Str\r\nfrom django_lazifier.utils.utils import log_exception\r\n\r\n\r\nclass Lst:\r\n @classmethod\r\n def get_random(cls, the_list: list, pop=False, default_value=None):\r\n \"\"\"\r\n Get one item at random in the specified list.\r\n\r\n :param the_list:\r\n :param pop:\r\n :param default_value:\r\n :return:\r\n \"\"\"\r\n if not the_list:\r\n return default_value\r\n\r\n length = len(the_list)\r\n rand_index = random.randint(0, length-1)\r\n\r\n if pop:\r\n return the_list.pop(rand_index)\r\n\r\n return the_list[rand_index]\r\n\r\n @classmethod\r\n def casefold(cls, str_list):\r\n \"\"\"\r\n Pass each string element through str.casefold()\r\n :param str_list:\r\n :return:\r\n \"\"\"\r\n return [str(x).casefold() for x in str_list]\r\n\r\n @classmethod\r\n def convert_to_int(cls, str_list):\r\n \"\"\"\r\n Convert a list of string into a list of int\r\n :param str_list: [\"1\", \"2.99\", \"0.11\"] => [1, 3, 0]\r\n :return: []\r\n \"\"\"\r\n if not str_list:\r\n return []\r\n\r\n int_list = []\r\n for s in str_list:\r\n val = Str.int_val(s, None)\r\n if val is not None:\r\n int_list.append(val)\r\n\r\n return int_list\r\n\r\n @classmethod\r\n def convert_to_str(cls, the_list):\r\n \"\"\"\r\n Convert a list of object into a list of string\r\n :return: []\r\n \"\"\"\r\n if not the_list:\r\n return []\r\n\r\n result = []\r\n for s in the_list:\r\n if s is not None:\r\n result.append(s.__str__())\r\n\r\n return result\r\n\r\n @classmethod\r\n def strip_string(cls, the_list, chars=None):\r\n \"\"\"\r\n Trim the list of strings.\r\n :param the_list:\r\n :param chars:\r\n :return:\r\n \"\"\"\r\n the_list = Lst.convert_to_str(the_list)\r\n return [elm.strip(chars) for elm in the_list]\r\n\r\n @classmethod\r\n def group_by(cls, the_list, group, none_value_label='None', flat=False):\r\n \"\"\"\r\n Group the list by the group specified.\r\n eg. Lst.group_by(seats, 'zone.name', 'do not belong to a zone')\r\n => { 'zone1': [seat1, seat2]\r\n 'zone2': [seat7, seat8]\r\n 'do not belong to a zone': [seat3, seat4, seat5]\r\n }\r\n\r\n :param the_list:\r\n :param group: {str|def} name of the attribute, support dot notation group_by(persons, 'contact.phone')\r\n :param none_value_label: the value of the column specified is None then use this label as the key.\r\n :param flat: if true only take the last item for each group and put it in the result dict\r\n :rtype: dict\r\n \"\"\"\r\n result = OrderedDict()\r\n for row in the_list:\r\n if callable(group):\r\n col_value = group(row)\r\n else:\r\n col_value = Obj.getattr(row, group, None)\r\n\r\n if col_value is None:\r\n col_value = none_value_label\r\n\r\n if not flat and col_value not in result:\r\n result[col_value] = []\r\n\r\n if flat:\r\n result[col_value] = row\r\n else:\r\n result[col_value].append(row)\r\n return result\r\n\r\n @classmethod\r\n def multi_group_by(cls, the_list, none_value_label, group_names: list):\r\n \"\"\"\r\n Provide a drilled down version of the data.\r\n eg. Lst.multi_group_by(sensors, _('Unassigned'), ['facility__id', 'zone__id'])\r\n\r\n return { facility_1 : [ {zone_1 : [ {sensor_1},\r\n {sensor_2} ],\r\n {zone_2 : [ {sensor_3},\r\n {sensor_4} ]\r\n\r\n :type the_list: list|QuerySet|ValuesQuerySet\r\n :param the_list: list, QuerySet or ValuesQuerySet\r\n :type none_value_label: str|None|object\r\n :param none_value_label: the value to use if the column value is None\r\n :param group_names: the list of columns to group by\r\n :return: List\r\n \"\"\"\r\n if type(group_names) == str:\r\n group_names = [group_names]\r\n\r\n if not isinstance(group_names, list):\r\n raise ValueError('The argument group_names must be a list of all the columns you want to group.')\r\n\r\n group_names = group_names.copy()\r\n if group_names:\r\n col = group_names.pop(0)\r\n result = Lst.group_by(the_list, col, none_value_label)\r\n if group_names:\r\n for col, rows in result.items():\r\n result[col] = Lst.multi_group_by(rows, none_value_label, group_names)\r\n\r\n return result\r\n return OrderedDict()\r\n\r\n @classmethod\r\n def tuple_multi_group_by(cls, the_list, none_value_label, group_names: list):\r\n \"\"\"\r\n Similarly to multi_group_by but instead of use the value of the specified columns\r\n as a key it combine all the keys together in one tuple as key.\r\n\r\n eg. sensors = Sensor.objects.values(**columns)\r\n Lst.tuple_multi_group_by(sensors, 'None', ['facility__id', 'zone__id'])\r\n\r\n return { (facility_1, zone_1): [ sensor1, sensor2 ],\r\n (facility_1, zone_2): [ sensor3 ],\r\n (facility_2, zone_3): [ sensor4 ])\r\n\r\n :type the_list: list|QuerySet|ValuesQuerySet\r\n :param the_list: list, QuerySet or ValuesQuerySet\r\n :param none_value_label: the value to use if the column value is None\r\n :param group_names: the list of columns to group by\r\n :return: List\r\n \"\"\"\r\n if type(group_names) == str:\r\n group_names = [group_names]\r\n\r\n if not isinstance(group_names, list):\r\n raise ValueError('The argument group_names must be a list of all the fields you want to group.')\r\n\r\n group_names = group_names.copy()\r\n if group_names:\r\n result = OrderedDict()\r\n first_grp_val = group_names.pop(0) # pop at the start\r\n first_group_by = Lst.group_by(the_list, first_grp_val, none_value_label)\r\n\r\n if group_names:\r\n for col, rows in first_group_by.items():\r\n tuple_list = Lst.tuple_multi_group_by(rows, none_value_label, group_names)\r\n for k, t in tuple_list.items():\r\n result[(col,) + k] = t\r\n else:\r\n for k, v in first_group_by.items():\r\n result[(k,)] = v\r\n return result\r\n\r\n return OrderedDict()\r\n\r\n @classmethod\r\n def all(cls, the_list, func, **kwargs):\r\n \"\"\"\r\n Return True if all is True, else False.\r\n Similar to all() but its accept a lambda.\r\n\r\n :param the_list:\r\n :param func: lambda that return bool\r\n :param kwargs: any additional params for func\r\n :return:\r\n \"\"\"\r\n for i in the_list:\r\n if not func(i, **kwargs):\r\n return False\r\n\r\n return True\r\n\r\n @classmethod\r\n def any(cls, the_list, func, **kwargs):\r\n \"\"\"\r\n Return True if any is True, else False.\r\n Similar to any() but its accept a lambda.\r\n\r\n :param the_list:\r\n :param func: lambda that return bool\r\n :param kwargs: any additional params for func\r\n :return:\r\n \"\"\"\r\n for i in the_list:\r\n if func(i, **kwargs):\r\n return True\r\n\r\n return False\r\n\r\n @classmethod\r\n def prep_select_optgroups(cls, the_list, opt_groups: list, value_attr, display_attr, none_value_label, sort_result=False):\r\n \"\"\"\r\n Prep list to be use as a choice for the ChoiceField\r\n\r\n eg. sensor_choices = Lst.prep_select_optgroups(sensors, ['facility.name', 'zone.name'],\r\n 'id', 'sensor_name', _('Unassigned Sensors'))\r\n\r\n :param the_list: ValueQuerySet, QuerySet or list\r\n :param opt_groups: the group column/attr name or index\r\n :param value_attr: the option value\r\n :param display_attr: the option display text\r\n :return:\r\n \"\"\"\r\n groups = Lst.tuple_multi_group_by(the_list, none_value_label, opt_groups)\r\n\r\n if groups:\r\n result = []\r\n for tp, arr in groups.items():\r\n og_header = ' > '.join(tp)\r\n og_list = []\r\n for row in arr:\r\n og_list.append((Obj.getattr(row, value_attr), Obj.getattr(row, display_attr),))\r\n result.append((og_header, tuple(og_list),))\r\n return tuple(result)\r\n\r\n if sort_result:\r\n return sorted(groups)\r\n return groups\r\n\r\n @classmethod\r\n def get_unique(cls, the_list, default_value=None, unique_attr=None):\r\n \"\"\"\r\n Get a list of unique values in the list, default_value is [] if default_value is set to None.\r\n\r\n :param the_list:\r\n :param default_value: if none value is []\r\n :param unique_attr: select your own unique attribute (in case when the object is unhashable\r\n or you want your own attr)\r\n :rtype list\r\n \"\"\"\r\n if default_value is None:\r\n default_value = []\r\n\r\n if not the_list:\r\n return default_value\r\n\r\n try:\r\n # Src: http://stackoverflow.com/questions/480214\r\n # /how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order\r\n # Src: http://www.peterbe.com/plog/uniqifiers-benchmark\r\n if unique_attr is None:\r\n added_list = set()\r\n add_to_added_list = added_list.add # this static ref for performance reason\r\n return [x for x in the_list if not (x in added_list or add_to_added_list(x))]\r\n\r\n result = []\r\n existed_item = {} # dict is much faster than list when checking existence of a key\r\n for itm in the_list:\r\n key = Obj.getattr(itm, unique_attr)\r\n if key not in existed_item:\r\n result.append(itm)\r\n existed_item[key] = None\r\n return result\r\n except Exception as ex:\r\n log_exception(ex)\r\n return default_value\r\n\r\n @classmethod\r\n def reverse(cls, the_list: list):\r\n \"\"\"\r\n Reverse the order of the items in the list.\r\n :param the_list:\r\n :return:\r\n \"\"\"\r\n if not list:\r\n return []\r\n # return list(reversed(the_list))\r\n return the_list[::-1]\r\n\r\n @classmethod\r\n def contains_all(cls, the_list, *args):\r\n \"\"\"\r\n Check to see if the_list contains all of the args\r\n\r\n :param the_list: the haystack\r\n :param args: the needle\r\n :return:\r\n \"\"\"\r\n return Lst.all(args, lambda x: x in the_list)\r\n\r\n @classmethod\r\n def contains_any(cls, the_list, *args):\r\n \"\"\"\r\n Check to see if the_list contains any of the args\r\n\r\n :param the_list: the haystack\r\n :param args: the needle\r\n :return:\r\n \"\"\"\r\n return Lst.any(args, lambda x: x in the_list)\r\n\r\n @classmethod\r\n def unordered_list_equals(cls, lst_a, lst_b):\r\n if not isinstance(lst_a, list) or not isinstance(lst_b, list):\r\n return False\r\n\r\n if lst_a == lst_b:\r\n return True\r\n\r\n if len(lst_a) != len(lst_b):\r\n return False\r\n\r\n return set(lst_a) == set(lst_b)\r\n\r\n @classmethod\r\n def str_join(cls, lst, separator=', ', value_attr: str=None):\r\n if not lst:\r\n return ''\r\n\r\n str_list = []\r\n for itm in lst:\r\n if value_attr is not None:\r\n itm = Obj.getattr(itm, value_attr)\r\n itm = str(itm)\r\n str_list.append(itm)\r\n return separator.join(str_list)\r\n\r\n @classmethod\r\n def chunks(cls, lst, chunk_size, pad_with=None):\r\n \"\"\"\r\n Split the list into chunks.\r\n eg. [1, 2, 3, 4, 5] (chunk == 2) => result [ [1, 2], [3, 4], [5] ]\r\n \"\"\"\r\n result = []\r\n for i in range(0, len(lst), chunk_size):\r\n result.append(lst[i:i + chunk_size])\r\n\r\n if result and pad_with is not None and len(result[-1]) != chunk_size:\r\n result[-1] = result[-1] + ([pad_with] * (chunk_size - len(result[-1])))\r\n return result\r\n\r\n\r\n @classmethod\r\n def get_first(cls, the_list, default_value=None):\r\n \"\"\"\r\n Get the first item of the list.\r\n\r\n :param the_list:\r\n :param default_value:\r\n :return:\r\n \"\"\"\r\n if the_list:\r\n for itm in the_list:\r\n return itm\r\n return default_value\r\n\r\n @classmethod\r\n def map_to(cls, the_list, attribs: list, default_value=None, execute_callable=True):\r\n \"\"\"\r\n Go through the list and extract the specified attributes\r\n\r\n :param the_list:\r\n :param attribs:\r\n :type default_value: object|dict\r\n :param default_value: either a value for all fields default or pass a dict to supply specific default value.\r\n :return: List of value lists\r\n \"\"\"\r\n result = []\r\n if not the_list:\r\n return result\r\n\r\n for itm in the_list:\r\n row = []\r\n for att in attribs:\r\n specific_default = default_value\r\n if isinstance(default_value, dict) and att in default_value:\r\n specific_default = default_value.get(att, default_value)\r\n value = Obj.getattr(itm, att, specific_default, execute_callable=execute_callable)\r\n row.append(value)\r\n result.append(row)\r\n return result\r\n","sub_path":"django_lazifier/utils/builtin_types/list.py","file_name":"list.py","file_ext":"py","file_size_in_byte":13996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"3855358","text":"\"\"\"\n-------------------------------------------------------------------\n-- Title: Analysis of Coronavirus related Tweets using TwitterAPI\n-- File: TwitterDataRetrieval.py\n-- Purpose: Script used to retrieve the tweets through TwitterAPI.\n-- Author: Georgios Spyrou\n-- Date: 01/03/2020\n-------------------------------------------------------------------\n\"\"\"\n\n# Data retrival from Twitter API\n\n# Import dependencies\nimport os\n\nimport json\nfrom datetime import datetime, timedelta\n\n# Twitter related\nfrom searchtweets import load_credentials\nfrom searchtweets import gen_rule_payload\nfrom searchtweets import ResultStream\n\n# Set up the project environment\n\n# Secure location of the required keys to connect to the API\n# This config also contains the search query\njson_loc = 'C:\\\\Users\\\\george\\\\Desktop\\\\Twitter_Project\\\\Twitter\\\\twitter_config.json'\n\nwith open(json_loc) as json_file:\n configFile = json.load(json_file)\n\n# Project folder location and keys\nos.chdir(configFile[\"project_directory\"])\n\n# Import the custom functions that we will use to retrieve and analyse\n# the data, and use the API to save the data to a .jsonl file.\n\nimport twitterCustomFunc as twf\n\ntwitter_keys_loc = configFile[\"keys\"]\n\n# Load the credentials to get access to the API\npremium_search_args = load_credentials(twitter_keys_loc,\n yaml_key=\"search_tweets_api\",\n env_overwrite=False)\nprint(premium_search_args)\n\n\n# Set tweet extraction period and create a list of days of interest\nfromDate = \"2020-03-12\"\ntoDate = \"2020-03-18\"\n\ndaysList = [fromDate]\n\nwhile fromDate != toDate:\n date = datetime.strptime(fromDate, \"%Y-%m-%d\")\n mod_date = date + timedelta(days=2)\n incrementedDay = datetime.strftime(mod_date, \"%Y-%m-%d\")\n daysList.append(incrementedDay)\n \n fromDate = incrementedDay\n\n# Retrieve the data for each day from the API\nfor day in daysList:\n \n dayNhourList = twf.createDateTimeFrame(day, hourSep=2)\n \n for hs in dayNhourList:\n fromDate = hs[0]\n toDate = hs[1]\n # Create the searching rule for the stream\n rule = gen_rule_payload(pt_rule=configFile['search_query'],\n from_date=fromDate,\n to_date=toDate ,\n results_per_call = 100)\n\n # Set up the stream\n rs = ResultStream(rule_payload=rule,\n max_results=100,\n **premium_search_args)\n\n # Create a .jsonl with the results of the Stream query\n #file_date = datetime.now().strftime('%Y_%m_%d_%H_%M')\n file_date = '_'.join(hs).replace(' ', '').replace(':','')\n filename = os.path.join(configFile[\"outputFiles\"],\n f'twitter_30day_results_{file_date}.jsonl')\n \n # Write the data received from the API to a file\n with open(filename, 'a', encoding='utf-8') as f:\n cntr = 0\n for tweet in rs.stream():\n cntr += 1\n if cntr % 100 == 0:\n n_str, cr_date = str(cntr), tweet['created_at']\n print(f'\\n {n_str}: {cr_date}')\n json.dump(tweet, f)\n f.write('\\n')\n print(f'Created file {f}:')\n","sub_path":"Code/TwitterDataRetrieval.py","file_name":"TwitterDataRetrieval.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"405848420","text":"from django.test import TestCase\nfrom django.http import HttpRequest\nfrom django.shortcuts import render\nfrom django.template.loader import render_to_string\n\n#Create a simple model\nfrom django.db import models\nclass TestModel(models.Model):\n title = models.CharField(max_length=250)\n\n#Create a simple form\nfrom django.forms import ModelForm\nclass TestForm(ModelForm):\n class Meta:\n model = TestModel\n exclude = []\n\ndef test_view(request):\n form = TestForm()\n return render(request,\n 'custom_tests/bootstrap_form.html',\n {'form': form})\n\n# GET /record\nclass BootstrapFormFilterTest(TestCase):\n\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n\n def test_test_view_returns_correct_html(self):\n request = HttpRequest()\n response = test_view(request)\n expected_html = render_to_string('custom_tests/bootstrap_form.html', {'form': TestForm()})\n self.assertEqual(response.content.decode(), expected_html)\n\n\n def test_add_class_inserts_correct_class(self):\n request = HttpRequest()\n response = test_view(request)\n expected_html = render_to_string('custom_tests/bootstrap_form.html', {'form': TestForm()})\n self.assertEqual(expected_html, response.content.decode())\n self.assertInHTML(' ',\n response.content.decode()\n )\n\n def test_add_attributes_inserts_correct_attr(self):\n request = HttpRequest()\n response = test_view(request)\n expected_html = render_to_string('custom_tests/bootstrap_form.html', {'form': TestForm()})\n self.assertEqual(expected_html, response.content.decode())\n self.assertInHTML(' ',\n response.content.decode()\n )\n\n","sub_path":"shellac/tests/custom/test_bootstrapForm_unit.py","file_name":"test_bootstrapForm_unit.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"36016375","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 22 10:12:12 2019\n\n@author: Osman\n\n\ndataset : https://www.kaggle.com/tongpython/cat-and-dog\n\nas result you might find val_acc = 0.81 , loss = 0.44 or higher or a bit less.\n\n\n\"\"\"\n\n\nimport keras\nimport pandas as pd\nimport numpy as np\n\n\n## you have to change these values\n# these are the source code of cats and dogs for train and test on your computer. these are for me, change them for you.\ndataset_source_on_your_computer_for_train = r'C:\\Users\\Osman\\Desktop\\ann_cats_dogs\\training_set'\ndataset_source_on_your_computer_for_test = r'C:\\Users\\Osman\\Desktop\\ann_cats_dogs\\test_set'\n#\n\n\n# initialising the cnn\n\ncnn_model = keras.Sequential()\n\n# step 1 - convolution\n\ncnn_model.add(keras.layers.Conv2D(32,(3,3),input_shape = (64,64,3),activation='relu'))\n\n# step 2 - pooling\n\ncnn_model.add(keras.layers.MaxPooling2D())\n\n# step n - add how much layers you want.\n\ncnn_model.add(keras.layers.Conv2D(32,(3,3),activation='relu'))\n\n# step n - pooling\n\ncnn_model.add(keras.layers.MaxPooling2D())\n\n\n\n# step 3 - flettining\n\ncnn_model.add(keras.layers.Flatten())\n\n# step 4 - build ann\n\ncnn_model.add(keras.layers.Dense(128 , activation='relu'))\ncnn_model.add(keras.layers.Dense(1 , activation='sigmoid'))\n\ncnn_model.compile('adam',loss = keras.losses.binary_crossentropy,metrics=['acc'])\n\n\n# fitting the cnn images.\nfrom keras.preprocessing.image import ImageDataGenerator\n\n\ntrain_datagen = ImageDataGenerator(\n rescale=1./255,\n shear_range=0.2,\n zoom_range=0.2,\n horizontal_flip=True)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)\n\ntraining_set = train_datagen.flow_from_directory(\n dataset_source_on_your_computer_for_train,\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\ntest_set = test_datagen.flow_from_directory(\n dataset_source_on_your_computer_for_test,\n target_size=(64, 64),\n batch_size=32,\n class_mode='binary')\n\ncnn_model.fit_generator(training_set,\n steps_per_epoch=8000,\n epochs=25,\n validation_data=test_set,\n validation_steps=2023)\n\n\n\n\n\n\n","sub_path":"7-Kedi Köpek Tanıma/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"206147476","text":"import gurobipy as gp\nimport openpyxl\nfrom gurobipy import GRB\nimport pandas as pa\n\n\nworkbook2 = openpyxl.load_workbook(\"DataFile3.xlsx\")\nsheets=[\"Region1\",\"Region2\",\"Region3\"]\ndef getData():\n capacity=[]\n PatientData=[]\n resreq =[]\n for sheet in sheets:\n sheet_read= workbook2[sheet]\n capacity_range = sheet_read[\"B13:G13\"]\n for cell in capacity_range:\n capacity.append([i.value for i in cell])\n x_range = sheet_read[\"B3:G12\"]\n PatientData.append( [[cell.value if cell.value is not None else 0 for cell in row] for row in x_range])\n resreq.append([[cell.value if cell.value is not None else 0 for cell in row] for row in sheet_read[\"M3:N22\"]])\n # Ndays = len(capacity[0])\n #capacity = [capacity[i:i + Ndays] for i in range(0, len(capacity), Ndays)]\n print(\"X\")\n print(PatientData)\n print(\"R`equested Resources\")\n print(resreq)\n print(\"Capacity\")\n print(capacity)\n return capacity, PatientData,resreq\n\ndef periodic_problem(NPatients, Ndays, NResources, Nregions):\n #sets\n model = gp.Model(\"OptimsationModel\")\n patients = range(NPatients)\n days = range(Ndays)\n resources=range(NResources)\n regions=range (Nregions)\n #parameters\n capacity,x, resreq= getData()\n regionsSet= {\n 0: [1, 2],\n 1: [0,2],\n 2: [0,1]\n }\n\n # Decision Variables\n y=model.addVars(regions,patients,lb=0,vtype=GRB.BINARY,name= \"OwnRegionPatientTaken\" )\n\n z=model.addVars(regions,regions,patients,lb=0,vtype=GRB.BINARY,name=\"OtherRegionPatientTaken\" )\n\n\n\n\n # Objective\n\n totalPatiens = gp.quicksum(y)+gp.quicksum(z)\n model.setObjective(totalPatiens, GRB.MAXIMIZE)\n\n # Contranints\n #for every region, patient taken and transffered patient taken should be less than its capacity\n for r in regionsSet:\n for i in days:\n\n model.addConstr(gp.quicksum(x[r][m][i]*y[r,m] for m in patients)+gp.quicksum(gp.quicksum((x[r2][m][i]*(1-y[r2,m]))*z[r,r2,m] for m in patients) for r2 in regionsSet[r])<=capacity[r][i])\n\n # transferred patient of region can only go to one region\n for r in regionsSet:\n for i in days:\n for m in patients:\n model.addConstr(gp.quicksum(z[r2,r,m] for r2 in regionsSet[r] )<=1)\n #ownpatients taken should not be less than the transferredpatient taken\n for r in regionsSet:\n\n model.addConstr(gp.quicksum(y[r,m] for m in patients)>=gp.quicksum( gp.quicksum(z[r2,r,m]for m in patients)for r2 in regionsSet[r] ))\n\n for r in regionsSet:\n for m in patients:\n model.addConstr(z[r,r,m]==0)\n\n for r in regionsSet:\n for i in days:\n for m in patients:\n model.addConstr(x[r][m][i] >= y[r,m])\n model.addConstr(x[r][m][i] >=gp.quicksum(z[r2,r,m] for r2 in regionsSet[r]))\n\n for r in regionsSet:\n for i in days:\n for m in patients:\n model.addConstr(y[r,m] + gp.quicksum(z[r2, r, m] for r2 in regionsSet[r])<=x[r][m][i])\n\n\n # print(remaingCap)\n\n model.update()\n model.optimize()\n\n print(\"\\nPatient Assignments:\")\n for var in y.values():\n print(f\"{var.VarName} = {var.x}\")\n for var in z.values():\n print(f\"{var.VarName} = {var.x}\")\n\n print(totalPatiens)\nperiodic_problem(10, 5, 2, 3)\n\n","sub_path":"Gurobi/ProposalModel5.py","file_name":"ProposalModel5.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"463173189","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 31 01:01:00 2021\r\n\r\n@author: Samsung\r\n\"\"\"\r\n\r\n#arboles.py\r\n\r\n\r\n#EJERCICIOS DE CLASE 04 AL FINAL DEL CODIGO.\r\n\r\n#Ejercicio 3.18: Lectura de los árboles de un parque\r\n\r\n\r\nimport csv\r\ndef leer_parque (nombre_archivo, parque):\r\n lista_arboles = []\r\n f = open(nombre_archivo,'rt', encoding=\"utf-8\")\r\n rows = csv.reader(f)\r\n headers = next(rows)\r\n \r\n for arbol in rows:\r\n dic_arboles = dict(zip(headers, arbol))\r\n \r\n if dic_arboles ['espacio_ve'] == parque:\r\n lista_arboles.append(dic_arboles)\r\n \r\n return lista_arboles\r\n\r\nlista_arboles = leer_parque('../data/arbolado-en-espacios-verdes.csv', 'GENERAL PAZ')\r\nprint(lista_arboles)\r\n\r\n#%%\r\n#Ejercicio 3.19: Determinar las especies en un parque\r\n\r\ndef especies (lista_arboles):\r\n especie = []\r\n for arbol in lista_arboles:\r\n especie.append(arbol ['nombre_gen']) #primero creo una lista con todos los nombres de especieas de cada arbol. aparecen repetidos\r\n \r\n \r\n return set(especie) #antes de pedir q me devuelva la lista le digo q me elimine los duplicados\r\n\r\n\r\nespecie = especies(lista_arboles)\r\nprint(especie)\r\n\r\n\r\n#%%\r\n#Ejercicio 3.20: Contar ejemplares por especie\r\ndef contar_ejemplares (lista_arboles):\r\n from collections import Counter\r\n ejemplares = Counter()\r\n for arbol in lista_arboles:\r\n ejemplares[arbol['nombre_gen']] += 1\r\n \r\n return ejemplares\r\n\r\nejemplares = contar_ejemplares(lista_arboles)\r\nprint (ejemplares)\r\n \r\n\r\n#%%\r\n# GENERAL PAZ\r\n\r\nlista_arboles = leer_parque('../data/arbolado-en-espacios-verdes.csv', 'GENERAL PAZ')\r\n\r\nejemplares = contar_ejemplares(lista_arboles)\r\n\r\n\r\nranking_GP = ejemplares.most_common(5)\r\n\r\nprint('RANKING CANTIDAD: ', ranking_GP) \r\n\r\n\r\n\r\n\r\n# LOS ANDES\r\nlista_arboles = leer_parque('../data/arbolado-en-espacios-verdes.csv', 'ANDES, LOS')\r\n\r\nejemplares = contar_ejemplares(lista_arboles)\r\n\r\n\r\n\r\nranking = ejemplares.most_common(5)\r\n\r\nprint('RANKING CANTIDAD: ', ranking) \r\n\r\n\r\n\r\n# CENTENARIO\r\n\r\nlista_arboles = leer_parque('../data/arbolado-en-espacios-verdes.csv', 'CENTENARIO')\r\n\r\nejemplares = contar_ejemplares(lista_arboles)\r\n\r\n\r\nranking = ejemplares.most_common(5)\r\nprint('RANKING CANTIDAD : ', ranking)\r\n\r\n\r\n#%%\r\n\r\n#Ejercicio 3.21: Alturas de una especie en una lista\r\n# GENERAL PAZ\r\n\r\n\r\n\r\ndef obtener_alturas(lista_arboles, especie):\r\n alturas = []\r\n for arbol in lista_arboles:\r\n if arbol ['nombre_com'] == especie:\r\n alturas.append(float(arbol['altura_tot']))\r\n return alturas\r\n\r\n#GENERAL PAZ\r\nlista_arboles = leer_parque('../data/arbolado-en-espacios-verdes.csv', 'GENERAL PAZ')\r\nalturasJ = obtener_alturas(lista_arboles, 'Jacarandá')\r\n\r\nprint(f' GENERAL PAZ ---> MAXIMO: {max(alturasJ)} PROMEDIO: {sum(alturasJ) /len(alturasJ)} ')\r\n\r\n# LOS ANDES\r\nlista_arboles = leer_parque('../data/arbolado-en-espacios-verdes.csv', 'ANDES, LOS')\r\nalturasJ = obtener_alturas(lista_arboles, 'Jacarandá')\r\nprint(f' LOS ANDES ---> MAXIMO: {max(alturasJ)} PROMEDIO: {sum(alturasJ) /len(alturasJ)} ')\r\n\r\n\r\n# CENTENARIO\r\n\r\nlista_arboles = leer_parque('../data/arbolado-en-espacios-verdes.csv', 'CENTENARIO')\r\nalturasJ = obtener_alturas(lista_arboles, 'Jacarandá')\r\nprint(f' CENTENARIO ---> MAXIMO: {max(alturasJ)} PROMEDIO: {sum(alturasJ) /len(alturasJ)} ')\r\n\r\n\r\n\r\n#%%\r\n\r\n#Ejercicio 3.22: Inclinaciones por especie de una lista\r\n\r\ndef obtener_inclinaciones(lista_arboles, especie):\r\n inclinaciones = []\r\n for arbol in lista_arboles:\r\n if arbol ['nombre_com'] == especie:\r\n inclinaciones.append(float(arbol['inclinacio']))\r\n return inclinaciones\r\n\r\nlista_arboles = leer_parque('data/arbolado-en-espacios-verdes.csv', 'GENERAL PAZ')\r\ninclinacionesJ = obtener_inclinaciones(lista_arboles, 'Jacarandá')\r\nprint(inclinacionesJ)\r\n\r\n#%%\r\n#Ejercicio 4.15: Lectura de todos los árboles\r\n\r\nimport csv\r\ndef leer_arboles(nombre_archivo):\r\n f = open('../data/arbolado-en-espacios-verdes.csv','rt', encoding=\"utf-8\")\r\n rows = csv.reader(f)\r\n \r\n headers = next(rows)\r\n types = [float, float, int, int, int, int, int, str, str, str, str, str, str,str,str, float, float]\r\n \r\n \r\n row = next(rows)\r\n \r\n \r\n arboleda = [{name:func(val) for name, func, val in zip (headers, types, row)} for row in rows]\r\n return arboleda\r\n\r\narboleda = leer_arboles('../data/arbolado-en-espacios-verdes.csv')\r\nprint(arboleda)\r\n#%%\r\n#Ejercicio 4.16: Lista de altos de Jacarandá\r\naltura_jacaranda = [float(arbol['altura_tot']) for arbol in arboleda if arbol['nombre_com'] == 'Jacarandá']\r\n\r\n#%%\r\n#Ejercicio 4.17: Lista de altos y diámetros de Jacarandá\r\n\r\nalt_diam = [(float(arbol['altura_tot']), float(arbol['diametro'])) for arbol in arboleda if arbol['nombre_com'] == 'Jacarandá']\r\n\r\n\r\n#%%\r\n#Ejercicio 4.18: Diccionario con medidas\r\n\r\ndef medidas_de_especies(especies, arboleda):\r\n \r\n pop = [[(float(arbol['altura_tot']), float(arbol['diametro']))for arbol in arboleda if arbol['nombre_com'] == especie] for especie in especies]\r\n \r\n dic = {nombre:valor for nombre, valor in zip(especies,pop)} \r\n return dic\r\n\r\n \r\ndic_medidas = medidas_de_especies(['Eucalipto', 'Palo borracho rosado', 'Jacarandá'], arboleda)\r\nprint(dic_medidas)\r\n\r\n\r\n#%%\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n#Ejercicio 5.24: Histograma de altos de Jacarandás #Funcion del ej 4.16\r\nplt.hist(altura_jacaranda, bins = 50)\r\n\r\n\r\n#%%\r\n#Ejercicio 5.25: Scatterplot (diámetro vs alto) de Jacarandás #Func del ej 4.17\r\n\r\nalt_diam = np.array(alt_diam)#Convierto en un ndarray\r\n\r\nplt.scatter(alt_diam[:,1], alt_diam[:,0], alpha = 0.3, c = 'g') # x = diam, y = altura\r\n\r\nplt.xlabel(\"diametro (cm)\")\r\nplt.ylabel(\"alto (m)\")\r\nplt.title(\"Relación diámetro-alto para Jacarandás\")\r\n\r\n\r\n\r\n\r\n\r\n#%%\r\n#Ejercicio 5.26: Scatterplot para diferentes especies\r\neucalipto = np.array(dic_medidas['Eucalipto'])\r\npalo = np.array(dic_medidas['Palo borracho rosado'])\r\njaca = np.array(dic_medidas['Jacarandá'])\r\n\r\ndef plot_eucalipto():\r\n plt.scatter(eucalipto[:,1], eucalipto[:,0], alpha = 0.3) # x = diam, y = altura\r\n plt.xlabel(\"diametro (cm)\")\r\n plt.ylabel(\"alto (m)\")\r\n plt.title(\"Relación diámetro-alto para Eucalipto\")\r\n \r\n#%%\r\ndef plot_palo():\r\n plt.scatter(palo[:,1],palo[:,0], alpha = 0.3) # x = diam, y = altura\r\n plt.xlabel(\"diametro (cm)\")\r\n plt.ylabel(\"alto (m)\")\r\n plt.title(\"Relación diámetro-alto para Palo borracho rosado\")\r\n \r\n#%%\r\ndef plot_jacaranda():\r\n plt.scatter(jaca[:,1], jaca[:,0], alpha = 0.3) # x = diam, y = altura\r\n plt.xlabel(\"diametro (cm)\")\r\n plt.ylabel(\"alto (m)\")\r\n plt.title(\"Relación diámetro-alto para Jacarandás\")\r\n ","sub_path":"05_Random_Plt_Dbg/arboles.py","file_name":"arboles.py","file_ext":"py","file_size_in_byte":6713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"226584349","text":"import numpy as np\nimport pandas as pd\nfrom scipy.spatial.distance import euclidean\nfrom fastdtw import fastdtw\nfrom dtw import dtw\nfrom statistics import median\n\n\n\n\ndef dtw_val_gen(sub_section1,sub_section2,dt):\n #print(\"dtw val gen start\")\n if (dt == 0): #Normal DTW\n x=np.array(sub_section1).reshape(-1, 1)\n y=np.array(sub_section2).reshape(-1, 1)\n euclidean_norm = lambda x, y: np.abs(x - y)\n dtw_value, cost_matrix, acc_cost_matrix, path = dtw(x, y, dist=euclidean_norm)\n\n else: #Fast DTW\n x = np.array(sub_section1)\n y = np.array(sub_section2)\n dtw_value, path = fastdtw(x, y, dist=euclidean)\n return dtw_value\n\n\n\n\ndef dtw_rank_gen(dtw_temp):\n \n #med=(dtw_temp['dtw_value'] ).tolist()\n #print(dtw_temp['dtw_value'])\n #if(len(dtw_temp)> 5) :\n #dtw_temp = dtw_temp[dtw_temp['dtw_value'] < median(med) ] #median(med)\n \n dtw_temp= dtw_temp.sort_values(by=['dtw_value'])\n #print(dtw_temp['dtw_value'])\n rank_list=[]\n for m in range(1, len(dtw_temp)+1):\n rank_list.append(m)\n dtw_temp.insert(loc=5, column='ranks', value=rank_list)\n \n return dtw_temp\n\n\n\n\"\"\"------------- Y_Alphabetize ------------- \"\"\"\ndef alphabetize_ts(sub_section,y_alpha_size):\n y_alphabets = get_y_alphabets(y_alpha_size)\n mean_val = x_distrubted_values(sub_section)\n y_alpha_val = min(y_alphabets, key=lambda x:abs(x-mean_val))\n y_alpha_idx = y_alphabets.index(y_alpha_val)\n curr_word = index_to_letter(y_alpha_idx)\n\n return(curr_word)\n\n\"\"\"------------- index to letter ------------- \"\"\"\n\n\ndef index_to_letter(idx):\n \"\"\"Convert a numerical index to a char.\"\"\"\n if 0 <= idx < 20:\n return chr(97 + idx)\n else:\n raise ValueError('A wrong idx value supplied.')\n\n\n\"\"\"------------- X-axis Distribution ------------- \"\"\"\n\ndef x_distrubted_values(series):\n mean = np.mean(series)\n median = sorted(series)[len(series) // 2]\n return mean\n\n\n\"\"\"------------- Normalization ------------- \"\"\"\n\ndef normalize(x):\n epsilon = 1e-6\n X = np.asanyarray(x)\n if np.nanstd(X) < epsilon:\n res = []\n for entry in X:\n if not np.isnan(entry):\n res.append(0)\n else:\n res.append(np.nan)\n return res\n return (X - np.nanmean(X)) / np.nanstd(X)\n\ndef normal_distribution(x):\n x = (x-min(x))/(max(x)-min(x))\n return x\n\n\"\"\"------------- Y-axis Distribution ------------- \"\"\"\ndef break_points_gaussian(size):\n options = {\n 3: np.array([ -0.43, 0.43]),\n 4: np.array([ -0.67, 0, 0.67]),\n 5: np.array([ -0.84, -0.25, 0.25, 0.84]),\n 6: np.array([ -0.97, -0.43, 0, 0.43, 0.97]),\n 7: np.array([ -1.07, -0.57, -0.18, 0.18, 0.57, 1.07]),\n 8: np.array([ -1.15, -0.67, -0.32, 0, 0.32, 0.67, 1.15]),\n 9: np.array([ -1.22, -0.76, -0.43, -0.14, 0.14, 0.43, 0.76, 1.22]),\n 10: np.array([ -1.28, -0.84, -0.52, -0.25, 0, 0.25, 0.52, 0.84, 1.28]),\n 11: np.array([ -1.34, -0.91, -0.6, -0.35, -0.11, 0.11, 0.35, 0.6, 0.91, 1.34]),\n 12: np.array([ -1.38, -0.97, -0.67, -0.43, -0.21, 0, 0.21, 0.43, 0.67, 0.97, 1.38]),\n 13: np.array([ -1.43, -1.02, -0.74, -0.5, -0.29, -0.1, 0.1, 0.29, 0.5, 0.74, 1.02, 1.43]),\n 14: np.array([ -1.47, -1.07, -0.79, -0.57, -0.37, -0.18, 0, 0.18, 0.37, 0.57, 0.79, 1.07, 1.47]),\n 15: np.array([ -1.5, -1.11, -0.84, -0.62, -0.43, -0.25, -0.08, 0.08, 0.25, 0.43, 0.62, 0.84, 1.11, 1.5]),\n 16: np.array([ -1.53, -1.15, -0.89, -0.67, -0.49, -0.32, -0.16, 0, 0.16, 0.32, 0.49, 0.67, 0.89, 1.15, 1.53]),\n 17: np.array([ -1.56, -1.19, -0.93, -0.72, -0.54, -0.38, -0.22, -0.07, 0.07, 0.22, 0.38, 0.54, 0.72, 0.93, 1.19, 1.56]),\n 18: np.array([ -1.59, -1.22, -0.97, -0.76, -0.59, -0.43, -0.28, -0.14, 0, 0.14, 0.28, 0.43, 0.59, 0.76, 0.97, 1.22, 1.59]),\n 19: np.array([ -1.62, -1.25, -1, -0.8, -0.63, -0.48, -0.34, -0.2, -0.07, 0.07, 0.2, 0.34, 0.48, 0.63, 0.8, 1, 1.25, 1.62]),\n 20: np.array([ -1.64, -1.28, -1.04, -0.84, -0.67, -0.52, -0.39, -0.25, -0.13, 0, 0.13, 0.25, 0.39, 0.52, 0.67, 0.84, 1.04, 1.28, 1.64]),\n }\n\n return options[size]\n\n\n\"\"\"------------- Get y_alphabets ------------- \"\"\"\n\ndef get_y_alphabets(y_alpha_size):\n y_alpha_size\n #y_alphabets = break_points_quantiles(y_alphabet_size).tolist()\n y_alphabets = break_points_gaussian(y_alpha_size).tolist()\n return y_alphabets\n\n\n\n\"\"\"------------- Hamming Distance ------------- \"\"\"\ndef hamming_distance1(string1, string2):\n distance = 0\n L = len(string1)\n for i in range(L):\n if string1[i] != string2[i]:\n distance += 1\n return distance\n\n\ndef hamming_distance(s1, s2):\n if len(s1) != len(s2):\n raise ValueError(\"Undefined for sequences of unequal length\")\n return sum(el1 != el2 for el1, el2 in zip(s1, s2))\n","sub_path":"Sax/Final_code_test/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":5045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"471607109","text":"\"\"\"\nCrossval tests multiple potential hyperparameter combinations for the system (a neural net)\n(TODO: test multiple nets per option set and take the best- maybe 10?)\n\"\"\"\nimport numpy as np\nimport copy\n\nimport system as sys\n\n#suppress nan warnings\nnp.seterr(divide = 'ignore', invalid = 'ignore', over = 'ignore')\n\n#crossval options:\niterations = 500 #number of training iterations for each net\n\n#dt.DataSource options:\ncv_preprocessing_options = [\n [['mean'],['stdev']]\n ] #Preprocessing: ['mean']; ['stdev']; ['pca',var]; ['whitening',var]\n #done in same order as the array\n #pca automatically standardizes based on mean and stdev, while whitening automatically does pca\n #thus the only time you should have 2 elements in the array is if you want to do both mean and stdev standardization\ntrain_test_CV_split = [0.6, 0.2, 0.2] #fraction of data split into the 3 groups, should add up to 1\nfile_name = \"iris.data\"\n\n#sys.ystem options:\ncv_options = {}\n\ncv_options['num_examples'] = [5, 20, 50]\n\n#Regularization: ['none']; ['l1', lambda]; ['l2', lambda]; ['elastic', lambda1, lambda2]; (dropout)\ncv_options['Reg'] = [\n ['l1', 0.01],\n ['l1', 0.1],\n\n ['l2', 0.01],\n ['l2', 0.1],\n ]\n\ncv_options['Loss'] = ['logistic'] #Loss function: logistic, (cross-entropy)\n\ncv_options['Act'] = ['tanh'] #Activation function: sigmoid, tanh, ReLU\n\n#Learning method: ['vanilla']; ['momentum', mu]; ['nesterov', mu]\ncv_options['Learn'] = [\n ['nesterov', 0.5],\n ['nesterov', 0.7],\n ['nesterov', 0.9],\n ['nesterov', 0.95]\n ]\n\n#Learning rate: ['constant', alpha]; ['step', alpha, fraction, num_epochs]; ['exp', alpha, k]; ['1/t', alpha, k]\ncv_options['Rate'] = [\n ['step', 0.1, 0.95, 20],\n ['step', 0.1, 0.9, 20],\n ['step', 0.1, 0.9, 35],\n ['step', 0.1, 0.9, 50],\n ['step', 0.1, 0.75, 20],\n ['step', 0.1, 0.5, 20],\n ]\n\n#total number of options to iterate over:\n#datasource: 2, system: 6\nsystems = []\ncosts = []\n\n#create all systems to be tested:\noptions = {}\nprint('Initializing option sets...')\nfor i_preprocessing_options in range(0, len(cv_preprocessing_options)):\n preprocessing_options = cv_preprocessing_options[i_preprocessing_options]\n\n for i_num_examples in range(0, len(cv_options['num_examples'])):\n options['num_examples'] = cv_options['num_examples'][i_num_examples]\n\n for i_Reg in range(0, len(cv_options['Reg'])):\n options['Reg'] = cv_options['Reg'][i_Reg]\n\n for i_Loss in range(0, len(cv_options['Loss'])):\n options['Loss'] = cv_options['Loss'][i_Loss]\n\n for i_Act in range(0, len(cv_options['Act'])):\n options['Act'] = cv_options['Act'][i_Act]\n\n for i_Learn in range(0, len(cv_options['Learn'])):\n options['Learn'] = cv_options['Learn'][i_Learn]\n\n for i_Rate in range(0, len(cv_options['Rate'])):\n options['Rate'] = cv_options['Rate'][i_Rate]\n\n systems.append(sys.System(options, preprocessing_options, file_name, train_test_CV_split))\n options = copy.deepcopy(options) #each system has its own options\n\n#test the systems (only keep final cv_cost):\nprint('Number of option sets:', len(systems))\nfor i in range(0, len(systems)):\n system = systems[i]\n ignore, ignore, cv_cost = system.doManyIterations(iterations)\n \n cv_cost = cv_cost[-1] #look at the final cost\n cv_cost = np.sum(cv_cost) / cv_cost.shape[0] #avg over all classes\n \n costs.append(cv_cost)\n\n print('.', end='')\nprint()\n\nminimums = np.where(costs == np.nanmin(costs))\nfor i in range(0, len(minimums)):\n i_min = minimums[i][0]\n system = systems[i_min]\n cost = costs[i_min]\n options = system.options\n preprocessing_options = system.dataSource.preprocessing_options\n\n print('Cost:', cost)\n print('Options:', options)\n print('Preprocessing:', preprocessing_options)\n","sub_path":"crossval.py","file_name":"crossval.py","file_ext":"py","file_size_in_byte":4399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"191551514","text":"import sys\r\nimport copy\r\nimport time\r\n\r\n# THIS VERSION IS BACKTRACKING SEARCH + AC3\r\n# Running script: given code can be run with the command:\r\n# python file.py, ./path/to/init_state.txt ./output/output.txt\r\n\r\n#This class is used to keep track of what values can be used in that position in the sudoku puzzle\r\nclass Position:\r\n def __init__(self, value):\r\n self.domain = set()\r\n self.value = value\r\n self.unassignedNeighbours = set()\r\n \r\n def __str__(self):\r\n return str(self.value)\r\n\r\n#This class represents the sudoku puzzle and is used to solve a sudoku puzzle\r\nclass Puzzle:\r\n def __init__(self, solution, unusedRowValues, unusedColumnValues, unusedBoxValues):\r\n self.nodeCount = 0\r\n self.solution = solution\r\n self.unusedRowValues = unusedRowValues\r\n self.unusedColumnValues = unusedColumnValues\r\n self.unusedBoxValues = unusedBoxValues\r\n #Seting the domains for all positions\r\n for r in range(9):\r\n for c in range(9):\r\n self.solution[r][c].domain = self.unusedRowValues[r].intersection(self.unusedColumnValues[c], self.unusedBoxValues[r//3][c//3])\r\n self.solution[r][c].unassignedNeighbours = self.getUnassignedNeighbours(r, c)\r\n \r\n #Gets all unassigned neighbours of all positions\r\n def getUnusedNeighbours(self):\r\n for r in range(9):\r\n for c in range(9):\r\n self.solution[r][c].unassignedNeighbours = self.getUnassignedNeighbours(r, c)\r\n \r\n #Gets unassigned neighbours of a particulat position\r\n def getUnassignedNeighbours(self, r, c):\r\n unassignedNeighbours = set()\r\n for i in range(9):\r\n if i != c and self.solution[r][i].value == 0:\r\n unassignedNeighbours.add((r, i))\r\n if i != r and self.solution[i][c].value == 0:\r\n unassignedNeighbours.add((i, c))\r\n boxRow = r // 3 * 3\r\n boxColumn = c // 3 * 3\r\n for i in range(boxRow, boxRow + 3):\r\n for j in range(boxColumn, boxColumn + 3):\r\n if i != r and j != c and self.solution[i][j].value == 0:\r\n unassignedNeighbours.add((i, j))\r\n return unassignedNeighbours\r\n \r\n #Used to choose the position that will be assigned. It currently just chooses the first unassigned position\r\n def choosePosition(self):\r\n row = -1\r\n column = -1\r\n min = 10000\r\n for r in range(9):\r\n for c in range(9):\r\n if self.solution[r][c].value == 0:\r\n if len(self.solution[r][c].domain) < min:\r\n min = len(self.solution[r][c].domain)\r\n row = r\r\n column = c\r\n return (row, column)\r\n \r\n #Used to removed a value from UnusedValues for a row/column\r\n def removeFromUnusedValues(self, r, c, value):\r\n self.unusedRowValues[r].remove(value)\r\n self.unusedColumnValues[c].remove(value)\r\n self.unusedBoxValues[r//3][c//3].remove(value)\r\n \r\n #Used to add a value to UnusedValues for a row/column\r\n def addToUnusedValues(self, r, c, value):\r\n self.unusedRowValues[r].add(value)\r\n self.unusedColumnValues[c].add(value)\r\n self.unusedBoxValues[r//3][c//3].add(value)\r\n \r\n #Used to update all domains whenever a change is made\r\n def updatePositionDomains(self):\r\n for r in range(9):\r\n for c in range(9):\r\n self.solution[r][c].domain = self.unusedRowValues[r].intersection(self.unusedColumnValues[c], self.unusedBoxValues[r//3][c//3])\r\n \r\n #Used to assign a value to a position\r\n def assignValue(self, row, column, value, changes):\r\n self.solution[row][column].value = value\r\n for (r, c) in self.solution[row][column].unassignedNeighbours:\r\n self.solution[r][c].unassignedNeighbours.remove((row, column))\r\n if self.solution[r][c].value == 0 and (value in self.solution[r][c].domain):\r\n self.solution[r][c].domain.remove(value)\r\n if changes.has_key((r, c)):\r\n changes.add(value)\r\n else:\r\n changes[(r, c)] = set([value])\r\n self.AC3(changes)\r\n \r\n #Used to undo the assignment to a position\r\n def removeAssignment(self, row, column, changes):\r\n value = self.solution[row][column].value\r\n self.solution[row][column].value = 0\r\n for (r, c) in self.solution[row][column].unassignedNeighbours:\r\n self.solution[r][c].unassignedNeighbours.add((row, column))\r\n self.undoAC3(changes)\r\n \r\n \r\n #Used to check if we have found a solution\r\n def isGoal(self):\r\n for r in range(9):\r\n for c in range(9):\r\n if self.solution[r][c].value == 0:\r\n return False\r\n return True\r\n \r\n #Used to check whether a solution is possible after the latest assignment\r\n def isValidAssignment(self):\r\n for r in range(9):\r\n for c in range(9):\r\n if len(self.solution[r][c].domain) == 0 and self.solution[r][c].value == 0:\r\n return False\r\n return True\r\n \r\n def createQueue(self):\r\n q = list()\r\n for row in range(9):\r\n for column in range(9):\r\n if self.solution[row][column].value != 0:\r\n continue\r\n for (r, c) in self.solution[row][column].unassignedNeighbours:\r\n if len(self.solution[r][c].domain) == 1 and self.solution[r][c].value == 0:\r\n q.append(((row, column), (r, c)))\r\n return q\r\n \r\n def updateQueue(self, q, row, column, r, c):\r\n for (i, j) in self.solution[row][column].unassignedNeighbours:\r\n if (i, j) != (row, column) and (i, j) != (r, c) and self.solution[i][j].value == 0:\r\n q.append(((i,j), (row, column)))\r\n \r\n def revise(self, row, column, r, c, changes):\r\n myDomain = self.solution[row][column].domain\r\n neighbourDomain = self.solution[r][c].domain\r\n revise = False\r\n if len(neighbourDomain) != 1:\r\n return False\r\n for n in neighbourDomain:\r\n if n in myDomain:\r\n myDomain.remove(n)\r\n revise = True\r\n if changes.has_key((row, column)):\r\n changes[(row, column)].add(n)\r\n else:\r\n changes[(row, column)] = set([n])\r\n return revise\r\n \r\n def AC3(self, changes):\r\n q = self.createQueue()\r\n while len(q) != 0:\r\n (row, column), (r,c) = q.pop(0)\r\n if self.revise(row, column, r, c, changes):\r\n if (len(self.solution[row][column].domain) == 0):\r\n return False\r\n if (len(self.solution[row][column].domain) == 1):\r\n self.updateQueue(q, row, column, r, c)\r\n return True\r\n \r\n def undoAC3(self, changes):\r\n for (r,c), change in changes.items():\r\n while len(change) != 0:\r\n self.solution[r][c].domain.add(change.pop())\r\n \r\n #The backtracking algorithm to find a solution\r\n def backtrack(self):\r\n self.nodeCount = self.nodeCount + 1\r\n if not self.isValidAssignment():\r\n return False\r\n if self.isGoal():\r\n return True\r\n (row, column) = self.choosePosition()\r\n domainCpy = self.solution[row][column].domain.copy()\r\n for n in domainCpy:\r\n changes = dict()\r\n self.assignValue(row, column, n, changes)\r\n isPossible = self.backtrack()\r\n if isPossible:\r\n return True\r\n else:\r\n self.removeAssignment(row, column, changes)\r\n \r\n def __str__(self):\r\n s = \"\"\r\n for r in range(9):\r\n for c in range(9):\r\n s = s + \" \" + str(self.solution[r][c])\r\n s = s + \"\\n\"\r\n return s\r\n \r\n def __hash__(self):\r\n return hash(str(self))\r\n \r\n\r\nclass Sudoku(object):\r\n def __init__(self, puzzle):\r\n #The sudoku puzzle we are given\r\n self.puzzle = puzzle\r\n \r\n #Initialize the 'answer' matrix (since we want each position in the puzzle to be a Position object)\r\n self.ans = [[Position(0) for r in range(9)] for c in range(9)]\r\n for r in range(9):\r\n for c in range(9):\r\n self.ans[r][c].value = self.puzzle[r][c]\r\n \r\n #Sets to keep track of unused values in rows and columns\r\n self.unusedRowValues = [set([1, 2, 3, 4, 5, 6, 7, 8, 9]) for i in range(9)]\r\n self.unusedColumnValues = [set([1, 2, 3, 4, 5, 6, 7, 8, 9]) for i in range(9)]\r\n self.unusedBoxValues = [[set([1, 2, 3, 4, 5, 6, 7, 8, 9]) for i in range(3)] for j in range(3)]\r\n for r in range(9):\r\n for c in range(9):\r\n n = self.ans[r][c].value\r\n if n != 0:\r\n self.unusedRowValues[r].remove(n)\r\n self.unusedColumnValues[c].remove(n)\r\n self.unusedBoxValues[r//3][c//3].remove(n)\r\n\r\n def solve(self):\r\n start = time.time()\r\n mySudoku = Puzzle(self.ans, self.unusedRowValues, self.unusedColumnValues, self.unusedBoxValues)\r\n mySudoku.backtrack()\r\n end = time.time()\r\n print(\"Time taken: \" + str(end - start))\r\n print(\"Nodes seen: \" + str(mySudoku.nodeCount))\r\n return mySudoku.solution\r\n\r\nif __name__ == \"__main__\":\r\n # STRICTLY do NOT modify the code in the main function here\r\n if len(sys.argv) != 3:\r\n print (\"\\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\\n\")\r\n raise ValueError(\"Wrong number of arguments!\")\r\n\r\n try:\r\n f = open(sys.argv[1], 'r')\r\n except IOError:\r\n print (\"\\nUsage: python CS3243_P2_Sudoku_XX.py input.txt output.txt\\n\")\r\n raise IOError(\"Input file not found!\")\r\n\r\n puzzle = [[0 for i in range(9)] for j in range(9)]\r\n lines = f.readlines()\r\n\r\n i, j = 0, 0\r\n for line in lines:\r\n for number in line:\r\n if '0' <= number <= '9':\r\n puzzle[i][j] = int(number)\r\n j += 1\r\n if j == 9:\r\n i += 1\r\n j = 0\r\n\r\n sudoku = Sudoku(puzzle)\r\n ans = sudoku.solve()\r\n\r\n with open(sys.argv[2], 'a') as f:\r\n for i in range(9):\r\n for j in range(9):\r\n f.write(str(ans[i][j]) + \" \")\r\n f.write(\"\\n\")\r\n","sub_path":"sudoku_version4_AC3_and_MostConstrainedVariable.py","file_name":"sudoku_version4_AC3_and_MostConstrainedVariable.py","file_ext":"py","file_size_in_byte":10640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"192831967","text":"#!/usr/bin/env python\n\"\"\"\n--- Day 2: 1202 Program Alarm ---\nhttps://adventofcode.com/2019/day/2\n\nRank: 5348 / 4567\n\"\"\"\nfrom aoc2019lib import IntCodeVM\nfrom aocutils import read_input_int_split, timer\n\nINPUT = read_input_int_split('02')\n\n\ndef run_with_noun_and_verb(intcode_vm: IntCodeVM, noun: int, verb: int) -> int:\n \"\"\"Reset given intcode VM, set noun and verb, run it and get value at memory index 0.\"\"\"\n intcode_vm.reset()\n intcode_vm.mem_set(1, noun)\n intcode_vm.mem_set(2, verb)\n intcode_vm.run()\n return intcode_vm.mem_get(0)\n\n\n@timer\ndef part1():\n \"\"\"Solve challenge part 1.\"\"\"\n return run_with_noun_and_verb(IntCodeVM(INPUT), 12, 2)\n\n\n@timer\ndef part2():\n \"\"\"Solve challenge part 2.\"\"\"\n intcode_vm = IntCodeVM(INPUT)\n for noun in range(100):\n for verb in range(100):\n if run_with_noun_and_verb(intcode_vm, noun, verb) == 19690720:\n return 100 * noun + verb\n\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())\n","sub_path":"aoc02.py","file_name":"aoc02.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"416656458","text":"\"\"\" This file contains the Hashcat functions I used in the AutoHash program\"\"\"\n\nimport tempfile\nfrom FuncCommon import get_cmd_lines\nfrom FuncCrackOrganize import get_list_cracked_to_hash, get_list_not_cracked\nfrom FuncConversation import done_basic_session, done_advanced_session\n\n\ndef hashcat_basic(globalVars):\n \"\"\"\n For every hash list creating a temporary file with all the hashes\n Running hashcat on the temporary file\n Adding to the hash list (.cracked_hashes) all the cracked hashes\n Setting the hashlist not cracked list (.hashes)\n Calling the done_basic_session function\n \"\"\"\n globalVars.numNotCracked = globalVars.totalHashes\n for hash_list in globalVars.HashLists:\n tmp_file = tempfile.NamedTemporaryFile()\n tmp_write = open(tmp_file.name, 'w')\n for hash in hash_list.hashes:\n tmp_write.write(hash.hash + '\\n')\n tmp_write.close()\n hashcat_log = get_cmd_lines(['hashcat', '-m', str(hash_list.hash_cat),\n '-a', '0', tmp_file.name, globalVars.wordListPath,\n '--force', '--quiet', '--potfile-disable'\n ])\n if(\"on line 1\" not in hashcat_log[0]):\n hash_list.cracked_hashes = get_list_cracked_to_hash(globalVars,hashcat_log)\n hash_list.hashes = get_list_not_cracked(hash_list.hashes,\n hash_list.cracked_hashes)\n tmp_file.close()\n done_basic_session(globalVars)\n\n\ndef hashcat_advanced(globalVars, rule_list_path, num_in_session, num_timeout):\n \"\"\"\n First checking if the cracking have a timeout timer\n => No:\n Running a loop on the hash lists, divided by hash type\n Creating a temp file that contains the hashes to crack\n Running hashcat with rules on a temp file that contains all the hashes\n => Yes:\n Running a loop on the hash lists, divided by hash type\n Creating a temp file\n Running the next loop for each hash =>\n Sets the temp file to contain only the current hash\n Running hashcat with rules and timeout on the temp file\n Check if the hash been cracked, if not marks him with custom value\n\n Overall wont crack more than specified to this sesssion\n Add the cracked hashes to the cracked list (hash_list.cracked_hashes)\n Reduce the var numNotCracked by the number of hashes been cracked\n In the end calling the done_basic_session function\n :var num_cracked_now: Counting the hashes added to the current session\n :var num_failed: Counting the hashes that their cracking been timed out\n :param rule_list_path: The path to the the rules file\n :param num_in_session: The number of hashes to crack on this session\n :param num_timeout: The number of minutes until the hash cracking timeout\n \"\"\"\n num_cracked_now = 0\n num_failed = 0\n if (num_timeout == 0):\n for hash_list in globalVars.HashLists:\n tmp_file = tempfile.NamedTemporaryFile()\n tmp_write = open(tmp_file.name, 'w')\n for hash in hash_list.hashes:\n tmp_write.write(hash.hash + '\\n')\n num_cracked_now += 1\n if (num_cracked_now == num_in_session):\n break\n tmp_write.close()\n hashcat_log = get_cmd_lines(['hashcat', '-m',\n str(hash_list.hashCat), '-a', '0',\n tmp_file.name, globalVars.wordListPath, '-r',\n rule_list_path, '--force', '--quiet',\n '--potfile-disable'\n ])\n if (\"on line 1\" not in hashcat_log[0]):\n hash_list.cracked_hashes += get_list_cracked_to_hash(globalVars, hashcat_log)\n hash_list.hashes = get_list_not_cracked(hash_list.hashes,\n hash_list.cracked_hashes)\n tmp_file.close()\n if (num_cracked_now == num_in_session):\n break\n else:\n for hash_list in globalVars.HashLists:\n tmp_file = tempfile.NamedTemporaryFile()\n for hash in hash_list.hashes:\n tmp_write = open(tmp_file.name, 'w')\n tmp_write.flush()\n tmp_write.write(hash.hash + '\\n')\n tmp_write.close()\n hash_after = get_cmd_lines(['hashcat', '-m',\n str(hash_list.hash_cat), '-a', '0',\n tmp_file.name, globalVars.wordListPath, '-r',\n rule_list_path, '--runtime',\n str(num_timeout * 60), '--force',\n '--quiet', '--potfile-disable'\n ])\n\n if (hash_after == [] or \"on line 1\" in hash_after):\n hash_after = [\n hash.hash + ':' + '___________'] # 11 times _\n num_failed += 1\n globalVars.numTimedOutCracked += 1\n hash_list.cracked_hashes += get_list_cracked_to_hash(\n globalVars, hash_after)\n num_cracked_now += 1\n if (num_cracked_now == num_in_session):\n break\n hash_list.hashes = get_list_not_cracked(hash_list.hashes,\n hash_list.cracked_hashes)\n tmp_file.close()\n if (num_cracked_now == num_in_session):\n break\n globalVars.numNotCracked += num_failed\n done_advanced_session(globalVars, rule_list_path)","sub_path":"src/FuncHashcat.py","file_name":"FuncHashcat.py","file_ext":"py","file_size_in_byte":5941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"237766654","text":"import socket\n\nfrom utils.configs import AlgorithmConfigs\n\nclass Algorithm:\n def __init__(self):\n self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n # self.server_sock.setblocking(False)\n self.server_ip = AlgorithmConfigs.SERVER_IP\n self.port = AlgorithmConfigs.SERVER_PORT\n self.server_sock.bind((self.server_ip, self.port))\n self.server_sock.listen(1)\n\n self.client_sock = None\n self.clientInfo = None\n self.is_connected = False\n print(\"Algorithm (INSTANTIATED)\")\n\n def isConnected(self):\n return self.is_connected\n\n def connect(self):\n try:\n print(f\"Algorithm (WAITING) at {self.server_ip}\")\n if self.client_sock is None:\n self.client_sock, self.client_address = self.server_sock.accept()\n self.is_connected = True\n print(f\"Algorithm (CONNECTED) to {self.client_address} {self.client_sock}\")\n except KeyboardInterrupt:\n print(f\"Android (KEYBOARD INTERRUPT)\")\n self.disconnect_server()\n except Exception as e:\n print(f\"Algorithm (ERROR) connect():{e}\")\n\n def disconnect_client(self):\n print(\"Algorithm (CLIENT DISCONNECTED) CALLED\")\n self.client_sock.close()\n self.client_sock = None\n self.is_connected = False\n print(\"Algorithm (CLIENT DISCONNECTED)\")\n\n def disconnect_server(self):\n self.server_sock.close()\n print(\"Algorithm (SERVER DISCONNECTED)\")\n \n def read(self):\n try:\n raw_message = self.client_sock.recv(AlgorithmConfigs.BUFFER_SIZE)\n message = raw_message.decode(\"utf-8\").strip().strip('\\x00')\n if len(message) > 0:\n print(f\"Algorithm (MESSAGE-FROM): {message}\")\n return message\n message = None\n except socket.error:\n print(\"Algorithm read disconnect client\")\n self.disconnect_client()\n except Exception as e:\n print(f\"Algorithm (ERROR) read():{e}\")\n return None\n\n def write(self, message):\n try:\n print(f\"Algorithm (MESSAGE-TO): {message}\")\n buffer = message +\"\\x00\"*max(AlgorithmConfigs.BUFFER_SIZE-len(message ),0)\n self.client_sock.send(buffer.encode('utf-8'))\n except socket.error:\n self.disconnect_client()\n except Exception as e:\n print(f\"Algorithm (ERROR) write():{e}\")\n","sub_path":"source/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"85119428","text":"'''\nSolve the 2-D linear convection equation using the finite difference method.\n'''\n\nimport numpy as np # here we load numpy\nfrom matplotlib import pyplot as plt # here we load matplotlib\nfrom matplotlib import cm # colormap\nimport time, sys # here we load some utilities\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator)\nfrom mpl_toolkits.axes_grid1.inset_locator import inset_axes\nfrom mpl_toolkits.mplot3d import Axes3D # new library required for projected 3D plots\nplt.rcParams[\"font.family\"] = \"stix\" # set the font to Times globally\nplt.rcParams[\"mathtext.fontset\"] = \"stix\" # set the math font to Times\n\n## Variable declarations\nnx = 81 # grid points in x-direction\nny = 81 # grid points in y-direction\nnt = 100 # number of time steps\nc = 1 # wave speed\ndx = 2/(nx-1) # spatial resolution in x-direction\ndy = 2/(ny-1) # spatial resolution in y-direction\nsigma = 0.2 # for CFL condition\ndt = sigma*dx\n\nx = np.linspace(0,2,nx) # x-coordinates\ny = np.linspace(0,2,ny) # y-coordinates\n\n## Assign initial conditions\n# u = 2 when x and y are between 0.5 and 1 and u = 1 everywhere else\nu = np.ones((ny, nx)) # col (x) will always be the last dimension\nu[int(0.5/dy):int(1/dy+1), int(0.5/dx):int(1/dx+1)] = 2\n\n## Plot the initial condition\nfig = plt.figure()\nax = fig.gca(projection='3d')\nX, Y = np.meshgrid(x, y)\nsurf = ax.plot_surface(X, Y, u, cmap=cm.viridis, antialiased=False)\n\n# set the axis properties\nax.xaxis.set_major_formatter(FormatStrFormatter('%g'))\nax.yaxis.set_major_formatter(FormatStrFormatter('%g'))\nax.zaxis.set_major_formatter(FormatStrFormatter('%g'))\nax.tick_params(labelsize=8)\n\n# set the figure properties\nplt.xlabel('$x$ (m)', fontsize=10)\nplt.ylabel('$y$ (m)', fontsize=10)\nax.set_zlabel('$u$ (m/s)', fontsize=10)\nplt.xlim(0, 2)\nplt.ylim(0, 2)\nax.set_zlim(1, 2)\nplt.tight_layout(pad=0.1) # make the layout tight to minimize the white space\n\n# annotate the current time\nax.annotate('$t = 0.000$ s', xy=(0.75,0.9), xycoords='axes fraction', fontsize=10)\n\n# save and show the figure\nfolderName = '/home/ygc/Documents/Codes/cfd-python/2dLinearConvection/'\nfileName = 'u000.png'\nplt.savefig(folderName+fileName, dpi=300)\nplt.show(block=False)\nplt.pause(0.1) # show the image for 0.1 s\nplt.close()\n\n## Solve using finite difference and plot the results\nfor n in range(nt):\n un = u.copy()\n\n for i in range(1, nx):\n for j in range(1, ny):\n u[j,i] = un[j,i]-c*dt/dx*(un[j,i]-un[j,i-1])-c*dt/dy*(un[j,i]-un[j-1,i])\n\n # set the boundary values\n u[0,:] = 1\n u[-1,:] = 1\n u[:,0] = 1\n u[:,-1] = 1\n\n # Plot the results\n fig = plt.figure()\n ax = fig.gca(projection='3d')\n surf = ax.plot_surface(X, Y, u, cmap=cm.viridis, antialiased=False)\n\n # set the axis properties\n ax.xaxis.set_major_formatter(FormatStrFormatter('%g'))\n ax.yaxis.set_major_formatter(FormatStrFormatter('%g'))\n ax.zaxis.set_major_formatter(FormatStrFormatter('%g'))\n ax.tick_params(labelsize=8)\n\n # set the figure properties\n plt.xlabel('$x$ (m)', fontsize=10)\n plt.ylabel('$y$ (m)', fontsize=10)\n ax.set_zlabel('$u$ (m/s)', fontsize=10)\n plt.xlim(0, 2)\n plt.ylim(0, 2)\n ax.set_zlim(1, 2)\n plt.tight_layout(pad=0.1) # make the layout tight to minimize the white space\n\n # annotate the current time\n ax.annotate('$t = {0:.3f}$ s'.format((n+1)*dt), xy=(0.75,0.9), xycoords='axes fraction', fontsize=10)\n\n # save and show the figure\n fileName = 'u{:0>3d}.png'.format(n+1)\n plt.savefig(folderName+fileName, dpi=300)\n plt.show(block=False)\n plt.pause(0.1) # show the image for 0.1 s\n plt.close()","sub_path":"5_2dLinearConvection.py","file_name":"5_2dLinearConvection.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"75785237","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport uuid\nimport subprocess\n\n\ndef main():\n domain = '.'.join([\"www\", uuid.uuid4().hex, \"com\"])\n cmd = [\"ping\", domain]\n if os.name == \"nt\":\n cmd.extend([\"-n\", \"1\"])\n elif os.name == \"posix\":\n cmd.extend([\"-c\", \"1\"])\n try:\n returncode = subprocess.check_call(cmd)\n except subprocess.CalledProcessError as ex:\n print(\"ERROR:\", ex.returncode, ex.returncode != 0)\n else:\n print(\"returncode:\", returncode, returncode == 0)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"standard/046.subprocess/subprocess_check_call.py","file_name":"subprocess_check_call.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"236421232","text":"import tensorflow as tf\nimport numpy as np\nfrom models import *\n\n# make new obj\nmnist = type('',(object,),{})()\nmnist.train = type('',(object,),{})()\nmnist.test = type('',(object,),{})()\n\nmnist.train.num_examples = 60000\nmnist.test.num_examples = 10000\n\nimport pickle\nwith open('../tmp/snu_sugang_images.pkl', 'rb') as f:\n tmp_images = pickle.load(f)\n mnist.train.images = tmp_images[:mnist.train.num_examples]\n mnist.test.images = tmp_images[mnist.train.num_examples:mnist.train.num_examples+mnist.test.num_examples]\n\nwith open('../tmp/snu_sugang_labels.pkl', 'rb') as f:\n tmp_labels = pickle.load(f)\n mnist.train.labels = tmp_labels[:mnist.train.num_examples]\n mnist.test.labels = tmp_labels[mnist.train.num_examples:mnist.train.num_examples+mnist.test.num_examples]\ntrX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels\n\nX = tf.placeholder(tf.float32, [None, 26, 52, 3])\nY = tf.placeholder(tf.int32, [None, 2])\nY_onehot = tf.one_hot(Y, 10, 1.0, 0.0)\ntraining = tf.placeholder(bool, (), name='mode')\n\nwith tf.variable_scope('model') as scope:\n prob, hypothesis = vgg(X, True, training)\n\ncorrect_prediction = tf.equal(tf.argmax(hypothesis, 2), tf.argmax(Y_onehot, 2))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\ncost = tf.reduce_mean(tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(\n logits=hypothesis, labels=Y_onehot), axis=1))\n\na = tf.Variable(0.0003)\noptimizer = tf.train.AdamOptimizer(a)\ntrain = optimizer.minimize(cost)\n\ninit = tf.global_variables_initializer()\n\nsess = tf.Session()\nsess.run(init)\n\ntraining_epochs = 1\nbatch_size = 128\ndisplay_step = 1\nfor epoch in range(training_epochs):\n avg_cost = 0.0\n avg_accuracy = 0.0\n total_batch = int(mnist.train.num_examples / batch_size)\n train_indices = np.arange(len(trX))\n np.random.shuffle(train_indices)\n trX = trX[train_indices]\n trY = trY[train_indices]\n\n for i in range(total_batch):\n batch_xs, batch_ys = trX[i*batch_size:(i+1)*batch_size], trY[i*batch_size:(i+1)*batch_size]\n sess.run(train, feed_dict={X:batch_xs, Y:batch_ys, training:True})\n tmp_cost, tmp_accuracy = sess.run([cost, accuracy], feed_dict={X:batch_xs, Y:batch_ys, training:False})\n avg_accuracy += tmp_accuracy/total_batch\n avg_cost += tmp_cost/total_batch\n print(total_batch, i, end='\\r')\n print()\n\n if epoch % display_step == 0:\n print (\"Epoch:\", '%04d' %(epoch+1), \"cost:\", \"{:0.9f}\".format(avg_cost), \"accuracy: %0.3f\" % avg_accuracy)\n\n test_indices = np.arange(len(teX))\n np.random.shuffle(test_indices)\n test_batch_size = 250\n \n accr = 0\n test_batch_num = len(teX)//test_batch_size\n for j in range(test_batch_num):\n small_ids = test_indices[j*test_batch_size:(j+1)*test_batch_size]\n f_d = {X: teX[small_ids], Y: teY[small_ids], training:False}\n accr += sess.run(accuracy, feed_dict=f_d) / test_batch_num\n print (\"Accuracy:\", accr)","sub_path":"jay/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"249390730","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport csv\n\nfrom django.conf import settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.list import ListView\n\nfrom .models import Ingredient, IngredientTag\nfrom .utils import get_nutrition_limits\nfrom targets.models import Target\n\n\nclass IngredientListView(LoginRequiredMixin, ListView):\n # - Table view - generic macros and cost for each ingredient\n model = Ingredient\n queryset = Ingredient.objects.filter(tags__isnull=True)\n #queryset = Ingredient.objects.all() # XXX NOTE: This now only shows untagged Ings\n\n def get_context_data(self, **kwargs):\n context = super(IngredientListView, self).get_context_data(**kwargs)\n context['alltags'] = IngredientTag.objects.values_list('name', flat=True)\n context['limits'] = get_nutrition_limits(self.queryset)\n context['listtype'] = 'untagged'\n return context\n\n\nclass IngredientListAllView(LoginRequiredMixin, ListView):\n # - Table view - generic macros and cost for each ingredient\n model = Ingredient\n queryset = Ingredient.objects.all()\n\n def get_context_data(self, **kwargs):\n context = super(IngredientListAllView, self).get_context_data(**kwargs)\n context['alltags'] = IngredientTag.objects.values_list('name', flat=True)\n context['limits'] = get_nutrition_limits(self.queryset) #TODO: Too intensive?\n context['listtype'] = 'all'\n return context\n\n\nclass IngredientListByTagView(LoginRequiredMixin, ListView):\n # - Table view filtered to a tag\n model = Ingredient\n\n def get_queryset(self):\n self.tag = get_object_or_404(IngredientTag, name=self.args[0])\n return Ingredient.objects.filter(tags=self.tag)\n\n def get_context_data(self, **kwargs):\n context = super(IngredientListByTagView, self).get_context_data(**kwargs)\n context['alltags'] = IngredientTag.objects.values_list('name', flat=True)\n context['limits'] = get_nutrition_limits(self.get_queryset())\n context['tag'] = self.tag\n context['listtype'] = 'tag'\n return context\n\n\nclass IngredientDetailView(LoginRequiredMixin, DetailView):\n model = Ingredient\n\n def get_context_data(self, **kwargs):\n context = super(IngredientDetailView, self).get_context_data(**kwargs)\n\n # User's current daily target for comparison\n # TODO: Should let user compare to different targets, and scale\n # to maximise something (etc)\n user = self.request.user\n daily_target = Target.get_primary_target(user)\n context.update({'daily_target': daily_target})\n\n return context\n\n@login_required\ndef IngredientCSVExportView(request):\n # Create the HttpResponse object with the appropriate CSV header.\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = 'attachment; filename=\"pants-ingredients.csv\"'\n\n # Use dictionary writer to export nutrition data dicts.\n # Fields are all standard items plus 'name' and calories which should be 1st\n fields = [\n 'name',\n 'kilocalories',\n 'protein_per_j',\n 'fibre_per_j',\n 'protein_per_cost',\n 'fibre_per_cost',\n 'rank',\n 'rank_per_cost',\n 'pf_per_j',\n ] + list(settings.NUTRITION_DATA_ITEMS) + [\n 'tags',\n ]\n writer = csv.DictWriter(\n response,\n fieldnames=fields,\n extrasaction='ignore', # ignore extra data if present in dicts\n )\n\n writer.writeheader()\n for ing in Ingredient.objects.all().iterator():\n data = ing.nutrition_data\n data['name'] = ing.name\n data['tags'] = ing.tags.values_list('name', flat=True)\n writer.writerow(data)\n\n return response\n","sub_path":"pants/ingredients/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"17859434","text":"import numpy as np\nimport pandas as pd\nfrom scipy.optimize import minimize\nimport scipy.optimize\nimport matplotlib.pyplot as plt\n\ndef fit_ata(\n input_endog,\n forecast_length \n ):\n \"\"\"\n :param input_endog: numpy array of intermittent demand time series\n :param forecast_length: forecast horizon\n :return: dictionary of model parameters, in-sample forecast, and out-of-sample forecast\n \"\"\"\n input_series = np.asarray(input_endog)\n epsilon = 1e-7\n input_length = len(input_series)\n nzd = np.where(input_series != 0)[0]\n \n if list(nzd) != [0]:\n \n try:\n w_opt = _ata_opt(\n input_series = input_series,\n input_series_length = input_length,\n epsilon = epsilon, \n w = None,\n nop = 2\n )\n \n ata_training_result = _ata(\n input_series = input_series, \n input_series_length = input_length,\n w = w_opt[0], \n h = forecast_length,\n epsilon = epsilon,\n )\n ata_model = ata_training_result['model']\n ata_fittedvalues = ata_training_result['in_sample_forecast']\n \n ata_forecast = ata_training_result['out_of_sample_forecast']\n\n ata_demand_series = ata_training_result['fit_output']\n\n ata_mse = w_opt[1]\n\n except Exception as e:\n \n ata_model = None\n ata_fittedvalues = None\n ata_forecast = None\n print(str(e))\n \n else:\n \n ata_model = None\n ata_fittedvalues = None\n ata_forecast = None \n \n \n return {\n 'ata_model': ata_model,\n 'ata_fittedvalues': ata_fittedvalues,\n 'ata_forecast': ata_forecast,\n 'ata_demand_series': ata_demand_series,\n 'ata_mse': ata_mse\n }\n\ndef _ata(\n input_series, \n input_series_length,\n w, \n h, \n epsilon\n ):\n \n # ata decomposition\n nzd = np.where(input_series != 0)[0] # find location of non-zero demand\n \n k = len(nzd)\n z = input_series[nzd] # demand\n \n x = np.concatenate([[nzd[0]], np.diff(nzd)]) # intervals\n\n # initialize\n \n init = [z[0], np.mean(x)]\n \n zfit = np.array([None] * k)\n xfit = np.array([None] * k)\n\n # assign initial values and prameters\n \n zfit[0] = init[0]\n xfit[0] = init[1]\n\n correction_factor = 1\n \n p = w[0]\n q = w[1]\n # fit model\n for i in range(1,k):\n a_demand = p / nzd[i]\n a_interval = q / nzd[i]\n\n # 提升效率的操作方式\n if nzd[i] <= p:\n zfit[i] = z[i]\n else:\n zfit[i] = zfit[i-1] + a_demand * (z[i] - zfit[i-1]) # demand\n\n\n if nzd[i] <= q:\n xfit[i] = z[i] - z[i-1]\n else:\n xfit[i] = xfit[i-1] + a_interval * (x[i] - xfit[i-1]) # interval\n \n \n cc = correction_factor * zfit / (xfit + epsilon)\n \n ata_model = {\n 'a_demand': p,\n 'a_interval': q,\n 'demand_series': pd.Series(zfit),\n 'interval_series': pd.Series(xfit),\n 'demand_process': pd.Series(cc),\n 'correction_factor': correction_factor\n }\n \n # calculate in-sample demand rate\n \n frc_in = np.zeros(input_series_length)\n tv = np.concatenate([nzd, [input_series_length]]) # Time vector used to create frc_in forecasts\n\n zfit_output = np.zeros(input_series_length)\n \n for i in range(k):\n frc_in[tv[i]:min(tv[i+1], input_series_length)] = cc[i]\n zfit_output[tv[i]:min(tv[i+1], input_series_length)] = zfit[i]\n\n # forecast out_of_sample demand rate\n \n # ata 中的weight符合超几何分布,因此并不会出现越到后面,weight下降越快。\n # 因此, ata的最后一个值,并不会100%等于最后一个fitted value。\n # 从forecast的公式可知,其中并没有 h 可迭代参数,因此,forecast的结果都是最后一个。\n if h > 0:\n frc_out = np.array([cc[k-1]] * h)\n else:\n frc_out = None\n\n return_dictionary = {\n 'model': ata_model,\n 'in_sample_forecast': frc_in,\n 'out_of_sample_forecast': frc_out,\n 'fit_output': zfit_output\n }\n \n return return_dictionary\n\ndef _ata_opt(\n input_series, \n input_series_length, \n epsilon,\n w = None,\n nop = 2\n ):\n\n # p0 = np.array([3,1])\n init_p = np.random.randint(1, input_series_length)\n init_q = np.random.randint(0, init_p)\n p0 = np.array([init_p,init_q])\n # print(p0)\n pbounds = ((1, input_series_length), (0, input_series_length))\n\n # 通过minimize的方式,获取到一个最优化值。\n # 感觉可以深挖下这个的算法耶。。里面还含有分布函数的选择。\n # 传入梯度下降的公式,则可以降低计算的消耗。。。。\n # 调整步长,来修正梯度下降的效率?\n wopt = minimize(\n fun = _ata_cost, \n x0 = p0, \n method='L-BFGS-B',\n bounds=pbounds,\n args=(input_series, input_series_length, epsilon)\n )\n\n constrained_wopt = wopt.x\n fun = wopt.fun\n\n # wopt = scipy.optimize.brute(_ata_cost,pbounds,\n # args=(input_series, input_series_length, epsilon))\n \n # # constrained_wopt = np.minimum([1], np.maximum([0], wopt.x))\n # constrained_wopt = wopt\n # fun = 0\n \n return (constrained_wopt, fun)\n\n# 仅仅通过rmse来判断,容易产生过拟合的问题,因此需要添加新的正则化来减轻过拟合~\ndef _ata_cost(\n p0,\n input_series,\n input_series_length,\n epsilon\n ):\n #防止进入负数区间\n if p0[0] < 0 or p0[1] < 0:\n return 3.402823466E+38\n # Q: [0, P] P: [1,n]\n if p0[1] > p0[0]:\n return 3.402823466E+38\n frc_in = _ata(\n input_series = input_series,\n input_series_length = input_series_length,\n w=p0,\n h=0,\n epsilon = epsilon\n )['in_sample_forecast']\n\n # MSE-------------------------------------\n E = input_series - frc_in\n\n # count = min(input_series_length-1,(int)(p0[0]))\n # indata = input_series[count:]\n # outdata = frc_in[count:]\n # E = indata - outdata\n \n E = E[E != np.array(None)]\n # E = np.sqrt(np.mean(E ** 2))\n E = np.mean(E ** 2)\n\n # # MAPE--------------------------------\n # E1 = (np.fabs(input_series - frc_in))\n # E2 = (np.fabs(input_series) + np.fabs(frc_in)) / 2\n # E = E1 / E2\n # E = E.sum() / len(input_series)\n\n # print((\"count: {0} p: {1} q: {2} E: {3}\").format(count, p0[0], p0[1], E))\n print((\"p: {0} q: {1} E: {2}\").format(p0[0], p0[1], E))\n # count = count + 1\n return E\n\n# a = np.zeros(7)\n# val = [1.0,4.0,5.0,3.0]\n# idxs = [1,2-1,6-2,7-3]\n# ts = np.insert(a, idxs, val)\n\n\ninput_data = pd.read_csv(\"./data/M4DataSet/NewYearly.csv\")\ninput_data = input_data.fillna(0)\nts = input_data['Feature']\n# ts = input_data['Feature'][:1000]\n\n#-------------Cross validation------------------------------------\ncv_count = 5\nrepeatpoint = 10\nsplit_count = int(len(ts) / cv_count)\nsplit_range = split_count - repeatpoint\ndataend = len(ts)\nopt_para = []\nfor i in range(cv_count):\n start = i * split_count - repeatpoint\n end = (i+1) * split_count - repeatpoint\n if start < 0:\n start = 0\n if end > dataend:\n end = dataend\n data = ts[start : end]\n fit_pred = fit_ata(data, repeatpoint)\n opt_model = fit_pred['ata_model']\n para = (opt_model[\"a_demand\"], opt_model[\"a_interval\"])\n Train_MSE = fit_pred['ata_mse']\n #test------------------------------------------\n test = ts[end : end+repeatpoint]\n test_fitted = fit_pred[\"ata_forecast\"]\n\n test_MSE = test - test_fitted \n test_MSE = test_MSE[test_MSE != np.array(None)]\n test_MSE = np.mean(test_MSE ** 2)\n\n print(\"cv train: {0}\\topt P: {1}\\tQ: {2}\\tTrain_MSE: {3}\\tTest_MSE: {4}\".format(i, opt_model[\"a_demand\"], opt_model[\"a_interval\"], Train_MSE, test_MSE))\n opt_para.append({\"para\":para, \"MSE\": test_MSE, 'fited': fit_pred})\n\n\n\n#--------------------------Output the best paras----------------------------\nopt_para = sorted(opt_para, key=lambda item: item['MSE'])\nbest_para = opt_para[0]\ntest_data = np.asarray(ts)\nfit_pred = _ata(test_data,len(test_data),best_para['para'],4,1e-7)\n\ntest_fited = fit_pred['in_sample_forecast']\nE = test_data - test_fited\nE = E[E != np.array(None)]\nMSE = np.mean(E ** 2)\n\nyhat = np.concatenate([fit_pred['in_sample_forecast'], fit_pred['out_of_sample_forecast']])\n# yhat = fit_pred['ata_demand_series']\n\nopt_model = fit_pred['model']\nprint(\"output P: {0}\\tQ: {1}\\tmse: {2}\".format(opt_model[\"a_demand\"],opt_model[\"a_interval\"], MSE))\n# print(ts)\n# print(yhat)\n\nplt.plot(ts)\nplt.plot(yhat)\n\nplt.show()\nprint(\"\")\n\n# output P: 4557.0 Q: 0.0 mse: 7763694.190167521\n# round 1: output P: 969.6244064590888 Q: 217.45943750155297 mse: 7836237.429606486\n# p: 13782.98556931908 q: 2499.000000000012 E: 2429.2208993823615 grid search\n# p: 13887.31775824237 q: 2157.2851580033325 E: 5840921.397489025\n# p: 14293.167068707324 q: 1e-08 E: 2687.3898919142553\n\n# # -----------------------Invalid-------------------------------\n# # Test\n# init = fit_pred['ata_forecast'][-1]\n# # init = 479\n# W = [fit_pred['ata_model']['a_demand'], fit_pred['ata_model']['a_interval']]\n# # W = [13887.31775824237, 2157.2851580033325]\n# test_data = pd.read_csv(\"./data/M4DataSet/NewYearlyTest.csv\")\n# test_data = test_data.fillna(0)\n# ts_test = test_data['Feature']\n\n# test_out = ata_forecast(W, init, len(ts_test), 1e-7)\n\n# # E = test_out - ts_test\n# # E = E[E != np.array(None)]\n# # E = np.mean(E ** 2)\n# # print(('out: a_demand : {0} a_interval: {1} rmse: {2}').format(W[0], W[1], E))\n\n# # print(ts_test)\n# # print(test_out)\n\n# plt.plot(ts_test)\n# plt.plot(test_out)\n\n# plt.show()\n# # ----------------------------------------------------------\n","sub_path":"ATA/main_doublepara_cross_with_point_forecast.py","file_name":"main_doublepara_cross_with_point_forecast.py","file_ext":"py","file_size_in_byte":11494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"91471058","text":"'''\nCopyright 2019 Google LLC\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n https://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\n\n\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\n\nimport paramiko\nfrom paramiko.ssh_exception import SSHException, PasswordRequiredException\nfrom paramiko.rsakey import RSAKey\n\nfrom mdt import config\n\n\nSUPPORTED_SYSTEMS = [\n 'Linux',\n 'MacOS',\n 'BSD',\n]\n\nKEYSDIR = os.path.join(config.CONFIG_BASEDIR, \"keys\")\nKEYFILE_PATH = os.path.join(config.CONFIG_BASEDIR, \"keys\", \"mdt.key\")\n\n\ndef GenerateAuthorizedKeysLine(paramiko_key):\n public_key = paramiko_key.get_base64()\n authorized_keys_line = 'ssh-rsa {0} mdt\\r\\n'.format(public_key)\n return authorized_keys_line\n\n\nclass Keystore:\n def __init__(self):\n if not os.path.exists(config.CONFIG_BASEDIR):\n os.makedirs(CONFIG_BASEDIR, mode=0o700)\n if not os.path.exists(KEYSDIR):\n os.makedirs(KEYSDIR, mode=0o700)\n if not os.path.exists(KEYFILE_PATH):\n self.pkey = None\n else:\n try:\n self.pkey = RSAKey.from_private_key_file(KEYFILE_PATH)\n except IOError as e:\n print(\"Unable to read private key from file: {0}\".format(e))\n sys.exit(1)\n except PasswordRequiredException as e:\n print(\"Unable to load in private key: {0}\".format(e))\n sys.exit(1)\n\n def generateKey(self):\n self.pkey = RSAKey.generate(bits=4096)\n\n try:\n self.pkey.write_private_key_file(KEYFILE_PATH)\n except IOError as e:\n print(\"Unable to write private key to disk: {0}\".format(e))\n return False\n else:\n return True\n\n def importKey(self, keyfile):\n try:\n self.pkey = RSAKey.from_private_key_file(keyfile)\n except IOError as e:\n print(\"Unable to read private key from file: {0}\".format(e))\n return False\n except PasswordRequiredException as e:\n print(\"Unable to load in private key: {0}\".format(e))\n return False\n except SSHException as e:\n print(\"Unable to import private key: {0}\".format(e))\n print(\"Note: Only OpenSSH keys generated using ssh-keygen in PEM format are supported.\")\n return False\n\n try:\n self.pkey.write_private_key_file(KEYFILE_PATH)\n except IOError as e:\n print(\"Unable to write private key to disk: {0}\".format(e))\n return False\n else:\n return True\n\n def key(self):\n return self.pkey\n\n\nclass GenKeyCommand:\n '''Usage: mdt genkey\n\nGenerates an SSH key and stores it to disk.\n\nNote that this does not prompt if you want to replace an already existing\nkey and will happily overwrite without telling you! Also note, you should remove\nthe keys previously stored on the device in $HOME/.ssh/authorized_keys and\nrestart the mdt-keymaster service on the device to re-push any newly generated\nkeys.\n'''\n\n def run(self, args):\n if os.path.exists(KEYFILE_PATH):\n print('WARNING!')\n print()\n print('MDT has detected a key already on disk. This command')\n print('will overwrite that key! This will effectively lock you out from')\n print('any boards that you may have previously used this key with!')\n print()\n print('If you are attempting to rotate your keys, you will need to run')\n print(\"'mdt resetkeys' on each board you've previously used to remove\")\n print('your old key first, otherwise you will be locked out from SSH')\n print('access and will have to push your key manually.')\n print()\n print(\"If you know what you're doing, you can proceed by typing 'YES'\")\n sys.stdout.write('here: ')\n sys.stdout.flush()\n\n response = sys.stdin.readline()\n if not response.startswith('YES'):\n print('Aborting.')\n return 1\n\n print('Proceeding.')\n os.unlink(KEYFILE_PATH)\n\n keystore = Keystore()\n if not keystore.generateKey():\n return 1\n\n return 0\n\n\nclass SetKeyCommand:\n '''Usage: mdt setkey \n\nCopies an SSH private key provided into the MDT key store for use with\nauthentication later.'''\n\n def run(self, args):\n if len(args) != 2:\n print(\"Usage: mdt setkey \")\n return 1\n\n source_keyfile = args[1]\n if not os.path.exists(source_keyfile):\n print(\"Can't copy {0}: no such file or directory.\".format(source_keyfile))\n return 1\n\n keystore = Keystore()\n if not keystore.importKey(source_keyfile):\n return 1\n\n print(\"Key {0} imported.\".format(source_keyfile))\n return 0\n","sub_path":"venv/Lib/site-packages/mdt/keys.py","file_name":"keys.py","file_ext":"py","file_size_in_byte":5338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"605367145","text":"#-*- coding:utf-8 -*-\n\"\"\"\nTest module for testing worker spawning and killing\nworkers and sinks\n\"\"\"\nimport unittest\nfrom servers.ventilator import Ventilator\nfrom workers.dummy_worker import DummyWorker\nfrom sinks.dummy_sink import DummySink\nfrom multiprocessing import Process\nfrom subprocess import Popen\nimport time\n\nclass testWorkerModules(unittest.TestCase):\n def setUp(self):\n #start a ventilator\n self.V = Ventilator()\n self.nw = 4\n #spawn 4 workers\n self.ws = [Popen(['python', 'workers/dummy_worker.py'], stdout=None) for i in range(self.nw)]\n #~ self.ws = []\n #~ for i in range(self.nw):\n #~ w = DummyWorker2\n #~ P = Process(target=w)\n #~ P.start()\n #~ self.ws.append(P)\n\n #spawn a sink\n self.sink = Popen(['python', 'sinks/dummy_sink.py'], stdout=None)\n\n\n # wait for workers and sinks to connect\n time.sleep(1)\n\n def test_send_json(self):\n '''\n Pushing json with unicode through workers to sinks.\n '''\n\n self.V.push_load([{'text':u'são joão'} for i in xrange(80)])\n time.sleep(2)\n #[p.wait() for p in self.ws]#wait for the workers to terminate\n wsr = [p.poll() for p in self.ws]\n time.sleep(1)\n self.sink.wait()\n sr = self.sink.returncode\n self.assertEqual([0]*self.nw, wsr)\n self.assertEqual(0, sr)\n\n def tearDown(self):\n pass\n# try:\n# self.sink.kill()\n# #tries to kill worker processes if they are still active\n# [p.kill() for p in self.ws]\n# except OSError as e:\n# print \"No processes left to kill\", e\n\nclass testWorkerAsSubprocesses(unittest.TestCase):\n def setUp(self):\n #start a ventilator\n self.V = Ventilator(pushport=5561,pubport=5562,subport=5563)\n self.nw = 4\n #spawn 4 workers\n self.ws = [Process(target=DummyWorker(pushport=5564,pullport=5561,subport=5563)) for i in range(self.nw)]\n [p.start() for p in self.ws]\n\n\n #spawn a sink\n self.sink = Process(target=DummySink(pullport=5564,pubport=5563,subport=5562))\n self.sink.start()\n\n\n # wait for workers and sinks to connect\n time.sleep(1)\n\n def test_send_json(self):\n '''\n Pushing json with unicode through workers to sinks.\n '''\n\n self.V.push_load([{'text':u'são joão'} for i in xrange(80)])\n time.sleep(1)\n\n\n\n def tearDown(self):\n pass\n# try:\n# self.sink.join()\n# #tries to kill worker processes if they are still active\n# [p.join() for p in self.ws]\n# except OSError as e:\n# print e\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"pypln/test_messaging.py","file_name":"test_messaging.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"325337625","text":"import requests,json\r\nclass api():\r\n def locked(key, api_type):\r\n\r\n url = \"http://api.neko-bot.net/api/locked/{api_type}\"\r\n headers = {\"TagKey\": f\"{key}\"}\r\n r = requests.get(url=url, headers=headers)\r\n if \"403\" not in r.status_code:\r\n return r.text\r\n if \"403\" in r.status_code:\r\n print(f\"Invalid token ({key}) was supplied.\")\r\n","sub_path":"versions/raw/nbapi-1.9.0.1.4/lib/nbapi/apil.py","file_name":"apil.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"144132155","text":"#Excepciones\ndef suma(num1, num2):\n return num1+num2\n\ndef resta(num1, num2):\n return num1-num2\n\ndef multiplicacion(num1, num2):\n return num1*num2\n\ndef division(num1, num2):\n try:\n return num1/num2\n except ZeroDivisionError:\n print(\"No se puede dividir entre 0\")\n return \"Operacion erronea\"\n\nwhile True:\n try:\n op1= int(input(\"Introduzca el primer numero: --->\"))\n op2 = int(input(\"Introduzca el segundo numero: --->\"))\n break\n except ValueError:\n print(\"Los valores introducidos no son correctos, intentalo de nuevo\")\n\noperacion = input(\"Ingrese la operación que va a realizar: (suma/resta/multiplicacion/division)--->\")\n\nif operacion == \"suma\":\n print(suma(op1, op2))\n\nelif operacion== \"resta\":\n print(resta(op1, op2))\n\nelif operacion == \"multiplicacion\":\n print(multiplicacion(op1, op2))\n\nelif operacion == \"division\":\n print(division(op1, op2))\n\nelse:\n print(\"Operacion no encontrada\")\n\nprint(\"Continuando..\")\n","sub_path":"Plan de Estudios/Software Engineering Career/0. Python and Flask/Basico/5.Excepciones/19.py","file_name":"19.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"67851663","text":"#!/usr/bin/env python3.5\n\"\"\"Telegram bot to query KickassTorrents.\"\"\"\n\nimport gc\nfrom katcr import Katcr\nfrom docopt import docopt\nimport telepot\nfrom telepot.loop import MessageLoop\nfrom telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton\n\n\nclass KATBot(telepot.Bot):\n \"\"\"KAT.cr search bot, looks only for the first page.\"\"\"\n\n def __init__(self, token):\n \"\"\"Initialize of KATBot.\"\"\"\n super().__init__(token)\n self.katcr = Katcr()\n self.torrent_by_name_dict = {}\n\n # pylint: disable=too-few-public-methods\n def on_chat_message(self, msg):\n \"\"\"Answer only chat messages.\"\"\"\n if msg['text'] == \"/start\":\n return\n _, _, chat_id = telepot.glance(msg)\n self.sendMessage(chat_id, \"Results for: {}\".format(msg['text']))\n keys = []\n for key, value in self.katcr.search(msg['text'], 1):\n self.torrent_by_name_dict[key[:63]] = value\n keys.append([\n InlineKeyboardButton(text=key, callback_data=key[:63])])\n keyboard = InlineKeyboardMarkup(inline_keyboard=keys)\n self.sendMessage(chat_id, \"Results for: {}\".format(msg['text']),\n reply_markup=keyboard, parse_mode=\"html\")\n gc.collect()\n\n def on_callback_query(self, msg):\n \"\"\"Get the button data.\"\"\"\n _, from_id, query_data = telepot.glance(msg, flavor='callback_query')\n self.sendMessage(from_id, self.torrent_by_name_dict[query_data])\n gc.collect()\n\n\ndef main():\n \"\"\"Run telegram bot.\n\n Usage: katcr_bot [options]\n\n Options:\n --token= Telegram bot token\n \"\"\"\n bot = KATBot(docopt(main.__doc__, version=\"0.0.1\")[\"--token\"])\n MessageLoop(bot).run_forever()\n","sub_path":"katcr/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"348044253","text":"from flask_restful import Resource, reqparse\n\nfrom com_stock_api.naver_news.dao import NewsDao\nfrom com_stock_api.naver_news.dto import NewsDto\n\nclass News(Resource):\n\n def __init__(self):\n parser = reqparse.RequestParser()\n parser.add_argument('id', type=int, required=False, help='This field cannot be left blank')\n parser.add_argument('date', type=int, required=False, help='This field cannot be left blank')\n parser.add_argument('headline', type=str, required=False, help='This field cannot be left blank')\n parser.add_argument('neg', type=float, required=False, help='This field cannot be left blank')\n parser.add_argument('pos', type=float, required=False, help='This field cannot be left blank')\n parser.add_argument('neu', type=float, required=False, help='This field cannot be left blank')\n parser.add_argument('keywords', type=float, required=False, help='This field cannot be left blank')\n parser.add_argument('url', type=str, required=False, help='This field cannot be left blank')\n\n def post(self):\n data = self.parset.parse_args()\n news = NewsDto(data['date'],data['headline'],data['neg'], data['pos'], data['neu'],data['keywords'],data['url'])\n try:\n news.save()\n except:\n return {'message':'An error occured inserting the news'}, 500\n return news.json(), 201\n\n def get(self,id):\n news = NewsDao.find_by_id(id)\n if news:\n return news.json()\n return {'message': 'News not found'}, 404\n\n def put (self, id):\n data = News.parser.parse_args()\n news = NewsDto.find_by_id(id)\n\n news.date = data['date']\n news.symbol = data['symbol']\n news.headline= data['headline']\n news.neg = data['neg']\n news.pos = data['pos']\n news.neu = data['neu']\n news.keywords = data['keywords']\n news.price= data['url']\n news.save()\n return news.json()\n\nclass News_(Resource):\n def get(self):\n return {'news': list(map(lambda news: news.json(), NewsDao.find_all()))}\n \n","sub_path":"com_stock_api/naver_news/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"567927062","text":"import glob\nimport pymongo\nimport logging, os, schedule, time\n\nfrom parsers.solar import fetch_solar\nfrom parsers.wind import fetch_wind\n\nINTERVAL_SECONDS = 60 * 5\n\n# Import all country parsers\ndef import_country(country_code):\n return getattr(\n __import__('parsers.%s' % country_code, globals(), locals(), ['fetch_%s' % country_code]),\n 'fetch_%s' % country_code)\ncountry_codes = map(lambda s: s[len('parsers/'):len('parsers/')+2], glob.glob('parsers/??.py'))\nparsers = map(import_country, country_codes)\n\n# Set up stats\nimport statsd\nstatsd.init_statsd({\n 'STATSD_HOST': os.environ.get('STATSD_HOST', 'localhost'),\n 'STATSD_BUCKET_PREFIX': 'electricymap_feeder'\n})\n\n# Set up logging\nENV = os.environ.get('ENV', 'development').lower()\nlogger = logging.getLogger(__name__)\nif not ENV == 'development':\n from logging.handlers import SMTPHandler\n mail_handler = SMTPHandler(\n mailhost=('smtp.mailgun.org', 587),\n fromaddr='Application Bug Reporter ',\n toaddrs=['olivier.corradi@gmail.com'],\n subject='Electricity Map Feeder Error',\n credentials=(os.environ.get('MAILGUN_USER'), os.environ.get('MAILGUN_PASSWORD'))\n )\n mail_handler.setLevel(logging.ERROR)\n logger.addHandler(mail_handler)\n logging.getLogger('statsd').addHandler(logging.StreamHandler())\nelse: logger.addHandler(logging.StreamHandler())\n\n\nclient = pymongo.MongoClient(os.environ.get('MONGO_URL', 'mongodb://localhost:27017'))\ndb = client['electricity']\ncol = db['realtime']\n\ndef fetch_countries():\n for parser in parsers: \n try:\n with statsd.StatsdTimer('fetch_one_country'):\n obj = parser()\n logging.info('INSERT %s' % obj)\n col.insert_one(obj)\n except: \n statsd.increment('fetch_one_country_error')\n logger.exception('fetch_one_country()')\n\ndef fetch_weather():\n try:\n with statsd.StatsdTimer('fetch_wind'): fetch_wind()\n except: \n statsd.increment('fetch_wind_error')\n logger.exception('fetch_wind()')\n try:\n with statsd.StatsdTimer('fetch_solar'): fetch_solar()\n except: \n statsd.increment('fetch_solar_error')\n logger.exception('fetch_solar()')\n\nschedule.every(INTERVAL_SECONDS).seconds.do(fetch_countries)\nschedule.every(15).minutes.do(fetch_weather)\n\nfetch_countries()\nfetch_weather()\n\nwhile True:\n schedule.run_pending()\n time.sleep(INTERVAL_SECONDS)\n","sub_path":"feeder/feeder.py","file_name":"feeder.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"570040222","text":"import sys\nimport asyncio\nimport synapse.lib.cell as s_cell\nimport synapse.lib.stormsvc as s_stormsvc\n\n# each service needs a unique id\nsvciden = '457a11723f821dd8884cb5f9d80596ad'\nsvcconf = {'svciden': svciden}\n\nclass HelloWorldService(s_stormsvc.StormSvc, s_cell.CellApi):\n '''\n HelloWorldService implements an example Storm Service.\n '''\n _storm_svc_name = 'helloworld'\n _storm_svc_vers = (1, 0, 0)\n _storm_svc_pkgs = (\n {\n 'name': 'hello',\n 'version': (1, 0, 0),\n 'svcconf': svcconf,\n 'modules': (\n {\n 'name': 'hello',\n 'modconf': svcconf,\n 'storm': '''\n function lookup(fqdn) {\n\n $retn = $lib.list()\n\n $hellosvc = $lib.service.get($modconf.svciden)\n\n $answ = $hellosvc.runDnsLook($fqdn)\n\n for $ipv4 in $answ.ipv4s {\n [ inet:dns:a=($fqdn, $ipv4)]\n $retn.append($node)\n }\n\n fini{ return($retn) }\n }\n '''\n },\n ),\n 'commands': (\n {\n 'name': 'hello.lookup',\n 'descr': 'Lookup an FQDN in the helloworld example service.',\n 'cmdargs': (\n # -h / --help plumbing happens automatically\n ('--yield', {'default': False, 'action': 'store_true',\n 'help': 'Yield created inet:dns:a nodes instead of the inbound inet:fqdn nodes.'}),\n ('--debug', {'default': False, 'action': 'store_true',\n 'help': 'Print detailed user feedback.'}),\n ),\n 'cmdconf': {'svciden': svciden},\n 'storm': '''\n // Filter out all node types other than inet:fqdn\n +inet:fqdn\n\n $fqdn = $node.repr()\n\n if $cmdopts.debug {\n $lib.print(\"hello.lookup resolving: {fqdn}\", fqdn=$fqdn)\n }\n\n // import our hello module\n $hello = $lib.import(hello)\n $nodes = $hello.lookup($fqdn)\n\n if $cmdopts.yield {\n -> { yield $nodes }\n }\n ''',\n },\n {\n 'name': 'hello.stream',\n 'descr': 'Yield a potentially large number of results from a service.',\n 'cmdargs': (),\n 'cmdconf': {'svciden': svciden},\n 'storm': '''\n // Filter out all node types other than inet:fqdn\n +inet:fqdn\n\n $hellosvc = $lib.service.get($cmdconf.svciden)\n\n $fqdn = $node.repr()\n -> {\n for $ipv4 in $hellosvc.runGenrLook($fqdn) {\n [ inet:dns:a = ($fqdn, $ipv4) ]\n }\n }\n ''',\n },\n ),\n },\n )\n\n async def runDnsLook(self, fqdn):\n # pretend to run a DNS lookup and return results\n # ( but in reality you could do anything and return it here )\n return {'ipv4s': [ '1.2.3.4', '5.6.7.8' ] }\n\n async def runGenrLook(self, fqdn):\n # storm services may also expose python generators\n # to allow streaming results of any size without memory pressure\n yield '1.1.1.1'\n yield '2.2.2.2'\n\nclass HelloWorldCell(s_cell.Cell):\n '''\n A Cell stores persistant information such as users and permissions.\n '''\n cellapi = HelloWorldService\n\nif __name__ == '__main__':\n asyncio.run(HelloWorldCell.execmain(sys.argv[1:]))\n","sub_path":"hellostormsvc.py","file_name":"hellostormsvc.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"91800038","text":"f = open(\"A-large (1).in\",\"r\")\r\no = open(\"A-large-answers.txt\",\"w\")\r\nT = int(f.readline())\r\n\r\nfor t in range(1,T+1):\r\n #print(\"Case \"+str(t))\r\n n = f.readline()\r\n #if n[-1] == \"\\n\":\r\n # n = n[:-1]\r\n n = int(n)\r\n #print(n)\r\n if n == 0:\r\n o.write(\"Case #\"+str(t)+\": INSOMNIA\\n\")\r\n continue\r\n m = n\r\n n = 0\r\n s = 1\r\n l = [1,2,3,4,5,6,7,8,9,0]\r\n while l:\r\n n += m\r\n n1 = n\r\n while n1:\r\n try:\r\n l.remove(n1%10)\r\n except ValueError:\r\n pass\r\n n1 = n1//10\r\n \r\n o.write(\"Case #\"+str(t)+\": \"+str(n)+\"\\n\")\r\no.close()\r\n\"\"\"\r\nf = open(\"A-test.txt\",\"w\")\r\nf.write(str(1001)+\"\\n\")\r\nfor i in range(99000,100001):\r\n f.write(str(i)+\"\\n\")\r\nf.close()\"\"\"\r\n\r\n","sub_path":"codes/CodeJamCrawler/CJ/16_0_1_AlonH_A.py","file_name":"16_0_1_AlonH_A.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"216828316","text":"import simplegui\nimport time\n\n## Set global variables\ninterval = 100\n# associate interval of 0.1 second \ntime = 0\nx = 0\ny = 0\nsuccess_rate = \"0\" + \"/\" + \"0\"\n\n\n## Event handlers\ndef tick():\n global time\n # time is the total number of 0.1 second passed \n time += 1\n\ndef format():\n global time\n # format() function format variable time into format like 10:59.9\n milesecond = time%10\n second = time/10\n if second>59:\n minute = second/60\n second = second - minute*60\n else:\n minute = 0\n if second < 10:\n s = \"0\"+str(second)\n else:\n s = str(second)\n return str(minute)+\":\"+s+\".\"+str(milesecond) \n\ndef draw(canvas):\n canvas.draw_text(format(),[115,150],30,\"Lime\")\n canvas.draw_text(success_rate,[0,30],30,\"Blue\")\n \n# 3 buttons\ndef start():\n timer.start()\n \ndef stop():\n global x\n global y\n global time\n global success_rate\n # make sure that we only count the times when the game is in progress, \n # rather than everytime we click \"stop\" button \n if timer.is_running():\n y += 1\n if time%10==0:\n x += 1\n success_rate = str(x) + \"/\" + str(y)\n timer.stop()\n\ndef reset():\n global time\n timer.stop()\n time = 0\n \n## Create frame and timer\nframe = simplegui.create_frame(\"Stopwatch\",300,300)\ntimer = simplegui.create_timer(interval,tick)\n\n## Draw on canvas / Add buttons\nframe.set_draw_handler(draw)\nframe.add_button(\"Start\",start)\nframe.add_button(\"Stop\",stop)\nframe.add_button(\"Reset\",reset)\n\n## Start frame \nframe.start()\n\n## Good code from my classmates\n# http://www.codeskulptor.org/#user39_vx55YqYCcD8ajjb_1.py\n# http://www.codeskulptor.org/#user39_Bf7FLIFgZm_2.py\n# http://www.codeskulptor.org/#user39_GeHBa0meqnbN9R0.py\n# http://www.codeskulptor.org/#user39_dH1dHkLRFJWfrHD.py\n# http://www.codeskulptor.org/#user39_V7Xy5oQjBf_0.py\n","sub_path":"IIPP/Stopwatch.py","file_name":"Stopwatch.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"344163156","text":"# import packages\nimport requests\nimport time \nimport csv\nimport os\nfrom functions import *\n\n#save as text or html\nsave_as_text=False\n#The folder to store the job details description\nfoldername='data'\n#The input file name which is geneated using main.py\nfilename='jobs_1.csv'\n\nimport os\nif not os.path.exists(foldername):\n os.makedirs(foldername)\n\nwith open(filename) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n next(csv_reader)\n for row in csv_reader:\n id=row[0]\n url=row[9]\n\n # get dom \n try:\n page = requests.get('https://ca.indeed.com' + url, allow_redirects=True)\n\n #ensuring at least 0.01 second between page grabs \n time.sleep(0.01) \n\n #fetch data\n soup = get_soup(page.text)\n #print(soup.prettify())\n desc = soup.find(id=\"jobDescriptionText\");\n \n # if results exist\n if(desc == None):\n break\n\n # get job description \n if save_as_text:\n filename=id+\".txt\"\n data=desc.get_text()\n else:\n filename=id+\".html\"\n data=str(desc)\n outfile = open(foldername+\"/\"+filename,'w')\n outfile.write(data) \n \n except:\n pass\n","sub_path":"getjobdesc.py","file_name":"getjobdesc.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"493388113","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDemonstrate how to synchronize 2 or more MFLI\ninstruments or 2 or more UHFLI instruments using the MDS capability of LabOne.\nIt also measures the temporal response of demodulator filters of both\nboth instruments using the Data Acquisition (DAQ) Module.\n\nCopyright 2008-2018 Zurich Instruments AG\n\"\"\"\n\nfrom __future__ import print_function\nimport time\nimport zhinst.utils\n\n\ndef run_example(device_ids, do_plot=False, synchronize=True):\n \"\"\"\n Run the example: Capture demodulator data from two devices using the Data Acquisition module.\n The devices are first synchronized using the MultiDeviceSync Module.\n\n Hardware configuration:\n The cabling of the instruments must follow the MDS cabling depicted in\n the MDS tab of LabOne.\n Additionally, Signal Out 1 of the master device is split into Signal In 1 of the master and slave.\n\n Arguments:\n\n device_ids (list): The IDs of the devices to run the example with. For\n example, [\"dev3352\",\"dev3562\"]. The first device is the master.\n NOTE The devices must be of the same type, either 2 or more UHF or 2 or more MF instruments.\n\n do_plot (bool, optional): Specify whether to plot the data acquisition. Default is no\n plot output.\n\n synchronize (bool, optional): Specify if multi-device synchronization will\n be started and stopped before and after the data acquisition\n\n Returns:\n\n data (dict): A dictionary with all the data as returend from the sweeper\n module. It contains all the demodulator data dictionaries and some\n metainformation about the data acquisition.\n\n\n See the \"LabOne Programing Manual\" for further help, available:\n - On Windows via the Start-Menu:\n Programs -> Zurich Instruments -> Documentation\n - On Linux in the LabOne .tar.gz archive in the \"Documentation\"\n sub-folder.\n \"\"\"\n\n # Check if the master device ID exists\n if len(device_ids) == 0:\n raise Exception(\"No value for master_id specified. The first argument to the \"\n \"example should contain at least 2 device IDs, \"\n \"e.g. ['dev2006', 'dev2007'] or ['uhf-dev2006', 'uhf-dev2007'].\")\n\n # Check if the slave device ID exists\n if len(device_ids) < 2:\n raise Exception(\"No value for slave_id specified. The first argument to the \"\n \"example should contain at least 2 device IDs, \"\n \"e.g. ['dev2006', 'dev2007'] or ['uhf-dev2006', 'uhf-dev2007'].\")\n\n # Connection to the data server and devices\n\n # Connection to the local server 'localhost' ^= '127.0.0.1'\n apilevel = 6\n daq = zhinst.ziPython.ziDAQServer('localhost', 8004, apilevel)\n discovery = zhinst.ziPython.ziDiscovery()\n\n # Master and slave device ID\n props = []\n for devID in device_ids:\n deviceSerial = discovery.find(devID).lower()\n props.append(discovery.get(deviceSerial))\n devices = props[0]['deviceid']\n for prop in props[1:]:\n devices += \",\"+prop['deviceid']\n # Switching between MFLI and UHFLI\n deviceType = props[0]['devicetype']\n for prop in props[1:]:\n if prop['devicetype'] != deviceType:\n raise Exception(\"This example needs 2 or more MFLI instruments or 2 or more UHFLI instruments.\"\n \"Mixing device types is not possible\")\n\n for prop in props:\n if prop['devicetype'] == 'UHFLI':\n daq.connectDevice(prop['deviceid'], prop['interfaces'][0])\n else:\n daq.connectDevice(prop['deviceid'], '1GbE')\n\n # Disable all available outputs, demods, ...\n for prop in props:\n zhinst.utils.disable_everything(daq, prop['deviceid'])\n\n # Device synchronization\n if synchronize:\n print(\"Synchronizing devices %s ...\\n\" % devices)\n mds = daq.multiDeviceSyncModule()\n mds.set('multiDeviceSyncModule/start', 0)\n mds.set('multiDeviceSyncModule/group', 0)\n mds.execute()\n mds.set('multiDeviceSyncModule/devices', devices)\n mds.set('multiDeviceSyncModule/start', 1)\n\n timeout = 20\n start = time.time()\n status = 0\n while status != 2:\n time.sleep(0.2)\n status = mds.getInt('multiDeviceSyncModule/status')\n if status == -1:\n raise Exception('Error during device sync')\n if (time.time() - start) > timeout:\n raise Exception('Timeout during device sync')\n\n print(\"Devices successfully synchronized.\")\n\n # Device settings\n demod_c = 0 # demod channel, for paths on the device\n out_c = 0 # signal output channel\n # Get the value of the instrument's default Signal Output mixer channel.\n prop = discovery.get(props[0]['deviceid'])\n out_mixer_c = zhinst.utils.default_output_mixer_channel(prop, out_c)\n in_c = 0 # signal input channel\n osc_c = 0 # oscillator\n\n time_constant = 1.0e-3 # [s]\n demod_rate = 10e3 # [Sa/s]\n filter_order = 8\n osc_freq = 1e3 # [Hz]\n out_amp = 0.600 # [V]\n\n # Master device settings\n master = props[0]['deviceid'].lower()\n daq.setInt('/%s/sigouts/%d/on' % (master, out_c), 1)\n daq.setDouble('/%s/sigouts/%d/range' % (master, out_c), 1)\n daq.setDouble('/%s/sigouts/%d/amplitudes/%d' % (master, out_c, out_mixer_c), out_amp)\n daq.setDouble('/%s/demods/%d/phaseshift' % (master, demod_c), 0)\n daq.setInt('/%s/demods/%d/order' % (master, demod_c), filter_order)\n daq.setDouble('/%s/demods/%d/rate' % (master, demod_c), demod_rate)\n daq.setInt('/%s/demods/%d/harmonic' % (master, demod_c), 1)\n daq.setInt('/%s/demods/%d/enable' % (master, demod_c), 1)\n daq.setInt('/%s/demods/%d/oscselect' % (master, demod_c), osc_c)\n daq.setInt('/%s/demods/%d/adcselect' % (master, demod_c), in_c)\n daq.setDouble('/%s/demods/%d/timeconstant' % (master, demod_c), time_constant)\n daq.setDouble('/%s/oscs/%d/freq' % (master, osc_c), osc_freq)\n daq.setInt('/%s/sigins/%d/imp50' % (master, in_c), 1)\n daq.setInt('/%s/sigins/%d/ac' % (master, in_c), 0)\n daq.setDouble('/%s/sigins/%d/range' % (master, in_c), out_amp/2)\n daq.setDouble('/%s/sigouts/%d/enables/%d' % (master, out_c, out_mixer_c), 0)\n # Slave device settings\n for prop in props[1:]:\n slave = prop['deviceid'].lower()\n daq.setDouble('/%s/demods/%d/phaseshift' % (slave, demod_c), 0)\n daq.setInt('/%s/demods/%d/order' % (slave, demod_c), filter_order)\n daq.setDouble('/%s/demods/%d/rate' % (slave, demod_c), demod_rate)\n daq.setInt('/%s/demods/%d/harmonic' % (slave, demod_c), 1)\n daq.setInt('/%s/demods/%d/enable' % (slave, demod_c), 1)\n daq.setInt('/%s/demods/%d/oscselect' % (slave, demod_c), osc_c)\n daq.setInt('/%s/demods/%d/adcselect' % (slave, demod_c), in_c)\n daq.setDouble('/%s/demods/%d/timeconstant' % (slave, demod_c), time_constant)\n daq.setDouble('/%s/oscs/%d/freq' % (slave, osc_c), osc_freq)\n daq.setInt('/%s/sigins/%d/imp50' % (slave, in_c), 1)\n daq.setInt('/%s/sigins/%d/ac' % (slave, in_c), 0)\n daq.setDouble('/%s/sigins/%d/range' % (slave, in_c), out_amp/2)\n # Synchronization\n daq.sync()\n time.sleep(1)\n\n # measuring the transient state of demodulator filters using DAQ module\n\n # DAQ module\n # Create a Data Acquisition Module instance, the return argument is a handle to the module\n daqMod = daq.dataAcquisitionModule()\n # Configure the Data Acquisition Module\n # Device on which trigger will be performed\n daqMod.set('dataAcquisitionModule/device', master)\n # The number of triggers to capture (if not running in endless mode).\n daqMod.set('dataAcquisitionModule/count', 1)\n daqMod.set('dataAcquisitionModule/endless', 0)\n # 'dataAcquisitionModule/grid/mode' - Specify the interpolation method of\n # the returned data samples.\n #\n # 1 = Nearest. If the interval between samples on the grid does not match\n # the interval between samples sent from the device exactly, the nearest\n # sample (in time) is taken.\n #\n # 2 = Linear interpolation. If the interval between samples on the grid does\n # not match the interval between samples sent from the device exactly,\n # linear interpolation is performed between the two neighbouring\n # samples.\n #\n # 4 = Exact. The subscribed signal with the highest sampling rate (as sent\n # from the device) defines the interval between samples on the DAQ\n # Module's grid. If multiple signals are subscribed, these are\n # interpolated onto the grid (defined by the signal with the highest\n # rate, \"highest_rate\"). In this mode, dataAcquisitionModule/duration is\n # read-only and is defined as num_cols/highest_rate.\n grid_mode = 2\n daqMod.set('dataAcquisitionModule/grid/mode', grid_mode)\n # type:\n # NO_TRIGGER = 0\n # EDGE_TRIGGER = 1\n # DIGITAL_TRIGGER = 2\n # PULSE_TRIGGER = 3\n # TRACKING_TRIGGER = 4\n # HW_TRIGGER = 6\n # TRACKING_PULSE_TRIGGER = 7\n # EVENT_COUNT_TRIGGER = 8\n daqMod.set('dataAcquisitionModule/type', 1)\n # triggernode, specify the triggernode to trigger on.\n # SAMPLE.X = Demodulator X value\n # SAMPLE.Y = Demodulator Y value\n # SAMPLE.R = Demodulator Magnitude\n # SAMPLE.THETA = Demodulator Phase\n # SAMPLE.AUXIN0 = Auxilliary input 1 value\n # SAMPLE.AUXIN1 = Auxilliary input 2 value\n # SAMPLE.DIO = Digital I/O value\n triggernode = '/%s/demods/%d/sample.r' % (master, demod_c)\n daqMod.set('dataAcquisitionModule/triggernode', triggernode)\n # edge:\n # POS_EDGE = 1\n # NEG_EDGE = 2\n # BOTH_EDGE = 3\n daqMod.set('dataAcquisitionModule/edge', 1)\n demod_rate = daq.getDouble('/%s/demods/%d/rate' % (master, demod_c))\n # Exact mode: To preserve our desired trigger duration, we have to set\n # the number of grid columns to exactly match.\n trigger_duration = time_constant*30\n sample_count = demod_rate*trigger_duration\n daqMod.set('dataAcquisitionModule/grid/cols', sample_count)\n # The length of each trigger to record (in seconds).\n daqMod.set('dataAcquisitionModule/duration', trigger_duration)\n daqMod.set('dataAcquisitionModule/delay', -trigger_duration/4)\n # Do not return overlapped trigger events.\n daqMod.set('dataAcquisitionModule/holdoff/time', 0)\n daqMod.set('dataAcquisitionModule/holdoff/count', 0)\n daqMod.set('dataAcquisitionModule/level', out_amp/6)\n # The hysterisis is effectively a second criteria (if non-zero) for triggering\n # and makes triggering more robust in noisy signals. When the trigger `level`\n # is violated, then the signal must return beneath (for positive trigger edge)\n # the hysteresis value in order to trigger.\n daqMod.set('dataAcquisitionModule/hysteresis', 0.01)\n # synchronizing the settings\n daq.sync()\n\n # Recording\n\n # Subscribe to the demodulators\n daqMod.unsubscribe('*')\n master_subscribe_node = '/%s/demods/%d/sample.r' % (master, demod_c)\n daqMod.subscribe(master_subscribe_node)\n for prop in props[1:]:\n slave_subscribe_node = '/%s/demods/%d/sample.r' % (prop['deviceid'], demod_c)\n daqMod.subscribe(slave_subscribe_node)\n\n # Execute the module\n daqMod.execute()\n # Send a trigger\n daq.setDouble('/%s/sigouts/%d/enables/%d' % (master, out_c, out_mixer_c), 1)\n\n # wait for the acquisition to be finished\n while not daqMod.finished():\n time.sleep(1)\n print(\"Progress {:.2%}\".format(daqMod.progress()[0]), end=\"\\r\")\n\n # Read the result\n result = daqMod.read(True)\n\n # Turn off the trigger\n daq.setDouble('/%s/sigouts/%d/enables/%d' % (master, out_c, out_mixer_c), 0)\n # Finish the DAQ module\n daqMod.finish()\n daqMod.clear()\n\n # Stopping the MDS module\n if synchronize:\n mds.clear()\n\n # Extracting and plotting the data\n\n if do_plot:\n\n # Master data\n mClockbase = daq.getDouble('/%s/clockbase' % master)\n masTimestamp = result[master_subscribe_node][0]['timestamp']\n masTime = (masTimestamp[0] - float(masTimestamp[0][0])) / mClockbase\n masDemodAmp = result[master_subscribe_node][0]['value'][0]\n # Plotting\n import matplotlib.pyplot as plt\n\n plt.figure(1)\n plt.clf()\n axes1 = plt.subplot(2, 1, 1)\n plt.plot(masTime*1E3, masDemodAmp*1E3, color='blue')\n axes1.set_ylabel('Amplitude [mV]', fontsize=12, color='k')\n axes1.legend(['Master'])\n axes1.set_title('Transient Measurement by DAQ Module')\n plt.grid(True)\n\n # Slave data\n for prop in props[1:]:\n slave = prop['deviceid'].lower()\n slave_subscribe_node = '/%s/demods/%d/sample.r' % (slave, demod_c)\n sClockbase = daq.getDouble('/%s/clockbase' % slave)\n slvTimestamp = result[slave_subscribe_node][0]['timestamp']\n slvTime = (slvTimestamp[0] - float(slvTimestamp[0][0])) / sClockbase\n slvDemodAmp = result[slave_subscribe_node][0]['value'][0]\n\n axes2 = plt.subplot(2, 1, 2)\n plt.plot(slvTime*1E3, slvDemodAmp*1E3, color='red')\n axes2.legend(['Slaves'])\n axes2.set_xlabel('Time [ms]', fontsize=12, color='k')\n axes2.set_ylabel('Amplitude [mV]', fontsize=12, color='k')\n plt.grid(True)\n\n plt.figure(2)\n plt.clf()\n axes1 = plt.subplot(2, 1, 1)\n plt.plot(masTime*1E3, masDemodAmp*1E3, color='blue')\n\n for prop in props[1:]:\n slave = prop['deviceid'].lower()\n slave_subscribe_node = '/%s/demods/%d/sample.r' % (slave, demod_c)\n sClockbase = daq.getDouble('/%s/clockbase' % slave)\n slvTimestamp = result[slave_subscribe_node][0]['timestamp']\n slvTime = (slvTimestamp[0] - float(slvTimestamp[0][0])) / sClockbase\n slvDemodAmp = result[slave_subscribe_node][0]['value'][0]\n plt.plot(slvTime*1E3, slvDemodAmp*1E3, color='red')\n axes1.set_ylabel('Amplitude [mV]', fontsize=12, color='k')\n axes1.legend(['Master', 'Slaves'])\n axes1.set_title('Transient Measurement by DAQ Module')\n plt.grid(True)\n\n axes2 = plt.subplot(2, 1, 2)\n for prop in props[1:]:\n slave = prop['deviceid'].lower()\n slave_subscribe_node = '/%s/demods/%d/sample.r' % (slave, demod_c)\n sClockbase = daq.getDouble('/%s/clockbase' % slave)\n slvTimestamp = result[slave_subscribe_node][0]['timestamp']\n slvTime = (slvTimestamp[0] - float(slvTimestamp[0][0])) / sClockbase\n plt.plot(slvTime*1E3, (masTime - slvTime)*1E3, color='green')\n axes2.set_title('Time Difference between Master and Slaves')\n axes2.set_xlabel('Time [ms]', fontsize=12, color='k')\n axes2.set_ylabel('Time difference [ms]', fontsize=12, color='k')\n plt.grid(True)\n\n plt.tight_layout()\n plt.draw()\n\n plt.show()\n\n return result\n","sub_path":"Drivers/python_libs/linux/zhinst/examples/common/example_multidevice_data_acquisition.py","file_name":"example_multidevice_data_acquisition.py","file_ext":"py","file_size_in_byte":15143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"220136552","text":"several_things=[\"hello\",2,4,6.0,7.5,234352354,\"the end\",\"\",99]\n\n#program 1\nfor i in several_things:\n print(\"List:\",i)\n#program 2\nfor j in several_things:\n print(type(j))\n#program 3\nstr_list= [\"hello\",\"\",\"goodbye\",\"wonderful\",\"I love Python\"]\n\nfor k in str_list:\n print(len(k))\n\n#program 4\naddition_str=\"2+5+10+20\"\nlst=list()\nlst=addition_str.split(\"+\")\nprint(lst)\nsum=0\nfor i in lst:\n j=int(i)\n sum=sum+j\n\nprint(sum)\n#program 5\nweek_temps_f=\"75.1,77.7,83.2,82.5,81.0,79.5,85.7\"\nlst=list()\nlst=week_temps_f.split(\",\")\nprint(lst)\nsum=0\ncount=0\nfor i in lst:\n i=float(i)\n count=count+1\n sum=sum+i\n\navg=sum/count\nprint(\"Average of numbers in list:\\n\",avg)\n","sub_path":"list1.py","file_name":"list1.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"292258508","text":"\"\"\"\r\nContains the PokerGame class\r\n\"\"\"\r\nfrom subprocess import check_call\r\nfrom time import sleep\r\n\r\nfrom deck import Deck\r\nfrom enums import GameState\r\nfrom hand import Hand\r\nfrom hand_evaluator import get_best_hand, get_players_with_hand\r\nfrom player import Player\r\n\r\nclass PokerGame(object):\r\n \"\"\"Play a game of poker\"\"\"\r\n def __init__(self, small_blind, big_blind, players):\r\n self.s_blind = small_blind\r\n self.b_blind = big_blind\r\n self.players = players\r\n self.active_players = []\r\n self.pot = 0\r\n self.call_amount = self.b_blind\r\n self.game_state = GameState.PRE_FLOP\r\n self.deck = Deck()\r\n self.deck.shuffle()\r\n self.first_round = True\r\n\r\n for player in players:\r\n self.active_players.append(player)\r\n\r\n def make_bet(self, player, amount):\r\n \"\"\"Make a bet: Withdraw from player and add to pot\"\"\"\r\n player.chips -= int(amount)\r\n self.pot += int(amount)\r\n player.current_bet += int(amount)\r\n\r\n def reset_round(self):\r\n \"\"\"Reset all game variables for next round\"\"\"\r\n self.pot = 0\r\n self.call_amount = self.b_blind\r\n self.game_state = GameState.PRE_FLOP\r\n self.deck = Deck()\r\n self.deck.shuffle()\r\n self.first_round = True\r\n\r\n self.active_players = []\r\n for player in self.players:\r\n player.reset()\r\n self.active_players.append(player)\r\n\r\n def deal_cards(self):\r\n \"\"\"Deal appropriate cards to each player depending on game state\"\"\"\r\n if self.game_state == GameState.PRE_FLOP:\r\n for i in range(0, 2):\r\n for player in self.players:\r\n card = self.deck.draw_card()\r\n player.hand.add_card(card)\r\n elif self.game_state == GameState.FLOP:\r\n for i in range(0, 3):\r\n card = self.deck.draw_card()\r\n for player in self.players:\r\n player.hand.add_card(card)\r\n elif self.game_state == GameState.TURN or self.game_state == GameState.RIVER:\r\n card = self.deck.draw_card()\r\n for player in self.players:\r\n player.hand.add_card(card)\r\n\r\n def process_user_action(self, player, action_lst, call_amount):\r\n \"\"\"Process a player's requested action\"\"\"\r\n action = action_lst[0]\r\n if len(action_lst) == 2:\r\n amount = int(action_lst[1])\r\n if action == \"RAISE\":\r\n self.call_amount = amount + self.call_amount\r\n self.make_bet(player, self.call_amount - player.current_bet)\r\n else: # CALL\r\n self.call_amount = amount\r\n self.make_bet(player, self.call_amount - player.current_bet)\r\n elif action == \"FOLD\":\r\n player.is_in = False\r\n self.active_players.remove(player)\r\n elif action == \"CALL\":\r\n self.make_bet(player, call_amount - player.current_bet)\r\n return action\r\n\r\n def get_user_action(self, player):\r\n \"\"\"Return a list representing the user's action\"\"\"\r\n # get possible actions depending on game state\r\n if self.game_state == GameState.PRE_FLOP:\r\n possible_actions = [\"FOLD\", \"CALL\", \"BET\"]\r\n prompt = player.name + \": [FOLD] [CALL] [BET]: \"\r\n if player == self.players[1] and self.first_round and \\\r\n self.call_amount == player.current_bet:\r\n self.first_round = False\r\n possible_actions = [\"FOLD\", \"CHECK\", \"BET\"]\r\n prompt = player.name + \": [FOLD] [CHECK] [BET]: \"\r\n elif player == self.players[1] and self.first_round and not \\\r\n self.call_amount == player.current_bet:\r\n self.first_round = False\r\n possible_actions = [\"FOLD\", \"CALL\", \"BET\"]\r\n prompt = player.name + \": [FOLD] [CALL] [BET]: \"\r\n elif not self.first_round:\r\n possible_actions = [\"FOLD\", \"CALL\"]\r\n prompt = player.name + \": [FOLD] [CALL]: \"\r\n else:\r\n if self.call_amount == player.current_bet:\r\n possible_actions = [\"FOLD\", \"CHECK\", \"RAISE\"]\r\n prompt = player.name + \": [FOLD] [CHECK] [RAISE]: \"\r\n elif self.call_amount > player.current_bet:\r\n possible_actions = [\"FOLD\", \"CALL\", \"RAISE\"]\r\n prompt = player.name + \": [FOLD] [CALL] [RAISE]: \"\r\n\r\n # get user input\r\n print(\"Current Hand: \" + str(player.hand))\r\n while True:\r\n user_input = input(prompt).upper().split()\r\n\r\n if user_input[0] in possible_actions:\r\n if len(user_input) > 2:\r\n print(\"ERROR: too many arguments\")\r\n elif len(user_input) == 2:\r\n try:\r\n amount = int(user_input[1])\r\n except:\r\n print(\"ERROR: second argument must be an integer\")\r\n continue\r\n if player.chips < amount:\r\n print(\"ERROR: not enough chips to bet\")\r\n continue\r\n return user_input\r\n else:\r\n print(\"ERROR: you can't do that\")\r\n\r\n def print_done_betting(self):\r\n \"\"\"Print message to indicate betting phase has complete\"\"\"\r\n print(\"\\n*&*&*&*&*&*&*&*&*&*&*&*&\")\r\n print(\"DONE BETTING \" + self.game_state.value)\r\n print(\"*&*&*&*&*&*&*&*&*&*&*&*&\")\r\n sleep(1)\r\n\r\n def print_dealing(self):\r\n \"\"\"Print message to indicate cards are being dealt\"\"\"\r\n for i in range(0, 5):\r\n check_call(\"clear\")\r\n print(\"Dealing cards\" + \".\" * i)\r\n sleep(.25)\r\n\r\n def print_welcome(self):\r\n \"\"\"Print welcome message\"\"\"\r\n print(\"----------------------------------------\")\r\n print(\"WELCOME TO WILD WEST TEXAS HOLD EM POKER\")\r\n print(\"----------------------------------------\\n\")\r\n\r\n def print_game_board(self):\r\n \"\"\"print game board\"\"\"\r\n for player in self.players:\r\n # determine blind text\r\n if player == self.players[0]:\r\n blind_text = \"(SB)\"\r\n elif player == self.players[1]:\r\n blind_text = \"(BB)\"\r\n else:\r\n blind_text = \"\"\r\n if player in self.active_players:\r\n print(\"{:<10} -- Current Bet: {:>8} Call Amount: {:>8} Chips: {:>8} {}\"\r\n .format(player.name, player.current_bet, self.call_amount, player.chips, blind_text))\r\n else:\r\n print(\"{:<10} -- OUT {:>46} {:>8} {}\"\r\n .format(player.name, \"Chips:\", player.chips, blind_text))\r\n\r\n print(\"pot amount: {}\".format(self.pot))\r\n\r\n def print_round_summary(self):\r\n \"\"\"print the round summary\"\"\"\r\n print(\"\\n\\nEND OF ROUND SUMMARRY\")\r\n print(\"---------------------\")\r\n for player in self.players:\r\n print(\"{:<10} -- Chips: {:>8}\".format(player.name, player.chips))\r\n\r\n def initiate_betting(self, game_state):\r\n \"\"\"Initiate the betting sequence\"\"\"\r\n s_blind_placed = False\r\n b_blind_placed = False\r\n first_pass = True\r\n end_enable = False\r\n if game_state == GameState.PRE_FLOP:\r\n end_player = self.players[2]\r\n else:\r\n end_player = self.players[0]\r\n while True:\r\n # Check to see if betting round is done\r\n if not first_pass:\r\n betting_done = True\r\n for player in self.players:\r\n if not player.current_bet == self.call_amount and player.is_in:\r\n betting_done = False\r\n break\r\n if betting_done:\r\n break\r\n\r\n for player in self.players:\r\n check_call(\"clear\")\r\n if game_state == GameState.PRE_FLOP:\r\n # Check to see if blinds are required\r\n if not s_blind_placed and self.players.index(player) == 0:\r\n # place small blind\r\n self.make_bet(player, self.s_blind)\r\n s_blind_placed = True\r\n print(player.name + \" places small blind of \" + str(self.s_blind))\r\n continue\r\n elif not b_blind_placed and self.players.index(player) == 1:\r\n # place big blind\r\n self.make_bet(player, self.b_blind)\r\n b_blind_placed = True\r\n print(player.name + \" places big blind of \" + str(self.b_blind))\r\n continue\r\n\r\n # Check to see if the player is the only active one left\r\n # If True\r\n if len(self.active_players) == 1 and player in self.active_players:\r\n return True\r\n\r\n # check if player has folded\r\n if not player.is_in:\r\n continue\r\n\r\n # Check to see if the player is the end player\r\n if end_player == player:\r\n if end_enable:\r\n break\r\n else:\r\n end_enable = True\r\n\r\n # print game board\r\n self.print_game_board()\r\n\r\n # Check if player is human\r\n if player.is_human:\r\n user_action_lst = self.get_user_action(player)\r\n action = self.process_user_action(player, user_action_lst, self.call_amount)\r\n if action in [\"RAISE\", \"BET\"]:\r\n end_player = player\r\n else:\r\n # Have CPU make decision\r\n # info to pass: pot size, call_amount\r\n \"\"\"\r\n Possible actions\r\n ----------------\r\n [\"FOLD\"] <- exits round, sets player.is_in to false\r\n [\"CHECK\"] <- only possible if call_amount = player.bet_amount\r\n [\"CALL\"] <- bets call_amount\r\n [\"RAISE X\"] <- bets X amount\r\n \"\"\"\r\n\r\n first_pass = False\r\n return False\r\n\r\n def play(self):\r\n \"\"\"Launch a game of Poker\"\"\"\r\n while True: # play until player exits\r\n check_call(\"clear\")\r\n self.print_welcome()\r\n\r\n start_game = input(\"Would you like to start a round of poker? y/n: \")\r\n if start_game.upper() == \"Y\":\r\n for state in GameState:\r\n self.game_state = state\r\n self.print_dealing()\r\n self.deal_cards()\r\n is_done = self.initiate_betting(self.game_state)\r\n check_call(\"clear\")\r\n\r\n if is_done:\r\n print(\"All but one have folded, game is over! Determining winner...\")\r\n sleep(1)\r\n break # continue to end of game to determine winner\r\n else:\r\n self.print_done_betting()\r\n sleep(1)\r\n\r\n check_call(\"clear\")\r\n\r\n # Determine if there is more than one player active and showdown is necessary\r\n if len(self.active_players) == 1:\r\n winner = self.active_players[0]\r\n print(str(winner) + \" wins the pot amount of: \" + str(self.pot))\r\n winner.chips += self.pot\r\n\r\n else:\r\n # Determine and print the winner, update chips for winning player(s)\r\n print(\"End of betting and there are more than one player active. ENTERING SHOWDOWN!\")\r\n showdown_hands = []\r\n for player in self.active_players:\r\n showdown_hands.append(player.get_best_hand())\r\n\r\n winning_hand = get_best_hand(showdown_hands)\r\n winning_players = get_players_with_hand(winning_hand, self.active_players)\r\n winnings = self.pot / len(winning_players)\r\n\r\n print(\"Winning Hand = \" + str(winning_hand))\r\n\r\n for player in winning_players:\r\n player.chips += winnings\r\n print(str(player) + \" has the winning hand and wins the pot amount of: \" + \\\r\n str(winnings))\r\n\r\n self.print_round_summary()\r\n self.reset_round()\r\n self.players.append(self.players.pop(0))\r\n input(\"\\nGame over, press any key to continue: \")\r\n else:\r\n print(\"You have chosen to stop playng. Have a nice day!\")\r\n break\r\n\r\nif __name__ == \"__main__\":\r\n PLAYER1 = Player(\"Arnej\", 500, Hand(), True)\r\n PLAYER2 = Player(\"Drizzy Dre\", 500, Hand(), True)\r\n PLAYER3 = Player(\"Milo\", 500, Hand(), True)\r\n\r\n PLAYERS = [PLAYER1, PLAYER2, PLAYER3]\r\n\r\n GAME = PokerGame(1, 2, PLAYERS)\r\n GAME.play()\r\n","sub_path":"poker.py","file_name":"poker.py","file_ext":"py","file_size_in_byte":13263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"359144338","text":"from datetime import datetime\n\n\ndef hour_float_to_time(time_float, is_24hr_format=True):\n \"\"\" Converts hour floats like 9.5 into 9:30 or 09:30 if is_24_hr_format is True \"\"\"\n if type(time_float) is str:\n time_float = float(time_float)\n hour, minute = divmod(time_float * 60, 60)\n # print('hour n minute', hour, minute)\n hm_string = '{0:02.0f}:{1:02.0f}'.format(hour, minute)\n if is_24hr_format:\n return hm_string\n else:\n return datetime.strptime(hm_string, '%H:%M').strftime('%-I.%M %p')\n\n\ndef float_to_day_time(time_float):\n if type(time_float) is str:\n time_float = float(time_float)\n day = int(time_float)\n if time_float > 0:\n pass\n # print('time_float = ', time_float)\n day_left = (time_float % 1) * 24\n hour, minute = divmod(day_left * 60, 60)\n if minute >= 59.00:\n minute = 0\n hour += 1\n if hour >= 7.9:\n day += 1\n hour = 0\n hm_string = str(day) + ' - ' + '{0:02.0f}:{1:02.0f}'.format(hour, minute)\n return hm_string\n\n\ndef ordinal_num(number):\n return str(number) + (\"th\" if 4 <= number % 100 <= 20 else {1:\"st\",2:\"nd\",3:\"rd\"}.get(number % 10, \"th\"))","sub_path":"utility/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"528144435","text":"#!/usr/bin/env python\nfrom sqlalchemy import orm\n# cancerhermit\nfrom pg_catalog import pg_attrdef, pg_class\nfrom pgvcs import row, _regclass,column,index,foreign_table,sequence,table,trigger,rule,view\n\nclass regclass(_regclass):\n \"\"\"init_on_load class assigment only\"\"\"\n __table__ = _regclass.__table__\n\n @orm.reconstructor\n def init_on_load(self):\n super(type(self),self).init_on_load()\n self.columns = []\n self.inhparent = None\n self.inhseqno = None\n if self.relkind=='c': # table for composite type\n pass\n #self.__class__ = composite_table\n if self.relkind=='i': # index class\n self.__class__ = index\n if self.relkind=='t': # toast class\n return\n if self.relkind=='f':\n self.__class__ = foreign_table\n if self.relkind=='r':\n self.__class__ = table\n if self.relkind=='S':\n self.__class__ = sequence\n sql='select * from %s.%s' % (self.schema.name,self.name)\n self.params=self.db.session.execute(sql).fetchone()\n if self.relkind=='v':\n self.__class__ = view\n #raise ValueError(\"Invalid regclass relkind, %s\" % self.relkind)\n\n","sub_path":"pgvcs/ddl/regclass.py","file_name":"regclass.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"3793320","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import integrate\n\nT0 = 1/5000\nt = np.linspace(0,20,10000)\nf_sampling = 1/(t[1]-t[0])\nlfft = len(t)\n\ndef v1(t):\n\tE0 = 8\n\tf0 = 100*1e3\n\tEm = 6\n\tfm = 5*1e3\n\tem = Em*np.cos(2*np.pi*fm*t)\n\te0 = E0*np.cos(2*np.pi*f0*t)\n\treturn 0.5*(em+e0)\n\nfreq = np.fft.fftfreq(lfft)\nfreq = np.fft.fftshift(freq)\n\n\ndef v2(t):\n\tb1,b2=0.054,0.004\n\treturn b1*v1(t) + b2*v1(t)**2\n'''\ndef find_period(array_y,array_x):\n\tts = array_x[1]-array_x[0]\n\tN_ts = np.where(array_y>max(array_y)*0.99)[0][-1]\n\tN_ts -= np.where(array_y>max(array_y)*0.99)[0][-2]\n\treturn N_ts*ts\n'''\n\n\ndef _cos(x,n_,w_):\n\treturn v2(x)*np.cos(x*n_*w_)\n\t\ndef data_cos(data,x,n_,w_):\n\treturn data*np.cos(x*n_*w_)\n\t\ndef an(T,n=10):\n\tan=np.zeros(n)\n\tW = 2*np.pi/T\n\n\tfor i in range(n):\n\t\tan[i]=(2/T)*(integrate.quad(_cos,0,T,args=(i,W))[0])\n\treturn an\n\ndef data_an(data_,x,T,TN,n=10):\n\tan=np.zeros(n)\n\tW = 2*np.pi/T\n\tfor i in range(n):\n\t\tarray = data_cos(data_[TN:2*TN],x[TN:2*TN],i,W)\n\t\tan[i]=(2/TN)*(np.trapz(array))\n\treturn an\n\n\n\n\n\t\ndef _sin(x,n_,w_):\n\treturn v2(x)*np.sin(x*n_*w_)\n\t\ndef data_sin(data,x,n_,w_):\n\treturn data*np.sin(x*n_*w_)\n\n\ndef bn(T,n=10):\n\tbn=np.zeros(n)\n\tW = 2*np.pi/T\n\n\tfor i in range(n):\n\t\tbn[i]=(2/T)*(integrate.quad(_sin,0,T,args=(i,W))[0])\n\treturn bn\t\n\n\ndef data_bn(data_,x,T,TN,n=10):\n\tbn=np.zeros(n)\n\tW = 2*np.pi/T\n\tfor i in range(n):\n\t\tarray = data_sin(data_[TN:2*TN],x[TN:2*TN],i,W)\n\t\tbn[i]=(2/TN)*(np.trapz(array))\n\treturn bn\n\n\n\n\n\n\ndef rebuilt(an_coefs,bn_coefs,T,x):\n\tw0 = 2*np.pi/T\n\tN = len(an_coefs)\n\tf_sum = 0\n\tfor n in range(N):\n\t\tf_sum += an_coefs[n]*np.cos(x*n*w0)\n\t\tf_sum += bn_coefs[n]*np.sin(x*n*w0)\n\treturn f_sum\n\t\n\n\n#filtragem do passa-faixas\nfrom scipy.signal import butter\nfrom scipy.signal import lfilter\nC = 130*1e-9\nL = 20*1e-6\nwc = 1/(np.sqrt(L*C))\nB = 2*np.pi*14*1e3 #bandwidth\nQ = wc/B #quality factor\nw_inferior = wc*np.sqrt(1+1/(4*Q**2))-wc/(2*Q)\nw_superior = wc*np.sqrt(1+1/(4*Q**2))+wc/(2*Q)\n\nfin=w_inferior/(2*np.pi)\nfsup=w_superior/(2*np.pi)\n\n\n\ndef butter_bandpass(lowcut, highcut, fs, order=5):\n nyq = 0.5 * fs\n low = lowcut / nyq\n high = highcut / nyq\n b, a = butter(order, [low, high], btype='band')\n return b, a\n\n\ndef butter_bandpass_filter(data, lowcut, highcut, fs, order=5):\n b, a = butter_bandpass(lowcut, highcut, fs, order=order)\n y = lfilter(b, a, data)\n return y\n\nv3 = butter_bandpass_filter(v2(t),fin/10000,fsup/10000,f_sampling,order=1)\nv3_S = np.fft.fft(v3,lfft)/lfft\nv3_S = np.fft.fftshift(v3_S)\n\n\nN = 25\nTN = 1000\na_n = data_an(v3,t,T0,TN,N)\nb_n = data_bn(v3,t,T0,TN,N)\n\nv3_rec = rebuilt(a_n,b_n,14,t)\nv3_rec_S = np.fft.fftshift(np.fft.fft(v3_rec))\nplt.subplot(211)\nplt.title(\"V3(t): sinal original\")\nplt.ylabel(\"Amplitude (V)\")\nplt.xlabel(\"tempo (s)\")\n\nplt.plot(t[TN:2*TN+200],v3[TN:2*TN+200])\n\nplt.subplot(212)\nplt.title(\"V3(f): sinal reconstruído pela Série de Fourier\")\nplt.ylabel(\"Amplitude (V)\")\nplt.xlabel(\"tempo (s)\")\nplt.plot(t,v3_rec,'r')\n\nplt.tight_layout()\nplt.show()\n\n\n\t\n\n","sub_path":"am_dsb_fseries_v3.py","file_name":"am_dsb_fseries_v3.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"516065695","text":"# coding: utf-8\n\nimport glob, sys\nfrom distutils.core import setup\ntry:\n from setuptools import setup\nexcept ImportError:\n pass\n\n\nversion = '0.2.1'\n\nsetup(\n name=\"taxon\",\n version=version,\n description=(\"Provides simple object taxonomy.\"),\n classifiers=[\"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"License :: Public Domain\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\"],\n author=\"Yasushi Masuda\",\n author_email=\"whosaysni at gmail.com\",\n url=\"http://github.com/whosaysni/taxon/\",\n license=\"Public Domain\",\n zip_safe=True,\n packages=[\"taxon\"],\n test_suite = 'tests.suite',\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413183441","text":"from deepspeed.profiling.flops_profiler import get_model_profile\nfrom deepspeed.profiling.flops_profiler import FlopsProfiler\nimport torchvision.models as models\nimport torch\nimport torchvision\nimport random\nimport time\nimport argparse\nimport os\nimport sys\nimport math\nimport torch.nn as nn\nimport torch.multiprocessing as mp\nfrom utils.fp16util import network_to_half, get_param_copy\nfrom utils.shufflenet import shufflenet\nfrom utils.shufflenet_v2 import shufflenet as shufflenet_v2\ntry:\n import apex\n HAVE_APEX = True\nexcept:\n HAVE_APEX = False\n\ndef weight_init(m):\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n# num_classes=1000\nmodels = {\n \"alexnet\" : torchvision.models.alexnet,\n \"densenet121\" : torchvision.models.densenet121,\n \"densenet161\" : torchvision.models.densenet161,\n \"densenet169\" : torchvision.models.densenet169,\n \"densenet201\" : torchvision.models.densenet201,\n \"googlenet\" : torchvision.models.googlenet,\n \"inception_v3\" : torchvision.models.inception_v3,\n \"mnasnet0_5\" : torchvision.models.mnasnet0_5,\n \"mnasnet0_75\" : torchvision.models.mnasnet0_75,\n \"mnasnet1_0\" : torchvision.models.mnasnet1_0,\n \"mnasnet1_3\" : torchvision.models.mnasnet1_3,\n \"mobilenet_v2\" : torchvision.models.mobilenet_v2,\n \"resnet18\" : torchvision.models.resnet18,\n \"resnet34\" : torchvision.models.resnet34,\n \"resnet50\" : torchvision.models.resnet50,\n \"resnet101\" : torchvision.models.resnet101,\n \"resnet152\" : torchvision.models.resnet152,\n \"resnext50\" : torchvision.models.resnext50_32x4d,\n \"resnext50_32x4d\" : torchvision.models.resnext50_32x4d,\n \"resnext101\" : torchvision.models.resnext101_32x8d,\n \"resnext101_32x8d\" : torchvision.models.resnext101_32x8d,\n \"shufflenet\" : shufflenet,\n \"shufflenet_v2\" : shufflenet_v2,\n \"shufflenet_v2_x05\" : torchvision.models.shufflenet_v2_x0_5,\n \"shufflenet_v2_x10\" : torchvision.models.shufflenet_v2_x1_0,\n \"shufflenet_v2_x15\" : torchvision.models.shufflenet_v2_x1_5,\n \"shufflenet_v2_x20\" : torchvision.models.shufflenet_v2_x2_0,\n \"shufflenet_v2_x0_5\" : torchvision.models.shufflenet_v2_x0_5,\n \"shufflenet_v2_x1_0\" : torchvision.models.shufflenet_v2_x1_0,\n \"shufflenet_v2_x1_5\" : torchvision.models.shufflenet_v2_x1_5,\n \"shufflenet_v2_x2_0\" : torchvision.models.shufflenet_v2_x2_0,\n \"SqueezeNet\" : torchvision.models.squeezenet1_0,\n \"squeezenet1_0\" : torchvision.models.squeezenet1_0,\n \"SqueezeNet1.1\" : torchvision.models.squeezenet1_1,\n \"squeezenet1_1\" : torchvision.models.squeezenet1_1,\n \"vgg11\" : torchvision.models.vgg11,\n \"vgg13\" : torchvision.models.vgg13,\n \"vgg16\" : torchvision.models.vgg16,\n \"vgg19\" : torchvision.models.vgg19,\n \"vgg11_bn\" : torchvision.models.vgg11_bn,\n \"vgg13_bn\" : torchvision.models.vgg13_bn,\n \"vgg16_bn\" : torchvision.models.vgg16_bn,\n \"vgg19_bn\" : torchvision.models.vgg19_bn,\n \"wide_resnet50_2\" : torchvision.models.wide_resnet50_2,\n \"wide_resnet101_2\" : torchvision.models.wide_resnet101_2,\n}\n\n# newer torchvision models, for backwards compat\ntry:\n models[\"mobilenet_v3_large\"] = torchvision.models.mobilenet_v3_large\n models[\"mobilenet_v3_small\"] = torchvision.models.mobilenet_v3_small\nexcept AttributeError:\n pass\n\n# segmentation models, num_classes=21\nsegmentation_models = {\n \"fcn_resnet50\" : torchvision.models.segmentation.fcn_resnet50,\n \"fcn_resnet101\" : torchvision.models.segmentation.fcn_resnet101,\n \"deeplabv3_resnet50\" : torchvision.models.segmentation.deeplabv3_resnet50,\n \"deeplabv3_resnet101\" : torchvision.models.segmentation.deeplabv3_resnet101,\n}\n\n# newer torchvision segmentation models, for backwards compat\ntry:\n segmentation_models[\"deeplabv3_mobilenet_v3_large\"] = torchvision.models.segmentation.deeplabv3_mobilenet_v3_large\n segmentation_models[\"lraspp_mobilenet_v3_large\"] = torchvision.models.segmentation.lraspp_mobilenet_v3_large,\nexcept AttributeError:\n pass\n\ndef get_network_names():\n return sorted(list(models.keys()) + list(segmentation_models.keys()))\n\ndef get_network(net):\n # aux_logits=False only used by inception_v3\n if \"inception_v3\" == net:\n return models[net](aux_logits=False).to(device=\"cuda\")\n elif net in models:\n return models[net]().to(device=\"cuda\")\n elif net in segmentation_models:\n return segmentation_models[net]().to(device=\"cuda\")\n else:\n print (\"ERROR: not a supported model '%s'\" % net)\n sys.exit(1)\n\ndef forwardbackward(inp, optimizer, network, target, amp_opt_level, prof_step=0):\n # params: prof_step - none zero step to profile\n\n optimizer.zero_grad()\n\n if prof_step != 0:\n prof = FlopsProfiler(network)\n prof.start_profile()\n\n out = network(inp)\n # WIP: googlenet, deeplabv3_*, fcn_* missing log_softmax for this to work\n loss = torch.nn.functional.cross_entropy(out, target)\n\n # End profiler here if profile fwd pass only\n\n if prof_step != 0:\n if amp_opt_level:\n with apex.amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n\n # End profiler here to both fwd &bwd passes\n flops = prof.get_total_flops(as_string=True)\n params = prof.get_total_params(as_string=True)\n prof.print_model_profile(profile_step=prof_step)\n prof.end_profile()\n\n else:\n if amp_opt_level:\n with apex.amp.scale_loss(loss, optimizer) as scaled_loss:\n scaled_loss.backward()\n else:\n loss.backward()\n optimizer.step()\n\ndef rendezvous(distributed_parameters):\n print(\"Initializing process group...\")\n torch.distributed.init_process_group(backend=distributed_parameters['dist_backend'], init_method=distributed_parameters['dist_url'], rank=distributed_parameters['rank'], world_size=distributed_parameters['world_size'])\n print(\"Rendezvous complete. Created process group...\")\n\ndef run_benchmarking_wrapper(net, batch_size, iterations, prof_step, amp_opt_level, run_fp16, dataparallel, distributed_dataparallel, device_ids=None, distributed_parameters=None):\n if (dataparallel or distributed_dataparallel):\n ngpus = len(device_ids) if device_ids else torch.cuda.device_count()\n else:\n ngpus = 1\n\n if (distributed_dataparallel):\n # Assumption below that each process launched with --distributed_dataparallel has the same number of devices visible/specified\n distributed_parameters['world_size'] = ngpus * distributed_parameters['world_size']\n distributed_parameters['rank'] = ngpus * distributed_parameters['rank']\n mp.spawn(run_benchmarking, nprocs=ngpus, args=(ngpus, net, batch_size, iterations, prof_step, amp_opt_level, run_fp16, dataparallel, distributed_dataparallel, device_ids, distributed_parameters))\n else:\n run_benchmarking(0, ngpus, net, batch_size, iterations, prof_step, amp_opt_level, run_fp16, dataparallel, distributed_dataparallel, device_ids=None, distributed_parameters=None)\n\ndef run_benchmarking(local_rank, ngpus, net, batch_size, iterations, prof_step, amp_opt_level, run_fp16, dataparallel, distributed_dataparallel, device_ids=None, distributed_parameters=None):\n if device_ids:\n assert ngpus == len(device_ids)\n torch.cuda.set_device(\"cuda:%d\" % device_ids[local_rank])\n else:\n torch.cuda.set_device(\"cuda:0\")\n\n network = get_network(net)\n if \"shufflenet\" == net:\n model.apply(weight_init)\n\n if (run_fp16):\n network = network_to_half(network)\n\n if (dataparallel):\n devices_to_run_on = device_ids if device_ids else list(range(ngpus))\n print (\"INFO: Running dataparallel on devices: {}\".format(str(devices_to_run_on)))\n network = torch.nn.DataParallel(network, device_ids=devices_to_run_on)\n elif (distributed_dataparallel):\n distributed_parameters['rank'] += local_rank\n rendezvous(distributed_parameters)\n devices_to_run_on = [(device_ids[local_rank] if device_ids else local_rank)]\n print (\"INFO: Rank {} running distributed_dataparallel on devices: {}\".format(distributed_parameters['rank'], str(devices_to_run_on)))\n network = torch.nn.parallel.DistributedDataParallel(network, device_ids=devices_to_run_on)\n batch_size = int(batch_size / ngpus)\n\n if (net == \"inception_v3\"):\n inp = torch.randn(batch_size, 3, 299, 299, device=\"cuda\")\n else:\n inp = torch.randn(batch_size, 3, 224, 224, device=\"cuda\")\n if (run_fp16):\n inp = inp.half()\n if net in models:\n # number of classes is 1000 for imagenet\n target = torch.randint(0, 1000, (batch_size,), device=\"cuda\")\n elif net in segmentation_models:\n # number of classes is 21 for segmentation\n target = torch.randint(0, 21, (batch_size,), device=\"cuda\")\n param_copy = network.parameters()\n if (run_fp16):\n param_copy = get_param_copy(network)\n optimizer = torch.optim.SGD(param_copy, lr = 0.01, momentum = 0.9)\n\n if (amp_opt_level):\n network, optimizer = apex.amp.initialize(network, optimizer, opt_level=\"O%d\"%amp_opt_level)\n\n ## warmup.\n print (\"INFO: running forward and backward for warmup.\")\n forwardbackward(inp, optimizer, network, target, amp_opt_level)\n forwardbackward(inp, optimizer, network, target, amp_opt_level)\n\n time.sleep(1)\n torch.cuda.synchronize()\n\n ## benchmark.\n print (\"INFO: running the benchmark..\")\n tm = time.time()\n for i in range(iterations):\n if i == prof_step:\n forwardbackward(inp, optimizer, network, target, amp_opt_level, i)\n else:\n forwardbackward(inp, optimizer, network, target, amp_opt_level)\n torch.cuda.synchronize()\n\n tm2 = time.time()\n time_per_batch = (tm2 - tm) / iterations\n\n if run_fp16:\n dtype = 'FP16'\n elif amp_opt_level == 1:\n dtype = 'AMP-O1: Insert automatic FP16 casts around safe Pytorch functions and Tensor methods.'\n elif amp_opt_level == 2:\n dtype = 'AMP-O2: FP16 training with FP32 batchnorm and FP32 master weights.'\n elif amp_opt_level == 3:\n dtype = 'AMP-O3: Pure FP16 training.'\n elif amp_opt_level == 4:\n dtype = 'AMP-O4: Insert automatic BFLOAT16 casts around safe Pytorch functions and Tensor methods.'\n elif amp_opt_level == 5:\n dtype = 'AMP-O5: BFLOAT16 training with FP32 batchnorm and FP32 master weights.'\n else:\n dtype = 'FP32'\n\n print (\"OK: finished running benchmark..\")\n print (\"--------------------SUMMARY--------------------------\")\n print (\"Microbenchmark for network : {}\".format(net))\n if (distributed_dataparallel):\n print (\"--------This process: rank \" + str(distributed_parameters['rank']) + \"--------\");\n print (\"Num devices: 1\")\n else:\n print (\"Num devices: {}\".format(ngpus))\n print (\"Dtype: {}\".format(dtype))\n print (\"Mini batch size [img] : {}\".format(batch_size))\n print (\"Time per mini-batch : {}\".format(time_per_batch))\n print (\"Throughput [img/sec] : {}\".format(batch_size/time_per_batch))\n if (distributed_dataparallel):\n print (\"\")\n print (\"--------Overall (all ranks) (assuming same num/type devices for each rank)--------\")\n world_size = distributed_parameters['world_size']\n print (\"Num devices: {}\".format(world_size))\n print (\"Dtype: {}\".format(dtype))\n print (\"Mini batch size [img] : {}\".format(batch_size*world_size))\n print (\"Time per mini-batch : {}\".format(time_per_batch))\n print (\"Throughput [img/sec] : {}\".format(batch_size*world_size/time_per_batch))\n\ndef main():\n net = args.network\n batch_size = args.batch_size\n iterations = args.iterations\n prof_step = args.profile_step\n run_fp16 = args.fp16\n amp_opt_level = args.amp_opt_level\n dataparallel = args.dataparallel\n distributed_dataparallel = args.distributed_dataparallel\n device_ids_str = args.device_ids\n if (args.device_ids):\n device_ids = [int(x) for x in device_ids_str.split(\",\")]\n else:\n device_ids = None\n distributed_parameters = {}\n distributed_parameters['rank'] = args.rank\n distributed_parameters['world_size'] = args.world_size\n distributed_parameters['dist_backend'] = args.dist_backend\n distributed_parameters['dist_url'] = args.dist_url\n # Some arguments are required for distributed_dataparallel\n if distributed_dataparallel:\n assert args.rank is not None and \\\n args.world_size is not None and \\\n args.dist_backend is not None and \\\n args.dist_url is not None, \"rank, world-size, dist-backend and dist-url are required arguments for distributed_dataparallel\"\n\n run_benchmarking_wrapper(net, batch_size, iterations, prof_step, amp_opt_level, run_fp16, dataparallel, distributed_dataparallel, device_ids, distributed_parameters)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--network\", type=str, choices=get_network_names(), required=True, help=\"Network to run.\")\n parser.add_argument(\"--batch-size\" , type=int, required=False, default=128, help=\"Batch size (will be split among devices used by this invocation)\")\n parser.add_argument(\"--iterations\", type=int, required=False, default=20, help=\"Iterations\")\n parser.add_argument(\"--profile-step\", type=int, required=False, default=0, help=\"The global profiling step\")\n parser.add_argument(\"--fp16\", type=int, required=False, default=0,help=\"FP16 mixed precision benchmarking\")\n parser.add_argument(\"--amp-opt-level\", type=int, required=False, default=0,help=\"apex.amp mixed precision benchmarking opt level\")\n parser.add_argument(\"--dataparallel\", action='store_true', required=False, help=\"Use torch.nn.DataParallel api to run single process on multiple devices. Use only one of --dataparallel or --distributed_dataparallel\")\n parser.add_argument(\"--distributed_dataparallel\", action='store_true', required=False, help=\"Use torch.nn.parallel.DistributedDataParallel api to run on multiple processes/nodes. The multiple processes need to be launched manually, this script will only launch ONE process per invocation. Use only one of --dataparallel or --distributed_dataparallel\")\n parser.add_argument(\"--device_ids\", type=str, required=False, default=None, help=\"Comma-separated list (no spaces) to specify which HIP devices (0-indexed) to run dataparallel or distributedDataParallel api on. Might need to use HIP_VISIBLE_DEVICES to limit visiblity of devices to different processes.\")\n parser.add_argument(\"--rank\", type=int, required=False, default=None, help=\"Rank of this process. Required for --distributed_dataparallel\")\n parser.add_argument(\"--world-size\", type=int, required=False, default=None, help=\"Total number of ranks/processes. Required for --distributed_dataparallel\")\n parser.add_argument(\"--dist-backend\", type=str, required=False, default=None, help=\"Backend used for distributed training. Can be one of 'nccl' or 'gloo'. Required for --distributed_dataparallel\")\n parser.add_argument(\"--dist-url\", type=str, required=False, default=None, help=\"url used for rendezvous of processes in distributed training. Needs to contain IP and open port of master rank0 eg. 'tcp://172.23.2.1:54321'. Required for --distributed_dataparallel\")\n\n args = parser.parse_args()\n\n if args.fp16 and args.amp_opt_level:\n print (\"ERROR: Cannot use both --fp16 and --amp-opt-level\")\n sys.exit(1)\n if args.amp_opt_level and not HAVE_APEX:\n print (\"ERROR: You must install apex to use --amp-opt-level\")\n sys.exit(1)\n\n main()\n","sub_path":"FlopsProfile/flops_train_vision.py","file_name":"flops_train_vision.py","file_ext":"py","file_size_in_byte":16411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"401320390","text":"\"\"\"\nMethods for testing Operation Types in a Docker container\n\"\"\"\n\nimport json as j\nimport os\nimport subprocess\nfrom pydent import AqSession\n\n\ndef get_records(session, protocol, records, record_names):\n \"\"\"\n Generates a dictionary of all new records by their tag\n\n :param session: session with container\n :type session: AqSession\n :param protocol: directory that manages the protocol\n :type protocol: ODir\n :return: dictionary of all records by tag\n :rtype: dict\n \"\"\"\n record_dict = {}\n\n for model_string in record_names:\n for record_info in records[model_string]:\n if 'data' in record_info:\n data = record_info['data']\n else:\n with protocol.open_file(record_info['source'], mode='r') as f:\n data = j.load(f)\n\n # Format data with tags\n new_data = format_data(data, record_dict)\n\n if model_string == \"operation_types\":\n for ft in new_data['field_types']:\n ft['allowable_field_types'] = [\n format_data(aft, record_dict)\n for aft in ft['allowable_field_types']\n ]\n\n # Make records with Trident\n new_record = make_record(\n session, protocol.name, model_string, new_data, record_dict)\n\n record_dict[record_info['tag']] = new_record\n\n return record_dict\n\n\ndef format_data(data, record_dict):\n \"\"\"\n Replaces tags in given data with corresponding record ids\n\n :param data: raw data for a given record\n :type data: dict\n :param record_dict: dictionary of all records by tag\n :type record_dict: dict\n :return: formatted data\n :rtype: dict\n \"\"\"\n new_data = {}\n for attr in data:\n tag = data[attr]\n if type(tag) is str and tag in record_dict:\n record_id = record_dict[tag].id\n new_data[attr[:-4] + '_id'] = record_id\n else:\n new_data[attr] = data[attr]\n\n return new_data\n\n\ndef make_record(session, name, model_string, data, record_dict):\n \"\"\"\n Makes a new record of the given model (or loads an existing one\n if applicable)\n\n :param session: session with container\n :type session: AqSession\n :param name: name of the :class:`OperationType`\n :type name: str\n :param model_string: name of the model\n :type model_string: str\n :param data: formatted data for given record\n :type data: dict\n :param record_dict: dictionary of all records by tag\n :type record_dict: dict\n :return: record made from data\n :rtype: ModelBase\n \"\"\"\n model_name = model_string[:-1]\n record = None\n\n if model_name == \"sample_type\":\n record = session.SampleType.load(data)\n record.save()\n elif model_name == \"object_type\":\n record = session.ObjectType.load(data)\n record.save()\n elif model_name == \"sample\":\n try:\n record = session.Sample.load(data)\n record.save()\n except Exception:\n record = session.Sample.find_by_name(data['name'])\n elif model_name == \"item\":\n record = session.Item.load(data)\n record.make()\n elif model_name == \"operation\":\n ot = record_dict['ot']\n record = ot.instance()\n record.x = record.y = record.parent_id = record.parent = 0\n\n for in_data in data['inputs']:\n name = in_data['name']\n sample = record_dict[in_data['sample_tag']]\n item = record_dict[in_data['item_tag']]\n record.set_input(name, sample=sample, item=item)\n\n for out_data in data['outputs']:\n name = out_data['name']\n sample = record_dict[out_data['sample_tag']]\n record.set_output(name, sample=sample)\n elif model_name == \"operation_type\":\n # data['name'] = 'hullabaloo25'\n record = session.OperationType.load(data)\n try:\n record.save()\n except Exception:\n # Trident errors even though Operation Type is successfully created\n # TODO Handle creating Operation Types (and Field Types and\n # Allowable Field Types) more cleanly (e.g., many problems\n # arise from the fact that we can't 'reload' the OT record\n # upon creating it on a server; 'id's are incorrect).\n record = session.OperationType.find_by_name(record.name)\n\n else:\n raise Exception(\n 'Malformed data: {} is not a valid model name'.format(model_name))\n\n return record\n\n\ndef test_protocol(protocol, record_dict):\n \"\"\"\n Submits a plan to container given test data\n\n :param session: session with container\n :type session: AqSession\n :param protocol: directory that manages the protocol\n :type protocol: ODir\n :param record_dict: dictionary of all records by tag\n :type record_dict: dict\n :return: plan information (success status and errors)\n :rtype: dict\n \"\"\"\n # GET THINE SESSION\n session = record_dict['ot'].session\n\n # READ THAT JSON\n test_data = None\n with protocol.open_file('testing/data.json', mode='r') as f:\n test_data = j.load(f)\n\n # SUBMIT THAT PLAN\n plan = session.Plan.load({\n 'name': '{} Test'.format(protocol.name),\n 'layout': {'wires': None}})\n for op_tag in test_data['plan']['operations']:\n op = record_dict[op_tag]\n plan.add_operation(op)\n\n plan.create()\n plan.estimate_cost()\n plan.validate()\n\n plan.submit(session.current_user, session.current_user.budgets[0])\n\n # DEBUG THAT PLAN\n session.utils.batch_operations(\n {'operation_ids': [op.id for op in plan.operations]})\n op = plan.operations[0]\n job = op.jobs[0]\n try:\n session.utils.job_debug(job.id)\n except Exception:\n pass\n\n # return result\n op.reload(session.Operation.find(op.id))\n\n return {\n 'success': op.status == 'done',\n 'plan_url': '{}launcher?plan_id={}'.format(session.url, plan.id)\n }\n\n\ndef load_data(protocol):\n \"\"\"\n Open a session with running container\n\n :param protocol: directory that manages the protocol\n :type protocol: ODir\n :return: dictionary of all records by tag\n :rtype: dict\n \"\"\"\n # OPEN A SESSION\n session = AqSession('neptune', 'aquarium', 'http://localhost:3001/')\n\n # READ THAT JSON\n # protocol = environment.get_protocol_dir(cat_name, prot_name)\n test_data = None\n with protocol.open_file('testing/data.json', mode='r') as f:\n test_data = j.load(f)\n\n # GET THOSE RECORDS\n record_names = [\n 'sample_types',\n 'object_types',\n 'operation_types',\n 'samples',\n 'items',\n 'operations'\n ]\n record_dict = get_records(\n session, protocol, test_data['records'], record_names)\n\n return record_dict\n\n\ndef start_container(reset, cid):\n \"\"\"\n Start a Docker container\n\n :param reset: kill the running container if one exists\n :type reset: bool\n :return: whether a new container was started\n :rtype: bool\n \"\"\"\n # CHECK IF DOCKER CONTAINER IS RUNNING ALREADY\n if cid == '':\n running = False\n else:\n command = 'sudo docker ps -aq'\n check_running = subprocess.Popen(\n command.split(), stdout=subprocess.PIPE)\n output, error = check_running.communicate()\n running_ids = [rid.decode('utf-8') for rid in output.split(b'\\n')]\n\n running = cid in running_ids\n if not running:\n cid = ''\n\n if reset or not running:\n # RUN THIS DOCKER CONTAINER\n print('Starting Aquarium container...')\n here = os.path.abspath(os.path.dirname(__file__))\n start = subprocess.Popen([\n 'bash',\n '{}/docker_container.sh'.format(here),\n 'run',\n str(cid)\n ], stdout=subprocess.PIPE)\n output, error = start.communicate()\n cid = output.split(b'\\n')[-2].decode('utf-8')\n\n return {\n 'success': True,\n 'id': cid\n }\n\n return {\n 'success': False,\n 'id': cid\n }\n\n\ndef stop_container(cid):\n \"\"\" Stop a Docker container \"\"\"\n # KILL THIS DOCKER CONTAINER\n here = os.path.abspath(os.path.dirname(__file__))\n subprocess.call([\n 'bash',\n '{}/docker_container.sh'.format(here),\n 'kill',\n cid,\n ])\n","sub_path":"parrotfish/utils/docker_testing.py","file_name":"docker_testing.py","file_ext":"py","file_size_in_byte":8423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"66375502","text":"# Copyright(c) 2020 Jake Fowler\n#\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use, \n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, \n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, \n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n\nimport pandas as pd\nfrom datetime import datetime\nimport clr\nimport System as dotnet\nfrom pathlib import Path\nclr.AddReference(str(Path(\"cmdty_storage/lib/Cmdty.TimePeriodValueTypes\")))\nimport Cmdty.TimePeriodValueTypes as tp\nclr.AddReference(str(Path('cmdty_storage/lib/Cmdty.TimeSeries')))\nimport Cmdty.TimeSeries as ts\nfrom typing import Union\nfrom datetime import date\n\n\ndef from_datetime_like(datetime_like, time_period_type):\n \"\"\" Converts either a pandas Period, datetime or date to a .NET Time Period\"\"\"\n if (hasattr(datetime_like, 'hour')):\n time_args = (datetime_like.hour, datetime_like.minute, datetime_like.second)\n else:\n time_args = (0, 0, 0)\n\n date_time = dotnet.DateTime(datetime_like.year, datetime_like.month, datetime_like.day, *time_args)\n return tp.TimePeriodFactory.FromDateTime[time_period_type](date_time)\n\n\ndef net_datetime_to_py_datetime(net_datetime):\n return datetime(net_datetime.Year, net_datetime.Month, net_datetime.Day, net_datetime.Hour, net_datetime.Minute, net_datetime.Second, net_datetime.Millisecond * 1000)\n\n\ndef net_time_period_to_pandas_period(net_time_period, freq):\n start_datetime = net_datetime_to_py_datetime(net_time_period.Start)\n return pd.Period(start_datetime, freq=freq)\n\n\ndef series_to_double_time_series(series, time_period_type):\n \"\"\"Converts an instance of pandas Series to a Cmdty.TimeSeries.TimeSeries type with Double data type.\"\"\"\n return series_to_time_series(series, time_period_type, dotnet.Double, lambda x: x)\n\n\ndef series_to_time_series(series, time_period_type, net_data_type, data_selector):\n \"\"\"Converts an instance of pandas Series to a Cmdty.TimeSeries.TimeSeries.\"\"\"\n series_len = len(series)\n net_indices = dotnet.Array.CreateInstance(time_period_type, series_len)\n net_values = dotnet.Array.CreateInstance(net_data_type, series_len)\n\n for i in range(series_len):\n net_indices[i] = from_datetime_like(series.index[i], time_period_type)\n net_values[i] = data_selector(series.values[i])\n\n return ts.TimeSeries[time_period_type, net_data_type](net_indices, net_values)\n\n\ndef net_time_series_to_pandas_series(net_time_series, freq):\n \"\"\"Converts an instance of class Cmdty.TimeSeries.TimeSeries to a pandas Series\"\"\"\n curve_start = net_time_series.Indices[0].Start\n curve_start_datetime = net_datetime_to_py_datetime(curve_start)\n index = pd.period_range(start=curve_start_datetime, freq=freq, periods=net_time_series.Count)\n prices = [net_time_series.Data[idx] for idx in range(0, net_time_series.Count)]\n return pd.Series(prices, index)\n\n\ndef is_scalar(arg):\n return isinstance(arg, int) or isinstance(arg, float)\n\n\ndef raise_if_none(arg, error_message):\n if arg is None:\n raise ValueError(error_message)\n\n\ndef raise_if_not_none(arg, error_message):\n if arg is not None:\n raise ValueError(error_message)\n\n\nFREQ_TO_PERIOD_TYPE = {\n \"15min\" : tp.QuarterHour,\n \"30min\" : tp.HalfHour,\n \"H\" : tp.Hour,\n \"D\" : tp.Day,\n \"M\" : tp.Month,\n \"Q\" : tp.Quarter\n }\n\"\"\" dict of str: .NET time period type.\nEach item describes an allowable granularity of curves constructed, as specified by the \nfreq parameter in the curves public methods.\n\nThe keys represent the pandas Offset Alias which describe the granularity, and will generally be used\n as the freq of the pandas Series objects returned by the curve construction methods.\nThe values are the associated .NET time period types used in behind-the-scenes calculations.\n\"\"\"\n\ndef wrap_settle_for_dotnet(py_settle_func, freq):\n\n def wrapper_settle_function(py_function, net_time_period, freq):\n pandas_period = net_time_period_to_pandas_period(net_time_period, freq)\n py_function_result = py_function(pandas_period)\n net_settle_day = from_datetime_like(py_function_result, tp.Day)\n return net_settle_day\n\n def wrapped_function(net_time_period):\n return wrapper_settle_function(py_settle_func, net_time_period, freq)\n\n time_period_type = FREQ_TO_PERIOD_TYPE[freq]\n return dotnet.Func[time_period_type, tp.Day](wrapped_function)\n\n\nTimePeriodSpecType = Union[datetime, date, pd.Period]","sub_path":"src/Cmdty.Storage.Python/cmdty_storage/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"649912177","text":"\"\"\"\nFaça programa que leia idade de 7 pessoas e mostre quantas tem > 21 anos e quantas são menores\n\"\"\"\n\npessoas = ('primeira','segunda','terceira','quarta', 'quinta','sexta', 'última')\n\nsoma = 0\nfor c in range(0,7):\n i = int(input(\"Digite a idade da {} pessoa: \".format(pessoas[c])))\n if i >= 21:\n soma +=1\n\nprint(\"O número de pessoas com mais de 21 anos é {}, e o números de pessoas com idade menor de 21 é {}\".format(soma, 7 - soma))","sub_path":"Arquivos Exercicios/Exercicios/Ex054.py","file_name":"Ex054.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"262590225","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 19 13:58:55 2018\n\n@author: david.saltiel\n\"\"\"\n\n''' \n All the import for this file\n'''\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.feature_selection import RFE\n#from sklearn.ensemble import RandomForestClassifier\nfrom functions import compute_accuracy_score\nimport pickle\nfrom xgboost import XGBClassifier\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\n#%%\n'''\n Generic RFEMEthod for feature selection\n'''\nclass RFEMethod:\n '''\n df an objec that contains a dataframe contained in df.df \n the method uses the RFE method from sklearn\n to compute RFE for the df\n '''\n def __init__(self, df, verbose = False):\n self.df = df\n self.verbose = verbose\n\n '''\n get score and feature for a given number of features\n using the RFE method from sklearn\n '''\n def get_score_and_features(self, n_features, split = 'temporal'):\n features = list(self.df.columns.values)\n features.remove('Label')\n \n df_X = self.df[features]\n df_Y = self.df['Label']\n estimator = XGBClassifier(random_state=0)\n \n if split == 'temporal' :\n split_data = int(0.67*df_X.shape[0])\n x_train, x_test, y_train, y_test = df_X.iloc[:split_data,:], df_X.iloc[split_data:,:],\\\n df_Y.iloc[:split_data], df_Y.iloc[split_data:]\n else :\n x_train, x_test, y_train, y_test = train_test_split(df_X, df_Y, test_size=0.33,\n random_state = 0)\n \n selector = RFE(estimator, n_features, step=1)\n selector = selector.fit(x_train, y_train)\n \n features_bool = np.array(selector.support_)\n features = np.array(df_X.columns)\n list_feat = list(features[features_bool])\n# list_to_keep = []\n# for i in range(len(list(selector.support_))):\n# \tif list(selector.support_)[i] :\n# \t\tlist_to_keep.append(i)\n# list_feat = list(df_X.columns[list_to_keep])\n# list_delete = list(set(list(df_X.columns.values))-set(df_X.columns[list_to_keep]))\n# x_test = x_test.drop(list_delete ,axis=1)\n \n# clf_xgb = XGBClassifier(random_state=0)\n# clf_xgb = clf_xgb.fit(x_train , y_train)\n \n score = selector.score(x_test,y_test)\n# score = compute_accuracy_score(x_test, y_test)\n self.selected_features = list_feat\n self.list_score = score\n return self.selected_features, self.list_score\n \n \n '''\n loop over all features between nMin\n and nMax and generate the corresponding score\n if save_pickle == True, we also save as \n a pickle the result\n '''\n def save_all_score(self, nMin = 1, nMax = 20, save_pickle = False):\n dic_score_RFE ={}\n for n_features in range(nMin, nMax):\n list_feat, score = self.get_score_and_features(n_features)\n dic_score_RFE[n_features] = [list_feat, score]\n if self.verbose :\n print('n_features : {0} score : {1}'.format(n_features, score))\n if save_pickle:\n pickle.dump( dic_score_RFE, open( \"dic_score_RFE_v2.p\", \"wb\" ) )\n return dic_score_RFE\n\n ''' \n select features \n return the subset of initial features kept by the method\n \n '''\n def select_features(self, n_features= 6):\n return self.get_score_and_features(n_features)\n","sub_path":"code/RFE.py","file_name":"RFE.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"595871102","text":"import numpy as np\nimport cv2\n\n# Identify pixels above the threshold\n# Threshold of RGB > 160 does a nice job of identifying ground pixels only\ndef color_thresh(img, rgb_thresh=(160, 160, 160), rock_min = (0, 0, 145), rock_max = (255, 148, 180)):\n # Create an array of zeros same xy size as img, but single channel\n path_select = np.zeros_like(img[:,:,0])\n obs_select = np.zeros_like(img[:,:,0])\n rock_select = np.zeros_like(img[:,:,0])\n # Require that each pixel be above all three threshold values in RGB\n # above_thresh will now contain a boolean array with \"True\"\n # where threshold was met\n above_thresh = (img[:,:,0] > rgb_thresh[0]) \\\n & (img[:,:,1] > rgb_thresh[1]) \\\n & (img[:,:,2] > rgb_thresh[2])\n below_thresh = (img[:,:,0] <= rgb_thresh[0]) \\\n & (img[:,:,1] <= rgb_thresh[1]) \\\n & (img[:,:,2] <= rgb_thresh[2])\n inbetween_thresh = (img[:,:,0] >= rock_min[0]) \\\n & (img[:,:,1] >= rock_min[1]) \\\n & (img[:,:,2] >= rock_min[2]) \\\n & (img[:,:,0] < rock_max[0]) \\\n & (img[:,:,1] < rock_max[1]) \\\n & (img[:,:,2] < rock_max[2])\n # Index the array of zeros with the boolean array and set to 1\n path_select[above_thresh] = 1\n obs_select[below_thresh] = 1\n rock_select[inbetween_thresh] = 1\n # Return the binary image\n return path_select, obs_select, rock_select\n\n# Define a function to convert from image coords to rover coords\ndef rover_coords(binary_img):\n # Identify nonzero pixels\n ypos, xpos = binary_img.nonzero()\n # Calculate pixel positions with reference to the rover position being at the \n # center bottom of the image. \n x_pixel = -(ypos - binary_img.shape[0]).astype(np.float)\n y_pixel = -(xpos - binary_img.shape[1]/2 ).astype(np.float)\n return x_pixel, y_pixel\n\n\n# Define a function to convert to radial coords in rover space\ndef to_polar_coords(x_pixel, y_pixel):\n # Convert (x_pixel, y_pixel) to (distance, angle) \n # in polar coordinates in rover space\n # Calculate distance to each pixel\n dist = np.sqrt(x_pixel**2 + y_pixel**2)\n # Calculate angle away from vertical for each pixel\n angles = np.arctan2(y_pixel, x_pixel)\n return dist, angles\n\n# Define a function to map rover space pixels to world space\ndef rotate_pix(xpix, ypix, yaw):\n # Convert yaw to radians\n yaw_rad = yaw * np.pi / 180\n xpix_rotated = (xpix * np.cos(yaw_rad)) - (ypix * np.sin(yaw_rad))\n \n ypix_rotated = (xpix * np.sin(yaw_rad)) + (ypix * np.cos(yaw_rad))\n # Return the result \n return xpix_rotated, ypix_rotated\n\ndef translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale): \n # Apply a scaling and a translation\n xpix_translated = (xpix_rot / scale) + xpos\n ypix_translated = (ypix_rot / scale) + ypos\n # Return the result \n return xpix_translated, ypix_translated\n\n\n# Define a function to apply rotation and translation (and clipping)\n# Once you define the two functions above this function should work\ndef pix_to_world(xpix, ypix, xpos, ypos, yaw, world_size, scale):\n # Apply rotation\n xpix_rot, ypix_rot = rotate_pix(xpix, ypix, yaw)\n # Apply translation\n xpix_tran, ypix_tran = translate_pix(xpix_rot, ypix_rot, xpos, ypos, scale)\n # Perform rotation, translation and clipping all at once\n x_pix_world = np.clip(np.int_(xpix_tran), 0, world_size - 1)\n y_pix_world = np.clip(np.int_(ypix_tran), 0, world_size - 1)\n # Return the result\n return x_pix_world, y_pix_world\n\n# Define a function to perform a perspective transform\ndef perspect_transform(img, src, dst):\n \n M = cv2.getPerspectiveTransform(src, dst)\n warped = cv2.warpPerspective(img, M, (img.shape[1], img.shape[0]))# keep same size as input image\n \n return warped\n\n\n# Apply the above functions in succession and update the Rover state accordingly\ndef perception_step(Rover):\n # Perform perception steps to update Rover()\n # TODO: \n # NOTE: camera image is coming to you in Rover.img\n # 1) Define source and destination points for perspective transform\n dst_size = 5\n bottom_offset = 6\n source = np.float32([[14, 140], [301 ,140],[200, 96], [118, 96]])\n destination = np.float32([[Rover.img.shape[1]/2 - dst_size, Rover.img.shape[0] - bottom_offset],\n [Rover.img.shape[1]/2 + dst_size, Rover.img.shape[0] - bottom_offset],\n [Rover.img.shape[1]/2 + dst_size, Rover.img.shape[0] - 2*dst_size - bottom_offset], \n [Rover.img.shape[1]/2 - dst_size, Rover.img.shape[0] - 2*dst_size - bottom_offset],\n ])\n\n # 2) Apply perspective transform\n warped = perspect_transform(Rover.img, source, destination)\n\n # 3) Apply color threshold to identify navigable terrain/obstacles/rock samples\n threshed = color_thresh(warped)\n\n # 4) Update Rover.vision_image (this will be displayed on left side of screen)\n # Example: Rover.vision_image[:,:,0] = obstacle color-thresholded binary image\n # Rover.vision_image[:,:,1] = rock_sample color-thresholded binary image\n # Rover.vision_image[:,:,2] = navigable terrain color-thresholded binary image\n Rover.vision_image[:,:,0] = threshed[1]\n Rover.vision_image[:,:,1] = threshed[2]\n Rover.vision_image[:,:,2] = threshed[0]\n\n # 5) Convert map image pixel values to rover-centric coords\n x_path_rover, y_path_rover = rover_coords(threshed[0])\n x_obs_rover, y_obs_rover = rover_coords(threshed[1])\n x_rock_rover, y_rock_rover = rover_coords(threshed[2])\n\n # 6) Convert rover-centric pixel values to world coordinates\n xpos, ypos = Rover.pos\n yaw = Rover.yaw\n world_size = Rover.worldmap.shape[0]\n scale = 2 * dst_size\n x_path_world, y_path_world = pix_to_world(x_path_rover, y_path_rover, xpos, ypos, yaw, world_size, scale)\n x_obs_world, y_obs_world = pix_to_world(x_obs_rover, y_obs_rover, xpos, ypos, yaw, world_size, scale)\n x_rock_world, y_rock_world = pix_to_world(x_rock_rover, y_rock_rover, xpos, ypos, yaw, world_size, scale)\n # 7) Update Rover worldmap (to be displayed on right side of screen)\n # Example: Rover.worldmap[obstacle_y_world, obstacle_x_world, 0] += 1\n # Rover.worldmap[rock_y_world, rock_x_world, 1] += 1\n # Rover.worldmap[navigable_y_world, navigable_x_world, 2] += 1\n roll_max = 359.5\n roll_min = 0.5\n pitch_max = 359.5\n pitch_min = 0.5\n if ((Rover.roll > roll_max or Rover.roll < roll_min) and (Rover.pitch > pitch_max \\\n or Rover.pitch < pitch_min)):\n Rover.worldmap[y_obs_world, x_obs_world, 0] += 1\n Rover.worldmap[y_rock_world, x_rock_world, 1] += 1\n Rover.worldmap[y_path_world, x_path_world, 2] += 1\n\n # 8) Convert rover-centric pixel positions to polar coordinates\n # Update Rover pixel distances and angles\n # Rover.nav_dists = rover_centric_pixel_distances\n # Rover.nav_angles = rover_centric_angles\n dist, angles = to_polar_coords(x_path_rover, y_path_rover)\n Rover.nav_dists = dist\n Rover.nav_angles = angles\n \n return Rover","sub_path":"code/perception.py","file_name":"perception.py","file_ext":"py","file_size_in_byte":7250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"555516271","text":"#! /usr/local/bin/python\n\nfrom rtcmix import *\nimport random\nfrom DNAFuncs import *\nimport words\nimport sys\n\nrtsetparams(44100, 2)\nload(\"GRANULATE\")\n\ntransTab = [\n\t\t\t[0.00, 0.03, 0.07, 0.10],\n\t\t\t[0.00, 0.04, 0.07, 0.10],\n\t\t\t[0.00, 0.02, 0.07, 0.10],\n\t\t\t[0.00, 0.05, 0.10, 1.02]\n\t\t\t]\n\ndur = int(sys.argv[1])\n\ndef grainAmp():\n\tx = random.uniform(0.125, 0.5)\n\ty = random.uniform(0.25, 0.75)\n\tif x > y:\n\t\treturn y, x\n\telse:\n\t\treturn x, y\n\ninskip = 0\namp = 1\nenv = maketable(\"curve\", 1000, 0,0,2, 150,1,0, 850,1,2, 1000,0)\ncurrent = random.choice(words.words)\nfile = current[1]\nrtinput(file)\ninTab = maketable(\"soundfile\", \"nonorm\", 0, file)\ninChan = 0\nwinStart = 0.0\nwinEnd = DUR() - 0.0\ntravRate = random.uniform(0.001, 0.1)\ngrainTab = maketable(\"window\", 1000, \"hanning\")\nhopTime = random.uniform(0.001, 0.009)\ninJit = outJit = 0.0025\ngrainMin = hopTime * random.uniform(11, 33)\ngrainMax = grainMin * random.uniform(0.1, 0.5)\ngrainAmpMin, grainAmpMax = grainAmp()\ngrainTrans = random.uniform(-0.02, 0.02)\n#print file, grainTrans, hopTime, grainMin, grainMax, grainTrans\ntransColl = random.choice(transTab)\n\nGRANULATE(0, inskip, dur, amp * env, inTab, 1, inChan, winStart, winEnd, 1, travRate,\n\t\t grainTab, hopTime, inJit, outJit, grainMin, grainMax, grainAmpMax, grainAmpMin,\n\t\t grainTrans, transColl, 0.005, 1, 0, 1, 1)","sub_path":"acidPlay.py","file_name":"acidPlay.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"186163729","text":"#!/usr/bin/env python\nfrom error.error import *\nfrom cmdPush.Interface import Interface\nfrom setIP.SetIP import setip\nfrom pushConf.PushConf import pushconf\nfrom pushConf.PushCF import pushconf_cf\nfrom check.check import CheckList\nfrom GetLoad.GetMinLoad import hostload\nfrom GetLoad.FromRedis import getloadpay\nfrom conf_analytic.lvs_auto import confanal\nfrom gevent.pywsgi import WSGIServer\nfrom Online.Online import onlinepay\nfrom Offline.Offline import offlinepay\nfrom append.FileExist import filecheck\n\nimport traceback\nimport logging\nimport json\n\nLOG = logging.getLogger(\"lvsauto\")\n\ndef application(env, start_response):\n\twhile True:\n\t\ttry:\n\t\t\treq_body_size = int(env['CONTENT_LENGTH'])\n\t\t\tgetinput = env['wsgi.input'].read(req_body_size)\n\t\t\tgetinput = json.loads(getinput)\n\t\t\tLOG.info(\"Get payload:%s, path info:%s\" % (getinput, env['PATH_INFO']))\n\t\t\tif 'setip' in env['PATH_INFO']:\n\t\t\t\tstatus, reason = setip(getinput)\n\t\t\telif 'pushconf' in env['PATH_INFO']:\n\t\t\t\tif getinput['option'] in ['vip', 'member', 'cluster']:\n\t\t\t\t\tstatus, reason = pushconf(getinput)\n\t\t\t\telif getinput['option'] in ['vip_cf', 'member_cf']:\n\t\t\t\t\tstatus, reason = pushconf_cf(getinput)\n\t\t\telif 'getload' in env['PATH_INFO']:\n\t\t\t\tstatus, reason = hostload(getinput)\n\t\t\telif 'confanal' in env['PATH_INFO']:\n\t\t\t\tstatus, reason = confanal(getinput)\n\t\t\telif 'cluster/online' in env['PATH_INFO']:\n\t\t\t\tstatus, reason = onlinepay(getinput)\n\t\t\telif '/cluster/offline' in env['PATH_INFO']:\n\t\t\t\tstatus, reason = offlinepay(getinput)\n\t\t\telif '/load/min' in env['PATH_INFO']:\n\t\t\t\tstatus, reason = getloadpay(getinput)\n\t\t\telif '/cluster/fileexist' in env['PATH_INFO']:\n\t\t\t\tstatus, reason = filecheck(getinput)\n\t\t\telse:\n\t\t\t\tstatus, reason = 500, \"Internal server error.\"\n\t\t\tLOG.info(\"%s\" % (reason))\n\t\texcept:\n\t\t\tstart_response(\"500\", [('Content-Type','text/json')])\n\t\t\tLOG.error(\"%s\" % (traceback.format_exc()))\n\t\t\treturn json.dumps({\"status\":\"failed\",\"reason\":\"Internal server error.\"})\n\n\t\tstart_response(str(status),[('Content-Type','text/json')])\n\t\tif type(reason) is dict:\n\t\t\treturn json.dumps(reason)\n\t\telif type(reason) is str or type(reason) is unicode:\n\t\t\tif status == 200:\n\t\t\t\treturn json.dumps({\"status\":\"succ\",\"reason\":reason})\n\t\t\telse:\n\t\t\t\treturn json.dumps({\"status\":\"failed\", \"reason\":reason})\n\nif __name__ == '__main__':\n\tWSGIServer(('', 33999), application).serve_forever()\n","sub_path":"lavos.py","file_name":"lavos.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"649985918","text":"import re\nimport os\nimport shutil\nimport random\nimport time\nfrom captcha.image import ImageCaptcha\nfrom config import CHAR_SET, CAPTCHA_LEN, CAPTCHA_IMAGE_DIR, TEST_IMAGE_DIR,\\\n TEST_IMAGE_NUMBER\n\n\n# 生成验证码图片\ndef generate_captcha_image(\n char_set=CHAR_SET, img_path=CAPTCHA_IMAGE_DIR):\n k = 0\n total = 1\n for i in range(CAPTCHA_LEN):\n total *= len(char_set)\n\n for i in range(len(char_set)):\n for j in range(len(char_set)):\n for m in range(len(char_set)):\n for n in range(len(char_set)):\n captcha_text = char_set[i] + char_set[j] + char_set[m] +\\\n char_set[n]\n image = ImageCaptcha()\n image.write(\n captcha_text, format_img_path(img_path, captcha_text))\n k += 1\n print(\"\\rCreating %d/%d\" % (k, total))\n\n\n# 从验证码的图片集中取出一部分作为测试集,这些图片不参加训练,只用于模型的测试\ndef prepare_test_set():\n file_name_list = []\n for filePath in os.listdir(CAPTCHA_IMAGE_DIR):\n captcha_name = filePath.split('/')[-1]\n captcha_name = re.sub(r'\\.jpg$', '', captcha_name)\n file_name_list.append(captcha_name)\n random.seed(time.time())\n random.shuffle(file_name_list)\n for i in range(TEST_IMAGE_NUMBER):\n name = file_name_list[i]\n shutil.move(\n format_img_path(CAPTCHA_IMAGE_DIR, name),\n format_img_path(TEST_IMAGE_DIR, name))\n\n\ndef format_img_path(img_dir, img_name):\n return '{}/{}.jpg'.format(img_dir, img_name)\n\n\nif __name__ == '__main__':\n generate_captcha_image(CHAR_SET, CAPTCHA_IMAGE_DIR)\n prepare_test_set()\n print(\"\\nFinished\")\n","sub_path":"generate_sample.py","file_name":"generate_sample.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"505697578","text":"#!/usr/bin/env python3\n\n\"\"\"\nThe objective of this project is to understand, implement, \nand empirically measure the performance of two space allocation methods\nused in file systems, namely contiguous and linked allocation, against various inputs.\n\"\"\"\n\n__author__ = \"Firat Tamur\"\n__email__ = \"ftamur16@ku.edu.tr\"\n\n\nclass FAT:\n\n def __init__(self, block_size, block_count=32768, fat_entry_size=4):\n \"\"\"\n Initializes File Allocation Table.\n\n :param block_count: int\n :param block_size: int\n :param fat_entry_size: int\n \"\"\"\n self.block_count = block_count\n self.block_size = block_size\n self.fat_entry_size = fat_entry_size\n\n # create a list for files:\n # 0: not allocated\n # -1: end of file chain\n self.blocks = [0] * block_count\n\n # create a dict to keep each file_id and starting block\n # allocated space for fat starts from block 0.\n self.fat = {'fat': 0}\n\n # allocate blocks for fat\n self.fat_blocks = int(self.block_count / ((self.block_size / 4) + 1)) + 1\n\n # From 0 to (fat_blocks - 1) allocated to fat.\n # We can start from index fat_blocks to allocate\n # new files.\n for i in range(self.fat_blocks - 1):\n self.blocks[i] = i + 1\n\n self.blocks[self.fat_blocks - 1] = -1\n\n # set capacity which is block_count - fat_blocks\n self.capacity = block_count - self.fat_blocks\n\n # set size\n self.size = 0\n\n def create_file(self, file_id, file_length):\n \"\"\"\n Allocates blocks in self.blocks to given file_id\n Also updates fat dict.\n\n :param file_id: int\n :param file_length: int -> bytes\n\n :return: False -> failure, True -> success\n \"\"\"\n\n if file_id in self.fat.keys():\n # print(\"File already created!\")\n return False\n\n if file_length < 0:\n # print(\"Length value must be positive integer!\")\n return False\n\n # bytes to blocks\n block_count = self._byte_to_block(file_length)\n\n if self.capacity < block_count:\n # print(\"Not Enough Space!\")\n return False\n\n for i in range(self.fat_blocks, self.block_count):\n if self.blocks[i] == 0:\n\n # set fat initial file to fat_blocks\n self.fat[file_id] = i\n\n # search block after start point and allocate them.\n self._allocate_fat(i, i + 1, block_count)\n\n break\n\n\n self.capacity -= block_count\n self.size += block_count\n\n return True\n\n def access(self, file_id, byte_offset):\n \"\"\"\n Accesses file with given byte_offset.\n\n :param file_id: int\n :param byte_offset: int -> bytes\n\n :return: int\n \"\"\"\n\n if file_id not in self.fat.keys():\n # print(\"File doesn't exist!\")\n return False\n\n if byte_offset < 0:\n # print(\"Offset value must be positive integer!\")\n return False\n\n # bytes to block\n block_offset = self._byte_to_block(byte_offset)\n\n # start index\n start = self.fat[file_id]\n\n for i in range(block_offset - 1):\n start = self.blocks[start]\n\n return start\n\n def extend(self, file_id, extension):\n \"\"\"\n Extends file with given file_id.\n\n :param file_id: int\n :param extension: int -> blocks\n\n :return: False -> failure, True -> success\n \"\"\"\n\n if file_id not in self.fat.keys():\n # print(\"File doesn't exist!\")\n return False\n\n if extension < 0:\n # print(\"Extension value must be positive integer!\")\n return False\n\n if self.capacity < extension:\n # print(\"Not Enough Space!\")\n return False\n\n end = self.fat[file_id]\n\n while True:\n if self.blocks[end] == -1:\n break\n\n end = self.blocks[end]\n\n self._allocate_fat(end, self.fat_blocks, extension + 1)\n\n self.capacity -= extension\n self.size += extension\n\n return True\n\n def shrink(self, file_id, shrinking):\n \"\"\"\n Shrinks file with given file_id.\n\n :param file_id: int\n :param shrinking: int -> blocks\n\n :return: False -> failure, True -> success\n \"\"\"\n\n if file_id not in self.fat.keys():\n #print(\"File doesn't exist!\")\n return False\n\n if shrinking < 0:\n #print(\"Shrink value must be positive integer!\")\n return False\n\n file_size = self._find_size(file_id)\n\n if file_size - shrinking < 1:\n #print(\"Too large shrink value!\")\n return False\n\n delete_starts = 0\n end = self.fat[file_id]\n\n while True:\n delete_starts += 1\n\n if delete_starts >= file_size - shrinking:\n delete = end\n end = self.blocks[end]\n\n if delete_starts == file_size - shrinking:\n self.blocks[delete] = -1\n else:\n self.blocks[delete] = 0\n\n if self.blocks[end] == -1:\n self.blocks[end] = 0\n break\n else:\n end = self.blocks[end]\n\n self.capacity += shrinking\n self.size -= shrinking\n\n return True\n\n \"\"\" Utils \"\"\"\n\n def _find_size(self, file_id):\n \"\"\"\n Find file size of given file_id.\n\n :param file_id: int\n :return: int -> blocks\n \"\"\"\n\n file_size = 0\n\n end = self.fat[file_id]\n\n while end != -1:\n file_size += 1\n end = self.blocks[end]\n\n return file_size\n\n def _allocate_fat(self, end_index, search_starts, blocks):\n \"\"\"\n Allocates space for given file_index.\n Searches empty blocks starting from start index and blocks count.\n\n :param end_index: int\n :param search_starts: int\n :param blocks: int\n\n :return: None\n \"\"\"\n\n for i in range(search_starts, self.block_count):\n\n if self.blocks[i] == 0:\n\n if blocks == 1:\n self.blocks[end_index] = -1\n break\n\n self.blocks[end_index] = i\n end_index = i\n\n blocks -= 1\n\n if blocks == 1:\n self.blocks[end_index] = -1\n\n def _byte_to_block(self, bytes_count):\n \"\"\"\n Returns givens bytes count to blocks count.\n\n :param bytes_count: int\n :return: blocks: int\n \"\"\"\n\n if bytes_count % self.block_size == 0:\n blocks = bytes_count // self.block_size\n else:\n blocks = (bytes_count // self.block_size) + 1\n\n return blocks\n\n\n\n\n\n\n\n","sub_path":"fat.py","file_name":"fat.py","file_ext":"py","file_size_in_byte":6877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"443242906","text":"import numpy as np\n\n\ndef insert_global_vars(vars):\n global img, img_sample\n global overlap, patch_sz\n global sample_height, sample_width\n img, img_sample = vars.get('img'), vars.get('img_sample')\n sample_height, sample_width = vars.get('sample_height'), vars.get('sample_width')\n overlap, patch_sz = vars.get('OverlapWidth'), vars.get('PatchSize')\n\n\n# ------------------------------------ #\n# Best Fit Patch and related functions #\n# ------------------------------------ #\ndef overlap_error_vertical(img_px, sample_px):\n iLeft, jLeft = img_px\n iRight, jRight = sample_px\n img_int = img.astype(np.int32)\n img_sample_int = img_sample.astype(np.int32)\n\n diff = (img_int[iLeft:iLeft + patch_sz, jLeft:jLeft + overlap]\n - img_sample_int[iRight:iRight + patch_sz, jRight:jRight + overlap])\n overlap_err = np.sum(np.sum(diff**2, axis=2)**0.5)\n\n return overlap_err\n\n\ndef overlap_error_horizntl(left_px, right_px):\n iLeft, jLeft = left_px\n iRight, jRight = right_px\n img_int = img.astype(np.int32)\n img_sample_int = img_sample.astype(np.int32)\n\n diff = (img_int[iLeft:iLeft + overlap, jLeft:jLeft + patch_sz]\n - img_sample_int[iRight:iRight + overlap, jRight:jRight + patch_sz])\n overlap_err = np.sum(np.sum(diff**2, axis=2)**0.5)\n\n return overlap_err\n\n\ndef get_best_tex_patches(px, overlap_err_threshold):\n pixels = []\n\n def ssd_error(img_pos, tex_pos):\n ix, iy = img_pos\n tx, ty = tex_pos\n src = img.astype(np.int32)\n tex = img_sample.astype(np.int32)\n diff = (src[ix:ix + patch_sz, iy:iy + patch_sz]\n - tex[tx:tx + patch_sz, ty:ty + patch_sz])\n return np.sum(diff ** 2) ** 0.5\n\n for i in range(patch_sz, sample_height - patch_sz):\n for j in range(patch_sz, sample_width - patch_sz):\n err = ssd_error((px[0], px[1]), (i, j))\n if err < overlap_err_threshold:\n pixels.append((i, j))\n elif err < overlap_err_threshold / 2:\n return [(i, j)]\n\n return pixels\n\n\ndef get_best_patches(px, overlap_err_threshold):\n pixels = []\n # check for top layer\n if px[0] == 0:\n for i in range(sample_height - patch_sz):\n for j in range(overlap, sample_width - patch_sz):\n error = overlap_error_vertical((px[0], px[1] - overlap),\n (i, j - overlap))\n if error < overlap_err_threshold:\n pixels.append((i, j))\n elif error < overlap_err_threshold / 2:\n return [(i, j)]\n # check for leftmost layer\n elif px[1] == 0:\n for i in range(overlap, sample_height - patch_sz):\n for j in range(sample_width - patch_sz):\n error = overlap_error_horizntl((px[0] - overlap, px[1]),\n (i - overlap, j))\n if error < overlap_err_threshold:\n pixels.append((i, j))\n elif error < overlap_err_threshold / 2:\n return [(i, j)]\n # for pixel placed inside\n else:\n for i in range(overlap, sample_height - patch_sz):\n for j in range(overlap, sample_width - patch_sz):\n error_vertical = overlap_error_vertical(\n (px[0], px[1] - overlap), (i, j - overlap))\n error_horizntl = overlap_error_horizntl(\n (px[0] - overlap, px[1]), (i - overlap, j))\n if (error_vertical < overlap_err_threshold and\n error_horizntl < overlap_err_threshold):\n pixels.append((i, j))\n elif (error_vertical < overlap_err_threshold / 2 and\n error_horizntl < overlap_err_threshold / 2):\n return [(i, j)]\n return pixels\n\n\n# ------------------------------ #\n# Quilting and related Functions #\n# ------------------------------ #\ndef calc_ssd_error(offset, img_px, sample_px):\n err_r = int(img[img_px[0] + offset[0], img_px[1] + offset[1]][0]) - int(\n img_sample[sample_px[0] + offset[0], sample_px[1] + offset[1]][0])\n err_g = int(img[img_px[0] + offset[0], img_px[1] + offset[1]][1]) - int(\n img_sample[sample_px[0] + offset[0], sample_px[1] + offset[1]][1])\n err_b = int(img[img_px[0] + offset[0], img_px[1] + offset[1]][2]) - int(\n img_sample[sample_px[0] + offset[0], sample_px[1] + offset[1]][2])\n return (err_r**2 + err_g**2 + err_b**2) / 3.0\n\n\n# ---------------- #\n# Calculating Cost #\n# ---------------- #\ndef get_cost_vertical(img_px, sample_px):\n cost = np.zeros((patch_sz, overlap))\n for j in range(overlap):\n for i in range(patch_sz):\n if i == patch_sz - 1:\n cost[i, j] = calc_ssd_error((i, j - overlap), img_px,\n sample_px)\n else:\n if j == 0:\n cost[i, j] = calc_ssd_error(\n (i, j - overlap), img_px, sample_px) + min(\n calc_ssd_error(\n (i + 1, j - overlap), img_px, sample_px),\n calc_ssd_error(\n (i + 1, j + 1 - overlap), img_px, sample_px))\n elif j == overlap - 1:\n cost[i, j] = calc_ssd_error(\n (i, j - overlap), img_px, sample_px) + min(\n calc_ssd_error(\n (i + 1, j - overlap), img_px, sample_px),\n calc_ssd_error(\n (i + 1, j - 1 - overlap), img_px, sample_px))\n else:\n cost[i, j] = calc_ssd_error(\n (i, j - overlap), img_px, sample_px) + min(\n calc_ssd_error(\n (i + 1, j - overlap), img_px, sample_px),\n calc_ssd_error(\n (i + 1, j + 1 - overlap), img_px, sample_px),\n calc_ssd_error(\n (i + 1, j - 1 - overlap), img_px, sample_px))\n return cost\n\n\ndef get_cost_horizntl(img_px, sample_px):\n cost = np.zeros((overlap, patch_sz))\n for i in range(overlap):\n for j in range(patch_sz):\n if j == patch_sz - 1:\n cost[i, j] = calc_ssd_error((i - overlap, j), img_px,\n sample_px)\n elif i == 0:\n cost[i, j] = calc_ssd_error(\n (i - overlap, j), img_px, sample_px) + min(\n calc_ssd_error(\n (i - overlap, j + 1), img_px, sample_px),\n calc_ssd_error(\n (i + 1 - overlap, j + 1), img_px, sample_px))\n elif i == overlap - 1:\n cost[i, j] = calc_ssd_error(\n (i - overlap, j), img_px, sample_px) + min(\n calc_ssd_error(\n (i - overlap, j + 1), img_px, sample_px),\n calc_ssd_error(\n (i - 1 - overlap, j + 1), img_px, sample_px))\n else:\n cost[i, j] = calc_ssd_error(\n (i - overlap, j), img_px, sample_px) + min(\n calc_ssd_error(\n (i - overlap, j + 1), img_px, sample_px),\n calc_ssd_error(\n (i + 1 - overlap, j + 1), img_px, sample_px),\n calc_ssd_error(\n (i - 1 - overlap, j + 1), img_px, sample_px))\n return cost\n\n\n# ------------------------- #\n# Finding Minimum Cost Path #\n# ------------------------- #\n\n\ndef find_mincost_path_vertical(cost):\n boundary = np.zeros((patch_sz), np.int)\n parent_matrix = np.zeros((patch_sz, overlap), np.int)\n for i in range(1, patch_sz):\n for j in range(overlap):\n if j == 0:\n parent_matrix[i, j] = j if cost[i - 1, j] < cost[i - 1, j +\n 1] else j + 1\n elif j == overlap - 1:\n parent_matrix[i, j] = j if cost[i - 1, j] < cost[i - 1, j -\n 1] else j - 1\n else:\n curr_min = j if cost[i - 1, j] < cost[i - 1, j - 1] else j - 1\n parent_matrix[i, j] = curr_min if cost[i - 1, curr_min] < cost[\n i - 1, j + 1] else j + 1\n cost[i, j] += cost[i - 1, parent_matrix[i, j]]\n min_idx = 0\n for j in range(1, overlap):\n min_idx = min_idx if cost[patch_sz - 1, min_idx] < cost[patch_sz - 1,\n j] else j\n boundary[patch_sz - 1] = min_idx\n for i in range(patch_sz - 1, 0, -1):\n boundary[i - 1] = parent_matrix[i, boundary[i]]\n return boundary\n\n\ndef find_mincost_path_horizntl(cost):\n boundary = np.zeros((patch_sz), np.int)\n parent_matrix = np.zeros((overlap, patch_sz), np.int)\n for j in range(1, patch_sz):\n for i in range(overlap):\n if i == 0:\n parent_matrix[i, j] = i if cost[i, j - 1] < cost[i + 1, j -\n 1] else i + 1\n elif i == overlap - 1:\n parent_matrix[i, j] = i if cost[i, j - 1] < cost[i - 1, j -\n 1] else i - 1\n else:\n curr_min = i if cost[i, j - 1] < cost[i - 1, j - 1] else i - 1\n parent_matrix[i, j] = curr_min if cost[curr_min, j - 1] < cost[\n i - 1, j - 1] else i + 1\n cost[i, j] += cost[parent_matrix[i, j], j - 1]\n min_idx = 0\n for i in range(1, overlap):\n min_idx = min_idx if cost[min_idx, patch_sz - 1] < cost[i, patch_sz -\n 1] else i\n boundary[patch_sz - 1] = min_idx\n for j in range(patch_sz - 1, 0, -1):\n boundary[j - 1] = parent_matrix[boundary[j], j]\n return boundary\n\n\n# -------- #\n# Quilting #\n# -------- #\n\n\ndef quilt_vertical(boundary, img_px, sample_px):\n for i in range(patch_sz):\n for j in range(boundary[i], 0, -1):\n img[img_px[0] + i, img_px[1] - j] = img_sample[sample_px[0] + i,\n sample_px[1] - j]\n\n\ndef quilt_horizntl(boundary, img_px, sample_px):\n for j in range(patch_sz):\n for i in range(boundary[j], 0, -1):\n img[img_px[0] - i, img_px[1] + j] = img_sample[sample_px[0] - i,\n sample_px[1] + j]\n\n\ndef quilt_patches(img_px, sample_px):\n # check for top layer\n if img_px[0] == 0:\n cost = get_cost_vertical(img_px, sample_px)\n # Getting boundary to stitch\n boundary = find_mincost_path_vertical(cost)\n # Quilting Patches\n quilt_vertical(boundary, img_px, sample_px)\n # check for leftmost layer\n elif img_px[1] == 0:\n cost = get_cost_horizntl(img_px, sample_px)\n # Boundary to stitch\n boundary = find_mincost_path_horizntl(cost)\n # Quilting Patches\n quilt_horizntl(boundary, img_px, sample_px)\n # for pixel placed inside\n else:\n cost_vertical = get_cost_vertical(img_px, sample_px)\n cost_horizntl = get_cost_horizntl(img_px, sample_px)\n boundary_vertical = find_mincost_path_vertical(cost_vertical)\n boundary_horizntl = find_mincost_path_horizntl(cost_horizntl)\n quilt_vertical(boundary_vertical, img_px, sample_px)\n quilt_horizntl(boundary_horizntl, img_px, sample_px)\n\n\n# ---------------------------- #\n# Growing Image Patch-by-patch #\n# ---------------------------- #\ndef fill_image(img_px, sample_px, output=None):\n x, y = img_px\n ref_x, ref_y = sample_px\n out = output if output is not None else img\n out[x:x + patch_sz, y:y + patch_sz] = \\\n img_sample[ref_x:ref_x + patch_sz, ref_y:ref_y + patch_sz]\n","sub_path":"toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":12190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"44614325","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\n\nfrom Functions.get_Cp_debye import getOptimizedDebyeParams, get_Cp_debye\n\n\ndef get_demons(experimental_temps, \n experimental_Cp, \n target_temps_range, \n *bounds):\n # \n k_b=1.38064852E-23\n Na=6.022E+23\n n_kinetic = 3\n #\n params, pcov = getOptimizedDebyeParams(experimental_temps,\n experimental_Cp, \n *bounds)\n \n Cp_debye = get_Cp_debye(target_temps_range, *params)\n demon_number_floor = [ (0, np.floor((cp/(k_b*Na) - n_kinetic)) )[(cp/(k_b*Na) - n_kinetic) > 0] \\\n for cp in np.array(Cp_debye) ]\n demon_number_ceil = [ (0, np.ceil((cp/(k_b*Na) - n_kinetic)) )[(cp/(k_b*Na) - n_kinetic) > 0] \\\n for cp in np.array(Cp_debye) ]\n ### calculate floor weight: the diference between cp/(k_b*Na) - n_kinetic and floor\n weight_floor = [1 -\\\n np.sqrt(np.abs(demon_number_floor[i]-\\\n Cp_debye[i]/(k_b*Na)+n_kinetic)**2) \\\n for i in range(len( demon_number_floor)) \\\n ]\n ### calculate ceil weight: the diference between cp/(k_b*Na) - n_kinetic and ceil\n weight_ceil = [1 -\\\n np.sqrt(np.abs(demon_number_ceil[i]-\\\n Cp_debye[i]/(k_b*Na)+n_kinetic)**2) \\\n for i in range(len( demon_number_floor)) \\\n ]\n #### average of demons: demon_number_avg\n demon_number_avg = [weight_floor[i]*demon_number_floor[i] +\\\n weight_ceil[i]*demon_number_ceil[i] for i in range(len( demon_number_floor))]\n ####\n demons=np.zeros([len(target_temps_range), 4])\n demons[:, 0]= target_temps_range\n demons[:, 1]= demon_number_ceil\n demons[:, 2]= demon_number_floor\n ### the average:\n demons[:, 3]= demon_number_avg\n return demons , weight_floor, weight_ceil\n","sub_path":"FunctionsLayer2/get_demons.py","file_name":"get_demons.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"354757716","text":"# Copyright 2018 The TensorFlow Hub Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for tensorflow_hub.compressed_module_resolver.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# pylint:disable=g-import-not-at-top,g-statement-before-imports\ntry:\n import mock as mock\nexcept ImportError:\n import unittest.mock as mock\n# pylint:disable=g-import-not-at-top,g-statement-before-imports\n\nimport os\nimport re\nimport socket\nimport tarfile\nimport tempfile\nimport uuid\n\nimport tensorflow as tf\n\nfrom tensorflow_hub import compressed_module_resolver\nfrom tensorflow_hub import resolver\nfrom tensorflow_hub import test_utils\nfrom tensorflow_hub import tf_utils\n\nFLAGS = tf.flags.FLAGS\n\n\nclass HttpCompressedFileResolverTest(tf.test.TestCase):\n\n def setUp(self):\n # Set current directory to test temp directory where we can create\n # files and serve them through the HTTP server.\n os.chdir(self.get_temp_dir())\n\n # Create three temp files.\n self.files = [\"file1\", \"file2\", \"file3\"]\n for cur_file in self.files:\n with tf.gfile.GFile(cur_file, mode=\"w\") as f:\n f.write(cur_file)\n\n # Write a dummy file so download server doesn't return 404.\n with tf.gfile.GFile(\"mock_module\", mode=\"w\") as f:\n f.write(\"module\")\n\n # Create TAR files.\n tar = tarfile.open(\"mock_module.tar\", \"w\")\n for name in self.files:\n tar.add(name)\n tar.close()\n\n # Create TGZ file\n tar = tarfile.open(\"mock_module.tar.gz\", \"w:gz\")\n for name in self.files:\n tar.add(name)\n tar.close()\n\n self.server_port = test_utils.start_http_server()\n self.module_handle = (\n \"http://localhost:%d/mock_module.tar.gz\" % self.server_port)\n\n self.redirect_server_port = test_utils.start_http_server(\n redirect=\"http://localhost:%d\" % self.server_port)\n\n self.smart_server_port = test_utils.start_smart_module_server(\n self.module_handle)\n self.smart_handle = (\n \"http://localhost:%d/mock_module\" % self.smart_server_port)\n\n def testGetModulePathTar(self):\n FLAGS.tfhub_cache_dir = os.path.join(self.get_temp_dir(), \"cache_dir\")\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n path = http_resolver(\n \"http://localhost:%d/mock_module.tar\" % self.server_port)\n files = os.listdir(path)\n self.assertListEqual(sorted(files), [\"file1\", \"file2\", \"file3\"])\n\n def testGetModulePathTarGz(self):\n FLAGS.tfhub_cache_dir = os.path.join(self.get_temp_dir(), \"cache_dir\")\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n path = http_resolver(self.module_handle)\n files = os.listdir(path)\n self.assertListEqual(sorted(files), [\"file1\", \"file2\", \"file3\"])\n\n def testGetModuleFromSmartLocation(self):\n FLAGS.tfhub_cache_dir = os.path.join(self.get_temp_dir(), \"cache_dir\")\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n path = http_resolver(self.smart_handle)\n files = os.listdir(path)\n self.assertListEqual(sorted(files), [\"file1\", \"file2\", \"file3\"])\n\n def testModuleDescriptor(self):\n FLAGS.tfhub_cache_dir = os.path.join(self.get_temp_dir(), \"cache_dir\")\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n path = http_resolver(self.module_handle)\n desc = tf_utils.read_file_to_string(resolver._module_descriptor_file(path))\n self.assertRegexpMatches(desc, \"Module: %s\\n\"\n \"Download Time: .*\\n\"\n \"Downloader Hostname: %s .PID:%d.\" %\n (re.escape(self.module_handle),\n re.escape(socket.gethostname()), os.getpid()))\n\n def testNoCacheDirSet(self):\n FLAGS.tfhub_cache_dir = \"\"\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n handle = \"http://localhost:%d/mock_module.tar.gz\" % self.server_port\n path = http_resolver(handle)\n files = os.listdir(path)\n self.assertListEqual(sorted(files), [\"file1\", \"file2\", \"file3\"])\n self.assertStartsWith(path, tempfile.gettempdir())\n\n def testIsTarFile(self):\n self.assertTrue(compressed_module_resolver._is_tarfile(\"foo.tar\"))\n self.assertTrue(compressed_module_resolver._is_tarfile(\"foo.tar.gz\"))\n self.assertTrue(compressed_module_resolver._is_tarfile(\"foo.tgz\"))\n self.assertFalse(compressed_module_resolver._is_tarfile(\"foo\"))\n self.assertFalse(compressed_module_resolver._is_tarfile(\"footar\"))\n\n def testAppendFormatQuery(self):\n tests = [(\n \"https://example.com/module.tar.gz\",\n \"https://example.com/module.tar.gz?tf-hub-format=compressed\",\n ), (\n \"https://example.com/module\",\n \"https://example.com/module?tf-hub-format=compressed\",\n ), (\n \"https://example.com/module?extra=abc\",\n \"https://example.com/module?extra=abc&tf-hub-format=compressed\",\n ), (\n \"https://example.com/module?extra=abc\",\n \"https://example.com/module?extra=abc&tf-hub-format=compressed\",\n ), (\n \"https://example.com/module?extra=abc&tf-hub-format=test\",\n (\"https://example.com/module?extra=abc&\"\n \"tf-hub-format=test&tf-hub-format=compressed\"),\n )]\n for handle, expected in tests:\n self.assertTrue(\n compressed_module_resolver._append_compressed_format_query(handle),\n expected)\n\n def testAbandondedLockFile(self):\n # Tests that the caching procedure is resilient to an abandonded lock\n # file.\n FLAGS.tfhub_cache_dir = os.path.join(self.get_temp_dir(), \"cache_dir\")\n\n # Create an \"abandoned\" lock file, i.e. a lock file with no process actively\n # downloading anymore.\n module_dir = compressed_module_resolver._module_dir(self.module_handle)\n task_uid = uuid.uuid4().hex\n lock_filename = resolver._lock_filename(module_dir)\n tf_utils.atomic_write_string_to_file(lock_filename,\n resolver._lock_file_contents(task_uid),\n overwrite=False)\n with mock.patch.object(\n compressed_module_resolver.HttpCompressedFileResolver,\n \"_lock_file_timeout_sec\",\n return_value=10):\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n handle = \"http://localhost:%d/mock_module.tar.gz\" % self.server_port\n # After seeing the lock file is abandoned, this resolver will download the\n # module and return a path to the extracted contents.\n path = http_resolver(handle)\n files = os.listdir(path)\n self.assertListEqual(sorted(files), [\"file1\", \"file2\", \"file3\"])\n self.assertFalse(tf.gfile.Exists(lock_filename))\n\n def testModuleAlreadyDownloaded(self):\n FLAGS.tfhub_cache_dir = os.path.join(self.get_temp_dir(), \"cache_dir\")\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n path = http_resolver(self.module_handle)\n files = sorted(os.listdir(path))\n self.assertListEqual(files, [\"file1\", \"file2\", \"file3\"])\n creation_times = [\n tf.gfile.Stat(os.path.join(path, f)).mtime_nsec for f in files\n ]\n # Call resolver again and make sure that the module is not downloaded again\n # by checking the timestamps of the module files.\n path = http_resolver(self.module_handle)\n files = sorted(os.listdir(path))\n self.assertListEqual(files, [\"file1\", \"file2\", \"file3\"])\n self.assertListEqual(\n creation_times,\n [tf.gfile.Stat(os.path.join(path, f)).mtime_nsec for f in files])\n\n def testCorruptedArchive(self):\n with tf.gfile.GFile(\"bad_archive.tar.gz\", mode=\"w\") as f:\n f.write(\"bad_archive\")\n http_resolver = compressed_module_resolver.HttpCompressedFileResolver()\n try:\n http_resolver(\n \"http://localhost:%d/bad_archive.tar.gz\" % self.server_port)\n self.fail(\"Corrupted archive should have failed to resolve.\")\n except IOError as e:\n self.assertEqual(\n \"http://localhost:%d/bad_archive.tar.gz does not appear \"\n \"to be a valid module.\" %\n self.server_port, str(e))\n try:\n http_resolver(\n \"http://localhost:%d/bad_archive.tar.gz\" % self.redirect_server_port)\n self.fail(\"Corrupted archive should have failed to resolve.\")\n except IOError as e:\n # Check that the error message contain the ultimate (redirected to) URL.\n self.assertEqual(\n \"http://localhost:%d/bad_archive.tar.gz does not appear \"\n \"to be a valid module.\" %\n self.redirect_server_port, str(e))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n","sub_path":"tensorflow_hub/compressed_module_resolver_test.py","file_name":"compressed_module_resolver_test.py","file_ext":"py","file_size_in_byte":9184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"211430101","text":"\n# AI events\nAI_LEFT = 1000\nAI_RIGHT = 1001\nAI_UP = 1002\nAI_DOWN = 1003\nAI_MOVE = 1004\nAI_SKIP = 1005\n\n# Turn events\nEND_TURN = 1006\nDEATH = 1007\n\nclass Event(object):\n\n _events = []\n\n @classmethod\n def get( cls ):\n events = cls._events\n cls._events = []\n\n return events\n\n def __init__( self, key, target=None, **kwargs ):\n self.key = key\n self.target = target\n\n for k, v in kwargs.items():\n setattr(self, k, v )\n\n Event._events.append( self )\n\n","sub_path":"event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"197113627","text":"import ctypes\n\n\nclass bytestream_t(ctypes.Structure):\n _fields_ = [(\"buf\", ctypes.POINTER(ctypes.c_ubyte)),\n (\"max_len\", ctypes.c_size_t),\n (\"idx\", ctypes.c_size_t)]\n\n @classmethod\n def create(cls, length):\n array_type = ctypes.c_ubyte * length\n array = array_type()\n return cls(array, length, 0)\n\n @classmethod\n def from_stream(cls, stream):\n array_type = ctypes.c_ubyte * len(stream)\n array = array_type(stream)\n return cls(array, len(stream), 0)\n\n @property\n def stream(self):\n return bytearray([self.buf[i] for i in range(self.max_len)])\n","sub_path":"sermsg/codegen/implementations/static_c/test/bytestream.py","file_name":"bytestream.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"389729163","text":"#this program will remove the tag that y2mate add\n# to the name when you download it\n# Linux version\n\nimport os\n\ndef main():\n print( \"Eliminando tag..\")\n try:\n recorrer_directorio()\n print(\"Finalizado con exito!\")\n except error:\n print(\"Ocurrio un error :(\",error)\n\ndef recorrer_directorio():\n listar_canciones = os.listdir()\n\n for cancion in listar_canciones:\n if (cancion[:10] == \"y2mate.com\"):\n nombre_nuevo = cancion[12:]\n os.rename(cancion,nombre_nuevo)\n\n\nmain()\n","sub_path":"Music_downloader/music_downloader_v2/remove_nametag_from_y2mate/remover.py","file_name":"remover.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"195262741","text":"# -*- coding: utf-8 -*-\r\n#\r\n# Copyright © 2011-2013 Pierre Raybaut\r\n# Licensed under the terms of the MIT License\r\n# (see spyderlib/__init__.py for details)\r\n\r\n\"\"\"\r\nSpyder base configuration management\r\n\r\nAs opposed to spyderlib/config.py, this configuration script deals \r\nexclusively with non-GUI features configuration only\r\n(in other words, we won't import any PyQt object here, avoiding any \r\nsip API incompatibility issue in spyderlib's non-gui modules)\r\n\"\"\"\r\n\r\nfrom __future__ import print_function\r\n\r\nimport os.path as osp\r\nimport os\r\nimport sys\r\n\r\n# Local imports\r\nfrom spyderlib import __version__\r\nfrom spyderlib.utils import encoding\r\nfrom spyderlib.py3compat import (is_unicode, TEXT_TYPES, INT_TYPES, PY3,\r\n to_text_string, is_text_string)\r\n\r\n\r\n#==============================================================================\r\n# Only for development\r\n#==============================================================================\r\n# To activate/deactivate certain things for development\r\n# SPYDER_DEV is (and *only* has to be) set in bootstrap.py\r\nDEV = os.environ.get('SPYDER_DEV')\r\n\r\n# For testing purposes\r\n# SPYDER_TEST can be set using the --test option of bootstrap.py\r\nTEST = os.environ.get('SPYDER_TEST')\r\n\r\n\r\n#==============================================================================\r\n# Debug helpers\r\n#==============================================================================\r\nSTDOUT = sys.stdout\r\nSTDERR = sys.stderr\r\ndef _get_debug_env():\r\n debug_env = os.environ.get('SPYDER_DEBUG', '')\r\n if not debug_env.isdigit():\r\n debug_env = bool(debug_env)\r\n return int(debug_env) \r\nDEBUG = _get_debug_env()\r\n\r\ndef debug_print(message):\r\n \"\"\"Output debug messages to stdout\"\"\"\r\n if DEBUG:\r\n ss = STDOUT\r\n print(message, file=ss)\r\n\r\n#==============================================================================\r\n# Configuration paths\r\n#==============================================================================\r\n# Spyder settings dir\r\nif TEST is None:\r\n SUBFOLDER = '.spyder%s' % __version__.split('.')[0]\r\nelse:\r\n SUBFOLDER = 'spyder_test'\r\n\r\n\r\n# We can't have PY2 and PY3 settings in the same dir because:\r\n# 1. This leads to ugly crashes and freezes (e.g. by trying to\r\n# embed a PY2 interpreter in PY3)\r\n# 2. We need to save the list of installed modules (for code\r\n# completion) separately for each version\r\nif PY3:\r\n SUBFOLDER = SUBFOLDER + '-py3'\r\n\r\n\r\ndef get_home_dir():\r\n \"\"\"\r\n Return user home directory\r\n \"\"\"\r\n try:\r\n # expanduser() returns a raw byte string which needs to be\r\n # decoded with the codec that the OS is using to represent file paths.\r\n path = encoding.to_unicode_from_fs(osp.expanduser('~'))\r\n except:\r\n path = ''\r\n for env_var in ('HOME', 'USERPROFILE', 'TMP'):\r\n if osp.isdir(path):\r\n break\r\n # os.environ.get() returns a raw byte string which needs to be\r\n # decoded with the codec that the OS is using to represent environment\r\n # variables.\r\n path = encoding.to_unicode_from_fs(os.environ.get(env_var, ''))\r\n if path:\r\n return path\r\n else:\r\n raise RuntimeError('Please define environment variable $HOME')\r\n\r\n\r\ndef get_conf_path(filename=None):\r\n \"\"\"Return absolute path for configuration file with specified filename\"\"\"\r\n if TEST is None:\r\n conf_dir = osp.join(get_home_dir(), SUBFOLDER)\r\n else:\r\n import tempfile\r\n conf_dir = osp.join(tempfile.gettempdir(), SUBFOLDER)\r\n if not osp.isdir(conf_dir):\r\n os.mkdir(conf_dir)\r\n if filename is None:\r\n return conf_dir\r\n else:\r\n return osp.join(conf_dir, filename)\r\n \r\n\r\ndef get_module_path(modname):\r\n \"\"\"Return module *modname* base path\"\"\"\r\n return osp.abspath(osp.dirname(sys.modules[modname].__file__))\r\n\r\n\r\ndef get_module_data_path(modname, relpath=None, attr_name='DATAPATH'):\r\n \"\"\"Return module *modname* data path\r\n Note: relpath is ignored if module has an attribute named *attr_name*\r\n \r\n Handles py2exe/cx_Freeze distributions\"\"\"\r\n datapath = getattr(sys.modules[modname], attr_name, '')\r\n if datapath:\r\n return datapath\r\n else:\r\n datapath = get_module_path(modname)\r\n parentdir = osp.join(datapath, osp.pardir)\r\n if osp.isfile(parentdir):\r\n # Parent directory is not a directory but the 'library.zip' file:\r\n # this is either a py2exe or a cx_Freeze distribution\r\n datapath = osp.abspath(osp.join(osp.join(parentdir, osp.pardir),\r\n modname))\r\n if relpath is not None:\r\n datapath = osp.abspath(osp.join(datapath, relpath))\r\n return datapath\r\n\r\n\r\ndef get_module_source_path(modname, basename=None):\r\n \"\"\"Return module *modname* source path\r\n If *basename* is specified, return *modname.basename* path where \r\n *modname* is a package containing the module *basename*\r\n \r\n *basename* is a filename (not a module name), so it must include the\r\n file extension: .py or .pyw\r\n \r\n Handles py2exe/cx_Freeze distributions\"\"\"\r\n srcpath = get_module_path(modname)\r\n parentdir = osp.join(srcpath, osp.pardir)\r\n if osp.isfile(parentdir):\r\n # Parent directory is not a directory but the 'library.zip' file:\r\n # this is either a py2exe or a cx_Freeze distribution\r\n srcpath = osp.abspath(osp.join(osp.join(parentdir, osp.pardir),\r\n modname))\r\n if basename is not None:\r\n srcpath = osp.abspath(osp.join(srcpath, basename))\r\n return srcpath\r\n\r\n\r\ndef is_py2exe_or_cx_Freeze():\r\n \"\"\"Return True if this is a py2exe/cx_Freeze distribution of Spyder\"\"\"\r\n return osp.isfile(osp.join(get_module_path('spyderlib'), osp.pardir))\r\n\r\n\r\nSCIENTIFIC_STARTUP = get_module_source_path('spyderlib',\r\n 'scientific_startup.py')\r\n\r\n\r\n#==============================================================================\r\n# Image path list\r\n#==============================================================================\r\n\r\nIMG_PATH = []\r\ndef add_image_path(path):\r\n if not osp.isdir(path):\r\n return\r\n global IMG_PATH\r\n IMG_PATH.append(path)\r\n for _root, dirs, _files in os.walk(path):\r\n for dir in dirs:\r\n IMG_PATH.append(osp.join(path, dir))\r\n\r\nadd_image_path(get_module_data_path('spyderlib', relpath='images'))\r\n\r\nfrom spyderlib.otherplugins import PLUGIN_PATH\r\nif PLUGIN_PATH is not None:\r\n add_image_path(osp.join(PLUGIN_PATH, 'images'))\r\n\r\ndef get_image_path(name, default=\"not_found.png\"):\r\n \"\"\"Return image absolute path\"\"\"\r\n for img_path in IMG_PATH:\r\n full_path = osp.join(img_path, name)\r\n if osp.isfile(full_path):\r\n return osp.abspath(full_path)\r\n if default is not None:\r\n return osp.abspath(osp.join(img_path, default))\r\n\r\n\r\n#==============================================================================\r\n# Translations\r\n#==============================================================================\r\ndef get_translation(modname, dirname=None):\r\n \"\"\"Return translation callback for module *modname*\"\"\"\r\n if dirname is None:\r\n dirname = modname\r\n locale_path = get_module_data_path(dirname, relpath=\"locale\",\r\n attr_name='LOCALEPATH')\r\n # fixup environment var LANG in case it's unknown\r\n if \"LANG\" not in os.environ:\r\n import locale\r\n lang = locale.getdefaultlocale()[0]\r\n if lang is not None:\r\n os.environ[\"LANG\"] = lang\r\n import gettext\r\n try:\r\n _trans = gettext.translation(modname, locale_path, codeset=\"utf-8\")\r\n lgettext = _trans.lgettext\r\n def translate_gettext(x):\r\n if not PY3 and is_unicode(x):\r\n x = x.encode(\"utf-8\")\r\n y = lgettext(x)\r\n if is_text_string(y) and PY3:\r\n return y\r\n else:\r\n return to_text_string(y, \"utf-8\")\r\n return translate_gettext\r\n except IOError as _e: # analysis:ignore\r\n #print \"Not using translations (%s)\" % _e\r\n def translate_dumb(x):\r\n if not is_unicode(x):\r\n return to_text_string(x, \"utf-8\")\r\n return x\r\n return translate_dumb\r\n\r\n# Translation callback\r\n_ = get_translation(\"spyderlib\")\r\n\r\n\r\n#==============================================================================\r\n# Namespace Browser (Variable Explorer) configuration management\r\n#==============================================================================\r\n\r\ndef get_supported_types():\r\n \"\"\"\r\n Return a dictionnary containing types lists supported by the \r\n namespace browser:\r\n dict(picklable=picklable_types, editable=editables_types)\r\n \r\n See:\r\n get_remote_data function in spyderlib/widgets/externalshell/monitor.py\r\n get_internal_shell_filter method in namespacebrowser.py\r\n \r\n Note:\r\n If you update this list, don't forget to update doc/variablexplorer.rst\r\n \"\"\"\r\n from datetime import date\r\n editable_types = [int, float, complex, list, dict, tuple, date\r\n ] + list(TEXT_TYPES) + list(INT_TYPES)\r\n try:\r\n from numpy import ndarray, matrix, generic\r\n editable_types += [ndarray, matrix, generic]\r\n except ImportError:\r\n pass\r\n try:\r\n from pandas import DataFrame, Series\r\n editable_types += [DataFrame, Series]\r\n except ImportError:\r\n pass\r\n picklable_types = editable_types[:]\r\n try:\r\n from spyderlib.pil_patch import Image\r\n editable_types.append(Image.Image)\r\n except ImportError:\r\n pass\r\n return dict(picklable=picklable_types, editable=editable_types)\r\n\r\n# Variable explorer display / check all elements data types for sequences:\r\n# (when saving the variable explorer contents, check_all is True,\r\n# see widgets/externalshell/namespacebrowser.py:NamespaceBrowser.save_data)\r\nCHECK_ALL = False #XXX: If True, this should take too much to compute...\r\n\r\nEXCLUDED_NAMES = ['nan', 'inf', 'infty', 'little_endian', 'colorbar_doc',\r\n 'typecodes', '__builtins__', '__main__', '__doc__', 'NaN',\r\n 'Inf', 'Infinity', 'sctypes', 'rcParams', 'rcParamsDefault',\r\n 'sctypeNA', 'typeNA', 'False_', 'True_',]\r\n\r\n#==============================================================================\r\n# Mac application utilities\r\n#==============================================================================\r\n\r\nif PY3:\r\n MAC_APP_NAME = 'Spyder.app'\r\nelse:\r\n MAC_APP_NAME = 'Spyder-Py2.app'\r\n\r\ndef running_in_mac_app():\r\n if sys.platform == \"darwin\" and MAC_APP_NAME in __file__:\r\n return True\r\n else:\r\n return False\r\n","sub_path":"lib/python2.7/site-packages/spyderlib/baseconfig.py","file_name":"baseconfig.py","file_ext":"py","file_size_in_byte":10872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"374620529","text":"\n################################################################################\n# NAME : get_spire_beam.py\n# DATE STARTED : June 18, 2019\n# AUTHORS : Dale Mercado & Benjamin Vaugahn\n# PURPOSE : This function computes the spire beam given a band, pixel size and\n# output map kernel.\n# EXPLANATION :\n# CALLING SEQUENCE :\n# INPUTS :\n# band (string) = one of 'PSW', 'PMW', 'PLW' (def: PSW)\n# pixsize (float) = the pixel size in arcsec (def: 6/8.333/12)\n# npixx (int) = the number of pixels required in the x axis\n# This should be odd so the PSF is\n# centered. (def: 5 FWHM rounded to odd)\n# npixy (int) = the number of pixels required in the y axis.\n# This should be odd so the PSF is\n# centered. (def: npixx)\n# xcent (float) = x pixel corresponding to center of the beam\n# (can be fractional, note that pixel\n# numbering starts at 0) (def: npixx/2 using\n# integral division, so if npixx is 31,\n# this is 15). This is in the\n# non-oversampled beam.\n# ycent (float) = y pixel corresponding to center of the beam\n# (can be fractional). (def: npixy/2, see\n# note for xcent for further info)\n# Optional inputs:\n# bolometer (string) = Optional argument specifying which bolometer\n# to return beam for (i.e., band='PSW',\n# bolometer='A11': psf for 'PSWA11').\n# Not currently supported, but here for\n# when we have bolometer specific psfs in\n# the future.\n# fwhm (float) = The FWHM of the beam, in arcsec.\n# Normally this is determined by band.\n# oversamp = Amount to oversample pixels by before\n# convolving with pixel function.\n# Should be an odd integer (Def: 7)\n#\n#\n# OUTPUTS :\n# beamkern (float) = array size npixx x npixy containing\n# REVISION HISTORY :\n################################################################################\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import *\nfrom astropy.io import fits\nimport scipy.signal\nimport os\nfrom astropy.convolution import Gaussian2DKernel, Gaussian1DKernel\nfrom get_spire_beam_fwhm import *\n\n\n\ndef get_spire_beam(band=None, pixsize=0,npixx=0, npixy=0,\n xcent=0, ycent=0,bolometer=0, fwhm='',\n norm=0, oversamp=0, verbose=1,\n factor=0):\n errmsg = False\n if bolometer != 0:\n if verbose:\n print('PSFs for specific bolometer not yet supported -- ignoring')\n\n # Check if we have been given a band\n # If not make an assumption\n if band == None:\n if verbose:\n print('Band parameter not supplied, assuming PSW')\n band = 'PSW'\n # Check if we have been givin a pixel size\n if pixsize == 0:\n # band = upper(band)\n # units arcsec/pixel\n if band == 'PSW':\n pixsize = 6\n if band == 'PMW':\n pixsize = 8. + (1/3)\n if band == 'PLW':\n pixsize = 12\n else:\n print('Unknown band'+band)\n if verbose:\n print('pixsize paramter not supplied assuming %s arcsec' , (pixsize))\n\n\n if len(fwhm) == 0:\n beamFWHM = get_spire_beam_fwhm(band)\n else:\n beamFWHM = fwhm\n\n if beamFWHM < 0:\n print('Invalid Beam FWHM value'+ str(beamFWHM))\n\n # Check if we've been given the map size, if not assume something\n # npixx/npixy will be the final number of pixels\n if npixx == 0:\n npixx = round(beamFWHM * 5 / (pixsize))\n if npixx % 2 != 1:\n npixx +=1\n if verbose:\n print('npixx not supplied, using \",I0\"')\n #If no y size then assume same as x\n if npixy == 0:\n npixy = npixx\n\n #Make sure that these have been cast from a float properly or we get errors\n npixx = int(ceil(npixx))\n npixy = int(ceil(npixy))\n\n if npixx % 2 != 1 and verbose:\n print('WARNING: npixx not odd, so PSF will not be centered')\n if npixy % 2 != 1 and verbose:\n print('WARNING: npixy not odd, so psf will not be centered')\n\n # Now deal with oversampling\n if oversamp == 0:\n ioversamp = 7\n else:\n ioversamp = round(oversamp) #in case user provides float\n if ioversamp % 2 != 1:\n print('Oversamp must be an odd interger!')\n\n x_gen = npixx * ioversamp\n y_gen = npixy * ioversamp\n gen_pixsize = np.float64(pixsize) / ioversamp\n\n # Check if we have been givin the center, if not assume middle\n if xcent == 0:\n # if verbose:\n # print('xcent parameter not supplied, assuming array center')\n ixcent = x_gen / 2\n else:\n # Adjust for oversampling\n ixcent = xcent * ioversamp\n if ioversamp > 1:\n ixcent = ixcent + ioversamp / 2\n\n if ycent == 0:\n # if verbose:\n # print('ycent parameter not supplied, assuming array center')\n iycent = y_gen / 2\n else:\n iycent = ycent * ioversamp\n if ioversamp > 1:\n iycent = iycent +ioversamp / 2\n\n # Normalize FWHM to pixels\n beamFWHM /= gen_pixsize\n # Convert the FWHM to a standard deviation for astropy fit. From psf_gaussian\n stdev = beamFWHM / (sqrt(8 * log(2)))\n\n # If we want this normalized then call with norm flag set\n if factor:\n # 1D beam\n beamkernraw = Gaussian1DKernel(stdev, x_size=x_gen)\n beamkern = np.array(beamkernraw)\n if norm:\n beamkern = beamkern / beamkern.max()\n if ioversamp > 1:\n beamkern = rebin(beamkern,(npixx,npixy))\n else:\n beamkernraw = Gaussian2DKernel(stdev,x_size = x_gen, y_size = y_gen)\n beamkern = np.array(beamkernraw)\n if norm:\n beamkern = beamkern / beamkern.max()\n if ioversamp > 1:\n beamkern = \trebin(beamkern,(npixx,npixy))\n\n\n\n # # Use for debugging\n # plt.plot for 1d\n # plt.plot(beamkern, drawstyle='steps')\n # plt.imshow for 2d & colorbar\n # plt.imshow(beamkern, interpolation='none', origin='lower')\n # plt.colorbar()\n # plt.xlabel('x [pixels]')\n # plt.ylabel('y [pixels]')\n # plt.show()\n # beamkern = 1\n\n return beamkern\n\n\ndef rebin(a, new_shape):\n shape = a.shape\n M = int(shape[0])\n N = int(shape[1])\n m, n = new_shape\n if m radiusOfZeros * radiusOfZeros) and\n ((r - i - 1) * (r - i - 1) + j * j > radiusOfZeros * radiusOfZeros) and\n (i * i + (c - j - 1) * (c - j - 1) > radiusOfZeros * radiusOfZeros) and\n ((r - i - 1) * (r - i - 1) + (c - j - 1) * (c - j - 1) > radiusOfZeros * radiusOfZeros)):\n mask[i, j] = 1\n\ndft = dft * mask\n\nimage_back = cv2.idft(dft, flags=cv2.DFT_COMPLEX_OUTPUT)\nimage_back = cv2.magnitude(image_back[:, :, 0], image_back[:, :, 1])\ncv2.normalize(image_back, image_back, 0.0, 1.0, cv2.cv.CV_MINMAX)\ncv2.imshow(\"imageBackAfterDFT\", image_back)\n\nimage = cv2.Laplacian(image, 0)\ncv2.imshow(\"imageAfterLaplacian\", image)\ncv2.waitKey(0)","sub_path":"task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"642818884","text":"### simple if\ncars = ['audi', 'bmw', 'subaru', 'toyota']\n\nfor car in cars:\n if car == 'bmw':\n print(car.upper())\n else:\n print(car.title())\n\n# if-elif-else\nage = 12\nif age < 4:\n price = 0\nelif age < 18:\n price = 5\nelse:\n price = 10\nprint('Your cost is: ' + str(price) + '.')\n\n#multiple conditions\ntoppings = ['cheese', 'mushroom', 'cucumber']\nif 'cheese' in toppings:\n print('added cheese')\nif 'cucumber' in toppings:\n print('added cucumber')\n\n#exercise\n#1\nalien_color = 'red'\nif alien_color == 'green':\n print('Congratulations, you earned 5 points!')\nif alien_color == 'red':\n print('Congratulations, you earned 5 points!')\n#2\nif alien_color == 'green':\n print('Congratulations, you earned 5 points for shooting alien!')\nelse:\n print('Congratulations, you earned 10 points')\n#3\nif alien_color == 'green':\n print('Congratulations, you earned 5 points for shooting alien!')\nelif alien_color == 'yellow':\n print('Congratulations, you earned 10 points for shooting alien')\nelif alien_color == 'red':\n print('Congratulations, you earned 15 points for shooting alien')\n\n#Using if statement with list\nrequested_toppings = ['mushrooms', 'green peppers', 'extra cheese']\n\nfor topping in requested_toppings:\n if topping == 'green peppers':\n print(\"Sorry we don't have green peppers available now!\")\n else:\n print(topping.title() + ' added.')\n\n#List not empty\nrequested_toppings = []\n\nif requested_toppings:\n for topping in requested_toppings:\n if topping == 'green peppers':\n print(\"Sorry we don't have green peppers available now!\")\n else:\n print(topping.title() + ' added.')\nelse:\n print(\"Are you sure you want a plain pizza?\")\n\n#Using multiple lists\navailable_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple' , 'extra cheese']\nrequested_toppings = ['mushrooms', 'french fries', 'extra cheese']\n\nfor topping in requested_toppings:\n if topping not in available_toppings:\n print('Topping ' + topping.title() + ' is not available in our restaurant')\n else:\n print(topping.title() + ' added.')\n\n","sub_path":"chapter1/isstatement.py","file_name":"isstatement.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"169058159","text":"#Author: Fatima Abukar\r\n#Events class wrapper with many thanks to: http://www.pygame.org/wiki/InputWrapper?parent=CookBook\r\n\r\nimport pygame,sys\r\nfrom pygame.locals import *\r\nfrom pygame import *\r\n\r\n \r\n\r\nclass Event(object):\r\n pygame.init()\r\n #create global variables \r\n m_DOWN = \"isdown\"\r\n k_DOWN= \"isdown\"\r\n m_UP=\"isup\"\r\n k_UP=\"isup\"\r\n MOTION = \"motion\"\r\n Quit = True\r\n butt = {1: \"Button1\", 2: \"Button2\", 3: \"Button3\"}\r\n events = {}\r\n keydict={}\r\n mousedict={}\r\n quitdict={}\r\n button_state = ()\r\n mouse_pos = ()\r\n sizex, sizey=0,0\r\n newkeyname =\"\"\r\n \r\n #add a keyevent to dictionary \r\n @classmethod\r\n def __add_keyDict(cls,event):\r\n if event.type ==KEYDOWN:\r\n Event.keydict.update({event.key:[event, Event.k_DOWN]})\r\n elif event.type==KEYUP:\r\n Event.keydict.update({event.key:[event, Event.k_UP]})\r\n\r\n #add an mouseevent to dictionary \r\n @classmethod\r\n def __add_mouseDict(cls, event):\r\n if event.type == MOUSEBUTTONDOWN:\r\n Event.events.update({Event.butt[event.button]: [event, Event.m_DOWN]})\r\n elif event.type == MOUSEBUTTONUP:\r\n Event.events.update({Event.butt[event.button]: [event, Event.m_UP]})\r\n elif event.type == MOUSEMOTION:\r\n Event.events.update({MOUSEMOTION: [event, Event.MOTION]})\r\n \r\n #add a quitevent to dictionary \r\n @classmethod \r\n def __add_quitDict(cls,event):\r\n if event.type == pygame.QUIT:\r\n Event.quitdict.update({\"exit\": [event, Event.Quit]})\r\n \r\n #add a list of events to dictionaries\r\n @classmethod\r\n def __add_events(cls, events):\r\n for event in events:\r\n Event.__add_mouseDict(event)\r\n Event.__add_keyDict(event)\r\n Event.__add_quitDict(event)\r\n\r\n #set the keycodes \r\n @classmethod\r\n def __set_code(cls,keyname):\r\n if keyname ==\"left\":\r\n keyname = K_LEFT\r\n elif keyname ==\"right\":\r\n keyname =K_RIGHT\r\n elif keyname== \"up\":\r\n keyname = K_UP\r\n elif keyname == \"down\":\r\n keyname = K_DOWN\r\n Event.newkeyname = keyname\r\n\r\n #update the mouse buttons and positions \r\n @classmethod\r\n def __update_mouse(cls, buttons = (0,0,0), pos = (0,0)):\r\n Event.mouse_pos = pos\r\n Event.button_state = buttons\r\n\r\n #checks if the key is \"quit\" so you can exit the game \r\n @classmethod\r\n def contains(cls, name):\r\n for names in Event.quitdict:\r\n if names == name:\r\n return name\r\n \r\n #quits the game \r\n @classmethod\r\n def quit_game(cls):\r\n pygame.quit()\r\n sys.exit()\r\n \r\n @classmethod\r\n def exit_game(cls,game):\r\n for event in pygame.event.get():\r\n if event.type==pygame.QUIT:\r\n game=False\r\n pygame.quit()\r\n \r\n \r\n #checks if the key is at a down state and you have entered a keyname\r\n @classmethod\r\n def is_key(cls, keyname):\r\n Event.__set_code(keyname)\r\n event = Event.keydict.get(Event.newkeyname)\r\n novalue = None\r\n if event == novalue:\r\n key_code = novalue\r\n else:\r\n key_code = event[1]\r\n if key_code == Event.k_DOWN:\r\n return True\r\n else:\r\n return False\r\n \r\n #checks if the key has been released\r\n @classmethod\r\n def key_up(cls, keyname):\r\n #get event \r\n event = Event.keydict.get(keyname)\r\n novalue = None\r\n #if the event has no value \r\n if event==novalue:\r\n #key has no value \r\n key_code = novalue\r\n else:\r\n #key has state\r\n key_code = event[1]\r\n #if the key equals the state \r\n if key_code == Event.k_UP:\r\n #then the key has been released \r\n return True\r\n #otherwise the key has not been released \r\n return False\r\n \r\n #checks if the mouse has been pressed \r\n @classmethod\r\n def mouse_down(cls, button):\r\n \r\n event = Event.events.get(button)\r\n novalue=None\r\n if event ==novalue:\r\n key_code = novalue\r\n else:\r\n key_code = event[1]\r\n \r\n if key_code == Event.m_DOWN: \r\n return True\r\n else:\r\n return False\r\n\r\n #sets the image size for the cursor \r\n @classmethod\r\n def set_CursorPosOnImage(cls,sizex,sizey):\r\n Event.sizex=sizex\r\n Event.sizey=sizey\r\n\r\n #sets the cursor position on the image \r\n @classmethod \r\n def set_MouseCursorPos(cls,x,y):\r\n ## the passed x and y is the position of the cursor. \r\n x,y=Event.mouse_pos\r\n ##subtract half the image size from cursor x and y \r\n x=x-Event.sizex/2\r\n y=y-Event.sizey/2\r\n ## set the new mouse position of x and y. \r\n Event.mouse_pos=x,y\r\n \r\n #updates all the events \r\n @classmethod\r\n def update(cls):\r\n clock = pygame.time.Clock()\r\n time_passed = clock.tick(60)\r\n Event.__update_mouse(pygame.mouse.get_pressed(),pygame.mouse.get_pos())\r\n Event.__add_events(pygame.event.get())\r\n x,y = Event.mouse_pos\r\n Event.set_MouseCursorPos(x,y)\r\n\r\n \r\n \r\n \r\n","sub_path":"Game/PGS/Event.py","file_name":"Event.py","file_ext":"py","file_size_in_byte":5477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"522983395","text":"import collections\n\nimport dataset\n\nFilterSizes = collections.namedtuple(\n 'FilterSizes', ['conv0', 'conv1', 'conv2', 'conv3'])\n\n\nclass Model:\n def __init__(\n self,\n name,\n datadir,\n validation_size=500,\n test_size=1,\n batch_size=100,\n learning_rate=0.01,\n learning_rate_decay_factor=.1,\n max_steps=1000,\n rnn_cell_size=64,\n num_rnn_layers=1,\n grad_clip=10,\n conv_filter_sizes=FilterSizes(16, 16, 16, 16),\n embedding_dims=dataset.EmbeddingSize(\n **{'chars': 5, 'fonts': 3, 'fontsizes': 2, 'tokens': 10}),\n use_lstm=False,\n use_rnn_layer_norm=False,\n dropout_keep_prob=1.0\n ):\n self.name = name\n self.data = dataset.read_datasets(datadir, validation_size, test_size)\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.learning_rate_decay_factor = learning_rate_decay_factor\n self.grad_clip = grad_clip,\n self.max_steps = max_steps\n self.rnn_cell_size = rnn_cell_size\n self.num_rnn_layers = num_rnn_layers\n self.feature_vocab_size = self.data.feature_vocab_size\n self.token_vocab_size = self.data.token_vocab_size\n self.filters = conv_filter_sizes\n self.embedding_dims = embedding_dims\n self.use_lstm = use_lstm\n self.use_rnn_layer_norm = use_rnn_layer_norm\n self.dropout_keep_prob = dropout_keep_prob\n self.feature_dim = (embedding_dims.chars +\n embedding_dims.fonts +\n embedding_dims.fontsizes)\n\n @classmethod\n def small(cls, datadir, validation_size=500, test_size=1):\n return cls('small', datadir, validation_size, test_size,\n 20, 1e-4, 1, 6000, 64, 1)\n\n @classmethod\n def medium(cls, datadir, validation_size=1000, test_size=1):\n return cls('medium', datadir, validation_size, test_size,\n 100, 0.0001, 1, 2000, 256, 3)\n\n @classmethod\n def large(cls, datadir, validation_size=5000, test_size=1):\n return cls('large', datadir, validation_size, test_size,\n 50, 0.0001, 1, 6000, 1536, 3,\n conv_filter_sizes=FilterSizes(10, 10, 10, 10),\n dropout_keep_prob=0.5)\n\n @classmethod\n def medium_reg(cls, datadir, validation_size=500, test_size=1):\n return cls('medium-reg', datadir, validation_size, test_size,\n 100, 0.01, 1, 3000, 200, 4,\n use_lstm=True, use_rnn_layer_norm=True)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"432320108","text":"#typically programmers us i, j, k , l for the temp variable\n#if the temp var is special or used a lot, it will be given a proper name\n\n#range is a special built-in funtion in python. when used with a \n#for loop it will create a list of numbers from (i, i-1)\n#So in this loop, the range() function will generate a sequence of 0->9\n#This seems weird, but will make sense later in the data structure lesson\n\nfor i in range(0,10):\n\tprint(i)\n\nx = int(input(\"Enter number: \"))\nfor i in range(0, x):\n\tprint(\"Hello World\")","sub_path":"for_loops.py","file_name":"for_loops.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"295129443","text":"from flappening.entities import Text\n\nfrom flappening.utils import avgScore\n\n\nclass Statistics:\n\n #\n #\n # -------- Init -----------\n #\n def __init__(self):\n super().__init__()\n\n self.bestScore = Text('', position=[550, 25])\n self.avgScore = Text('', position=[550, 50])\n self.playersAlive = Text('', position=[550, 75])\n self.generation = Text('', position=[550, 100])\n\n #\n #\n # -------- update -----------\n #\n def update(self, players, playersGarbage, gameIteration) -> None:\n\n if (len(players) >= 1):\n\n self.playersAlive.setContent('bird alive: ' + str(len(players)))\n\n self.bestScore.setContent('best score: ' +\n str(players[-1].getScore()))\n\n self.avgScore.setContent(\n 'avg score: ' + str(avgScore([*players, *playersGarbage])))\n\n self.generation.setContent('generation: ' + str(gameIteration))\n\n # -------- draw -----------\n #\n def draw(self) -> None:\n self.playersAlive.draw()\n self.bestScore.draw()\n self.avgScore.draw()\n self.generation.draw()\n","sub_path":"flappening/game/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"99783402","text":"'''\n$ python3 s52.py\n\n\n'''\n\nfrom s52_aux import *\nfrom Crypto.Cipher import AES\nfrom Crypto.Hash import MD5\nfrom Crypto.Util.Padding import pad\nfrom Crypto.Random import get_random_bytes as rand\n#from binascii import hexlify\n\ndef f(M, H = AES.new(b'YELLOW SUBMARINE', AES.MODE_ECB).encrypt(b'\\x34\\x12\\x80' + (b'\\x00' * 13))[:2] + (b'\\x80' + b'\\x00' * 13)):\n if len(H) < 16:\n H = pad(H, 16, 'iso7816')\n if len(M) % 16 != 0:\n M = pad(M, 16, 'iso7816')\n blocks = []\n for i in range(len(M) // 16):\n blocks.append(M[i*16:(i*16)+16])\n for block in blocks:\n aes = AES.new(H, AES.MODE_ECB)\n H = aes.encrypt(block)[:2] + b'\\x80' + (b'\\x00' * 13)\n return H[:2]\n\ndef g(M, H = AES.new(b'YELLOW SUBMARINE', AES.MODE_ECB).encrypt(b'\\x21\\x43\\x54\\x80' + (b'\\x00' * 12))[:3] + (b'\\x80' + b'\\x00' * 12)):\n if len(H) < 16:\n H = pad(H, 16, 'iso7816')\n if len(M) % 16 != 0:\n M = pad(M, 16, 'iso7816')\n blocks = []\n for i in range(len(M) // 16):\n blocks.append(M[i*16:(i*16)+16])\n for block in blocks:\n aes = AES.new(H, AES.MODE_ECB)\n H = aes.encrypt(block)[:3] + b'\\x80' + (b'\\x00' * 12)\n return H[:3]\n\ndef collide(M_chain = None):\n while True:\n sample0 = rand(16)\n sample1 = rand(16)\n if sample1 == sample0:\n continue\n if M_chain is not None:\n H_0 = f(sample0, M_chain)\n H_1 = f(sample1, M_chain)\n if H_0 == H_1:\n return [sample0, sample1, f(sample0, M_chain)]\n else:\n H_0 = f(sample0)\n H_1 = f(sample1)\n if H_0 == H_1:\n return [sample0, sample1, f(sample0)]\n\ndef main():\n collisions = []\n collisions.append(collide())\n\n print('pre')\n for b in range(12):\n print('b', b + 1)\n collisions.append(collide(collisions[-1][2]))\n\n g_calls = 0\n rev_lookup = {}\n for collision in coll4096(collisions):\n g_calls += 1\n lookup = g(collision)\n if lookup not in rev_lookup:\n rev_lookup[lookup] = collision\n else:\n print('found\\n', collision, '\\n', rev_lookup.get(lookup))\n print('4096-collision: g calls', g_calls, end='\\n\\n')\n exit()\n\n print('\\n\\n4096-collision: g calls', g_calls, end='\\n\\n')\n print('length', len(rev_lookup))\n\n\n g_calls = 0\n rev_lookup = {}\n for collision in coll8192(collisions):\n g_calls += 1\n lookup = g(collision)\n if lookup not in rev_lookup:\n rev_lookup[lookup] = collision\n else:\n print('found\\n', collision, '\\n', rev_lookup.get(lookup))\n print('8102-collision: g calls', g_calls)\n exit()\n \n print('\\n\\n8192-collision: g calls', g_calls, end='\\n\\n')\n print('length', len(rev_lookup))\n\n\n for collision in collisions:\n print(collision)\n print('\\n')\n\n print('failed to find g-collision.')\n\n# print('count', trampoline(collisions))\n\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"response/s52.py","file_name":"s52.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"576642754","text":"from multiprocessing import Process\nimport pulse as pul\nfrom flask import Flask, render_template\nimport csv\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n with open('csv/stats.csv', 'r') as f:\n dataReader = csv.reader(f)\n for row in dataReader:\n print(row)\n return render_template('index.html', row=row, dataReader=dataReader)\n\nif __name__ == \"__main__\":\n # サブプロセスを作成し定期実行スクリプトを開始します\n p = Process(target=pul.start)\n p.start()\n \n # Flaskhttpサーバー起動\n app.run(host='0.0.0.0', port=8000)\n print(\"c_start終了\")","sub_path":"cuous_start.py","file_name":"cuous_start.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"269930634","text":"from gameboard import *\ngrid = Grid(11, 11)\ngrid.set_grid()\ngrid.test()\n# print(grid.grid)\nfor y in range(len(grid.grid)):\n for x in range(len(grid.grid[0])):\n if grid.grid[x][y] == 10:\n print(\"* \", end=\"\")\n elif grid.grid[x][y] == 3:\n print(\"o \", end=\"\")\n elif x == 5 and y == 0:\n print(\"@ \", end=\"\")\n else:\n print(\". \", end=\"\")\n print()\ncell = grid.get_cell((5, 0))\ntail = grid.get_cell((4, 6))\nend = grid.get_cell((8, 8))\n\nprint(grid.count_reachable_area(cell))\n\nprint(grid.a_star(cell, [tail]))\n\n\nprint(\"check neighbor\")\nneighbors = grid.get_neighbors(cell)\ngrid.set_cell((1, 6), 0)\n# for y in range(len(grid.grid)):\n# for x in range(len(grid.grid[0])):\n# if grid.grid[x][y] == 10:\n# print(\"* \", end=\"\")\n# elif grid.grid[x][y] == 3:\n# print(\"o \", end=\"\")\n# elif x == 2 and y == 5:\n# print(\"@ \", end=\"\")\n# else:\n# print(\". \", end=\"\")\n# print()\nfor neighbor in neighbors:\n print(\"direction:\", cell.get_direction(neighbor))\n print(grid.count_reachable_area(neighbor))\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"216852423","text":"#!/usr/bin/python\n\nimport requests\nimport time\nimport sys\n\nvalues = {\n \"65-US Central\": \"US Central\",\n \"1-US East\": \"US East\",\n \"4-US West\": \"US West\",\n \"91-WINDFLIX US\": \"WINDFLIX US\",\n \"7-Canada East\": \"Canada East\",\n \"63-Canada West\": \"Canada West\",\n \"69-Austria\": \"Austria\",\n \"75-Belgium\": \"Belgium\",\n \"74-Bulgaria\": \"Bulgaria\",\n \"97-Croatia\": \"Croatia\",\n \"70-Czech Republic\": \"Czech Republic\",\n \"62-Denmark\": \"Denmark\",\n \"99-Estonia\": \"Estonia\",\n \"73-Finland\": \"Finland\",\n \"21-France\": \"France\",\n \"16-Germany\": \"Germany\",\n \"84-Greece\": \"Greece\",\n \"71-Hungary\": \"Hungary\",\n \"80-Iceland\": \"Iceland\",\n \"58-Ireland\": \"Ireland\",\n \"79-Israel\": \"Israel\",\n \"55-Italy\": \"Italy\",\n \"76-Latvia\": \"Latvia\",\n \"90-Lithuania\": \"Lithuania\",\n \"83-Moldova\": \"Moldova\",\n \"13-Netherlands\": \"Netherlands\",\n \"48-Norway\": \"Norway\",\n \"68-Poland\": \"Poland\",\n \"92-Portugal\": \"Portugal\",\n \"45-Romania\": \"Romania\",\n \"94-Slovakia\": \"Slovakia\",\n \"51-Spain\": \"Spain\",\n \"24-Sweden\": \"Sweden\",\n \"33-Switzerland\": \"Switzerland\",\n \"100-Tunisia\": \"Tunisia\",\n \"10-United Kingdom\": \"United Kingdom\",\n \"93-WINDFLIX UK\": \"WINDFLIX UK\",\n \"102-Albania\": \"Albania\",\n \"82-Azerbaijan\": \"Azerbaijan\",\n \"56-India\": \"India\",\n \"42-Russia\": \"Russia\",\n \"104-Serbia\": \"Serbia\",\n \"103-Slovenia\": \"Slovenia\",\n \"66-South Africa\": \"South Africa\",\n \"60-Turkey\": \"Turkey\",\n \"77-Ukraine\": \"Ukraine\",\n \"30-Australia\": \"Australia\",\n \"67-New Zealand\": \"New Zealand\",\n \"23-Hong Kong\": \"Hong Kong\",\n \"87-Indonesia\": \"Indonesia\",\n \"39-Japan\": \"Japan\",\n \"78-Malaysia\": \"Malaysia\",\n \"98-Philippines\": \"Philippines\",\n \"36-Singapore\": \"Singapore\",\n \"59-South Korea\": \"South Korea\",\n \"85-Thailand\": \"Thailand\",\n \"81-Vietnam\": \"Vietnam\",\n \"89-Argentina\": \"Argentina\",\n \"64-Brazil\": \"Brazil\",\n \"96-Colombia\": \"Colombia\",\n \"54-Mexico\": \"Mexico\"\n}\n\nheaders = {\n 'authority': 'nld.windscribe.com',\n 'cache-control': 'max-age=0',\n 'origin': 'https://nld.windscribe.com',\n 'upgrade-insecure-requests': '1',\n 'content-type': 'application/x-www-form-urlencoded',\n 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'referer': 'https://nld.windscribe.com/getconfig/openvpn',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'en-US,en;q=0.9',\n 'cookie': sys.argv[1]\n}\n\nfor key, value in values.items():\n for proto in [\"tcp\", \"udp\"]:\n data = {\n 'location': key,\n 'protocol': proto,\n 'port': '1194',\n 'cipher': 'cbc'\n }\n\n filename = \"{name}-{protocol}.ovpn\".format(\n name=value.replace(' ', '-'),\n protocol=proto\n )\n time.sleep(5)\n response = requests.post('https://nld.windscribe.com/getconfig/openvpn', headers=headers, data=data)\n f = open(filename, \"w\")\n f.write(response.text)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"239272040","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication\n\nfrom playground.mainwindow import MainWindow\nfrom playground.projectmanagerdialog import ProjectManagerDialog\n\n\ndef main():\n app = QApplication(sys.argv)\n app.setOrganizationName('cyberegoorg')\n app.setApplicationName('playground')\n\n pm = ProjectManagerDialog()\n ret = pm.exec()\n\n if ret == pm.Accepted:\n name, dir = pm.open_project_name, pm.open_project_dir\n\n mw = MainWindow()\n mw.show()\n mw.focusWidget()\n mw.open_project(name, dir)\n\n sys.exit(app.exec_())\n\n else:\n sys.exit(0)","sub_path":"playground/src/playground/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"402356882","text":"import numpy as np\nfrom numba import jit\n\n\ndef gradd(init, b, Q, tol=1e-10, iters=1000):\n\n old = init\n new = init + 10 + tol\n i = 0\n # print(\"a\",np.linalg.norm(old - new) > tol,(iters > i))\n\n while (np.linalg.norm(old - new) > tol) and (iters > i):\n if i != 0:\n old = new\n new = old - np.linalg.inv(Q) @ (Q @ old + b)\n i += 1\n # print(new)\n # print(\"a\",np.linalg.norm(old - new))\n if i < iters:\n return new\n else:\n return \"not finished\"\n\n\nQ = np.array([[3, 12], [0, 4]])\nb = np.array([3, 7])\nxo = np.array([10, 0])\n\n\nprint(gradd(xo, b, Q))\nprint(-np.linalg.inv(Q) @ b)\n","sub_path":"ProbSets/Math/Week 7/six.py","file_name":"six.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"532509297","text":"#!/usr/bin/python\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nfrom sys import argv\n\n\n### Llamar así\n# $ python plotter.py stat/YYMMDD_HHMM\n\nif len(argv) == 1:\n\tprint(\"Run ./plotter.py stat/YYMMDD_HHMM\")\n\texit(-1)\n\n# Directorio donde están los csv\npath=argv[1]\n\n# Tablas de datos\nmeasuredf = pd.read_csv(path+'/metrics_out.csv')\nperfdf = pd.read_csv(path+'/perf_out.csv')\n\n\n# Grafico Metricas / Flags\nplt.figure(figsize=(15,10))\nsns.violinplot(y='flags', x='Métricas',data=measuredf, linewidth=0.3)\nplt.xlim(0, None)\n# Guardar\nplt.savefig(path+'violinplot_flags.jpg')\nplt.show()\n\n\n# Mas graficos por aquí\n\"\"\" plt.figure(figsize=(8,8))\ndf = pd.read_csv(\"data_cambio_algoritmo.csv\")\nsns.set_style(\"whitegrid\")\nplot1 = sns.violinplot(x=df[\"Versión\"], y=df[\"Métrica\"])\nplot1.set(ylim=(0,None))\nplt.savefig(\"algorithm_comparison.jpg\")\n\nplt.figure(figsize=(15,15))\ndf = pd.read_csv(\"datos comp-flag.csv\")\nsns.set_style(\"whitegrid\")\nplot2 = sns.violinplot(y=df[\"COMP/OPT/FLAGS\"], x=df[\"METRICA\"], linewidth=0.2, scale=\"width\",palette=\"Set3\")\nplot2.set(xlim=(0,None))\nplt.savefig(\"comp-opt-flag_comparison.jpg\")\n\nplt.figure(figsize=(10,8))\ndf = pd.read_csv(\"comp_flags.csv\")\nsns.set_style(\"whitegrid\")\nplot3 = sns.boxplot(x=\"variable\",y=\"value\", data=pd.melt(df),palette=\"Set3\")\nplot3.set(ylim=(0,None))\nplot3.set(xlabel=\"Flags\")\nplot3.set(ylabel=\"Métrica\")\nplt.savefig(\"specific-flags_boxplot.jpg\")\n\nplt.figure(figsize=(15,8))\ndf = pd.read_csv(\"comp_flags_firaunroll.csv\")\nsns.set_style(\"whitegrid\")\nplot4 = sns.kdeplot(df[\"FIRA\"])\nplot4 = sns.kdeplot(df[\"FBLOCK\"])\nplot4 = sns.kdeplot(df[\"FUNROLL\"])\nplot4 = sns.kdeplot(df[\"FFASTMATH\"])\nplot4 = sns.kdeplot(df[\"FUNROLL_FIRA\"], shade=True)\nplot4.set(xlim=(0,None))\nplot4.set(xlabel=\"Métrica\")\nplot4.set(ylabel=\"Frecuencia\")\n\nplt.savefig(\"specific-flags_distribution.jpg\")\n\"\"\"\n\n","sub_path":"plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"483259890","text":"NAME = 'Extract UV Thumbnail'\nORDER = 1\nVALID = True\nTYPE = 'extractor'\nKEY = 'uv_thumbnail'\nOWNER = 'Subin Gopi'\nCOMMENTS = 'To create uv thumbnail file'\nVERSION = '0.0.0'\nMODIFIED = 'April 19, 2020'\n\n\ndef execute(output_path=None, **kwargs):\n import os\n from studio_usd_pipe.core import common\n from studio_usd_pipe.utils import maya_asset \n if not os.path.isfile(kwargs['thumbnail']):\n return False, [kwargs['thumbnail']], 'not found input thumbnail!...'\n ouput_image_path = os.path.join(\n output_path,\n '{}.png'.format(kwargs['caption'])\n )\n premission = common.data_exists(ouput_image_path, True)\n if not premission:\n return False, [ouput_image_path], 'not able to save thumbnail!...'\n thumbnail = maya_asset.create_thumbnail(kwargs['thumbnail'], ouput_image_path)\n return True, [thumbnail], 'success!...'\n","sub_path":"studio_usd_pipe/resource/push/maya/uv/extractor_thumbnail.py","file_name":"extractor_thumbnail.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"50792899","text":"from django.shortcuts import render, HttpResponseRedirect, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import SignUpForm, OrganizationForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import login, authenticate\nfrom .models import OrganizationCreator, Organization\n\nimport phonenumbers\n\n\ndef home(request):\n return render(request, 'core/index.html')\n\n\ndef signup(request):\n template = 'registration/signup.html'\n\n def post():\n data = {\n 'username': None,\n 'password': None,\n 'confirm_password': None,\n 'email': None,\n 'phone_number': None,\n 'first_name': None,\n 'last_name': None\n }\n form = SignUpForm(request.POST)\n\n if not form.is_valid():\n return render(request, template, {'form': form})\n\n for val in data:\n data[val] = form.cleaned_data[val]\n\n if data['password'] != data['confirm_password']:\n return render(request, template, {'form': form, 'error': {\n 'password': 'Passwords do not match'\n }})\n\n try:\n parsed_phone = phonenumbers.parse(data['phone_number'], \"KE\")\n if not phonenumbers.is_valid_number(parsed_phone):\n raise phonenumbers.NumberParseException(msg='Invalid phone number', error_type='Invalid phone')\n\n except phonenumbers.NumberParseException:\n return render(request, template, {'form': form, 'error': {\n 'phone_number': 'Enter a valid phone number'\n }})\n\n if not User.objects.filter(username=data['username']):\n user = User.objects.create(\n username=data['username'],\n first_name=data['first_name'],\n last_name=data['last_name'],\n email=data['email']\n )\n user.set_password(data['password'])\n user.save()\n OrganizationCreator.objects.create(user=user, phone=data['phone_number'])\n user = authenticate(username=data['username'], password=data['password'])\n login(request, user)\n return HttpResponseRedirect('/dashboard/')\n\n return render(request, template, {'form': form, 'error': {\n 'username': 'A user exists with that username'\n }})\n\n def get():\n form = SignUpForm()\n return render(request, template, {'form': form})\n\n if request.method == 'GET':\n return get()\n\n if request.method == 'POST':\n return post()\n\n\ndef student_signup(request):\n return render(request, 'registration/signup.html')\n\n\n@login_required()\ndef dashboard(request):\n context = {\n 'page_title': 'dashboard'\n }\n return render(request, 'core/dashboard/home.html', context)\n\n\n@login_required()\ndef add_organization(request):\n template = 'core/dashboard/add_organization.html'\n\n def get():\n form = OrganizationForm()\n context = {\n 'page_title': 'add organization',\n 'form': form\n }\n return render(request, template, context)\n\n def post():\n username = request.user.username\n\n data = {\n 'name': None,\n 'email': None,\n 'website': None,\n 'address': None,\n 'phone': None,\n }\n form = OrganizationForm(request.POST)\n\n if not form.is_valid():\n return render(request, template, {'form': form})\n\n for val in data:\n data[val] = form.cleaned_data[val]\n\n try:\n parsed_phone = phonenumbers.parse(data['phone'], \"KE\")\n if not phonenumbers.is_valid_number(parsed_phone):\n raise phonenumbers.NumberParseException(msg='Invalid phone number', error_type='Invalid phone')\n\n except phonenumbers.NumberParseException:\n return render(request, template, {'form': form, 'error': {\n 'phone': 'Enter a valid phone number'\n }})\n\n try:\n user = User.objects.get(username=username)\n creator = OrganizationCreator.objects.get(user=user)\n\n obj, created = Organization.objects.get_or_create(\n name=data['name'],\n email=data['email'],\n website=data['website'],\n address=data['address'],\n phone=data['phone'],\n created_by=creator,\n approved=True\n )\n if created is False:\n return render(request, template, {\n 'form': form,\n 'errors': 'An organization exists with the same entries'\n })\n\n return redirect('/organizations/view/')\n\n except User.DoesNotExist or OrganizationCreator.DoesNotExist:\n return render(request, template, {\n 'form': form,\n 'errors': 'User does not exist'\n })\n\n if request.method == 'GET':\n return get()\n\n if request.method == 'POST':\n return post()\n\n\n@login_required()\ndef get_organizations(request):\n user = User.objects.get(username=request.user.username)\n creator = OrganizationCreator.objects.get(user=user)\n organizations = Organization.objects.filter(created_by=creator)\n context = {\n 'page_title': 'View Organizations',\n 'organizations': organizations\n }\n return render(request, 'core/dashboard/view_organizations.html', context)\n\n\n@login_required()\ndef add_position(request):\n context = {\n 'page_title': 'add position'\n }\n return render(request, 'core/dashboard/add_position.html', context)\n\n\n@login_required()\ndef get_positions(request):\n context = {\n 'page_title': 'view positions'\n }\n return render(request, 'core/dashboard/view_positions.html', context)\n\n\n@login_required()\ndef applications(request):\n context = {\n 'page_title': 'applications'\n }\n return render(request, 'core/dashboard/applications.html', context)\n\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"605625606","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2017 SHIELD, UBIWHERE\n# ALL RIGHTS RESERVED.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Neither the name of the SHIELD, UBIWHERE nor the names of its\n# contributors may be used to endorse or promote products derived from this\n# software without specific prior written permission.\n#\n# This work has been performed in the framework of the SHIELD project,\n# funded by the European Commission under Grant number 700199 through the\n# Horizon 2020 program. The authors would like to acknowledge the contributions\n# of their colleagues of the SHIELD partner consortium (www.shield-h2020.eu).\n\n\nimport logging.config\n\nimport os\nimport yaml\n\n\ndef setup_logging(config_file='logging.yaml', default_level=logging.INFO, env_key='LOG_CFG'):\n \"\"\"\n Setup logging configuration\n\n \"\"\"\n\n path = config_file\n cfg_from_env = os.getenv(env_key, None)\n\n if cfg_from_env:\n path = cfg_from_env\n\n if os.path.exists(path):\n with open(path, 'rt') as f:\n config = yaml.safe_load(f.read())\n logging.config.dictConfig(config)\n else:\n logging.basicConfig(level=default_level)\n","sub_path":"src/utils/storeutils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"167411743","text":"\"\"\"\nHey Andrew! This is the assignment my friend Jake gave me. He already gave some sick feedback for it.\nSo whenever you finish, I'll send along my code and his notes. I'm not sure of the best way to organize\nour code on here yet, so I may end up switching some stuff around if we end up with a lot of files.\n\n\nASSIGNMENT 1 -- INTRO\n````````````````````````````````````````````````````````````````````````````````````````\n1. Print out a greeting to the user\n2. Make a function that adds two variables together and prints the output\n3. Break a given string into a character array, then print the letters in alphabetical order with no duplicates.\n In python, an 'array' is generally a list.\n\"\"\"\n\n####################################\n######### ANDREW'S CODE ############\n####################################\n\nname = input(\"Hello User, what is your name? \")\nprint(\"Welcome\", name)\n\ndef assignment():\n dna = \"tcgcgatcgc\"\n dna2 = \"tggggcatgc\"\n\n recombination = dna + dna2\n lst = list(recombination)\n print(lst)\n\nassignment()","sub_path":"andrew_assignment_1.py","file_name":"andrew_assignment_1.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"227082219","text":"from .include import *\n\nimport tensorflow as tf\ntf.get_logger().setLevel(\"ERROR\")\n\nclass Conv3d:\n \"\"\"\n 3d convolution layer.\n \"\"\"\n def __init__(self, filters=32, kernel_size=3, stride=1, \n padding=\"SAME\", name=\"Conv3d\",\n activation=tf.nn.relu, \n regularizer=tf.contrib.layers.l2_regularizer(scale=1.),\n use_batch_norm=True):\n self.name = name\n self.filters = filters\n self.kernel_size = kernel_size\n self.stride = stride\n self.padding = padding\n self.activation = activation\n self.regularizer = regularizer\n self.use_batch_norm = use_batch_norm\n\n def forward(self, input, training=False, **args):\n with tf.variable_scope(self.name):\n weights = tf.get_variable(name=\"w\", \n shape=(self.kernel_size, self.kernel_size, self.kernel_size, input.shape[-1], self.filters),\n dtype=tf.float32, initializer=tf.contrib.layers.xavier_initializer(), \n regularizer=self.regularizer)\n x = tf.nn.conv3d(input, weights, strides=[1, self.stride, self.stride, self.stride, 1],\n padding=self.padding, name=\"conv\")\n if self.use_batch_norm:\n x = tf.layers.batch_normalization(x, name=\"bn\", training=training)\n if self.activation != None:\n x = self.activation(x)\n return x\n\n def __call__(self, input, training=False, **args):\n return self.forward(input, training=training, **args)\n\nclass Pool3d:\n def __init__(self, pool_size=2, stride=2, padding=\"SAME\", name=\"Pool3d\", **args):\n self.name = name\n self.pool_size = pool_size\n self.stride = stride\n self.padding = padding\n\n def forward(self, input, **args):\n with tf.variable_scope(self.name):\n pool = tf.layers.max_pooling3d(input, \n pool_size=[self.pool_size, self.pool_size, self.pool_size],\n strides=[self.stride, self.stride, self.stride],\n padding=self.padding, name=\"pool\")\n return pool\n\n def __call__(self, input, **args):\n return self.forward(input, **args)\n\nclass ConvBlock:\n \"\"\"\n Convolution block layer: (Conv3d, Conv3d, Conv3dPool).\n \"\"\"\n def __init__(self, filters=32, name=\"ConvBlock\", **args):\n self.name = name\n self.filters = filters\n self.conv1 = Conv3d(filters=self.filters, name=\"conv1\", **args)\n self.conv2 = Conv3d(filters=self.filters, name=\"conv2\", **args)\n self.pool = Conv3d(filters=self.filters, stride=2, name=\"pool\", **args)\n\n def forward(self, input, **args):\n with tf.variable_scope(self.name):\n x = self.conv1(input, **args)\n x = self.conv2(x, **args)\n x = self.pool(x, **args)\n return x\n\n def __call__(self, input, **args):\n return self.forward(input, **args)\n\nclass PredictionActivation:\n \"\"\"\n Final activation layer: \n sigmoid function is applied to [:, :, :, :, 0] confidence of model output;\n prediction coordinates are renormalized from cell local coordinates to absolute:\n sigmoid function is applied and then added to cell indexes.\n \"\"\"\n def __init__(self, name=\"PredictionActivation\"):\n self.name = name\n\n def forward(self, input, name=\"prediction\", **args):\n with tf.variable_scope(self.name):\n confidences = input[:, :, :, :, 0]\n centers = input[:, :, :, :, 1:4]\n confidences = tf.reshape(confidences, \n [-1, input.shape[1], input.shape[2], input.shape[3], 1])\n confidences = tf.sigmoid(confidences, name=\"confidences\")\n indices = np.zeros((input.shape[1], input.shape[2], input.shape[3], 3))\n for i in range(input.shape[1]):\n for j in range(input.shape[2]):\n for k in range(input.shape[3]):\n indices[i, j, k, :] = [i, j, k]\n centers = tf.add(tf.nn.sigmoid(centers), indices, name=\"centers\")\n out = tf.concat([confidences, centers], axis=-1, name=name)\n return out\n\n def __call__(self, input, **args):\n return self.forward(input, **args)\n\nclass Loss:\n \"\"\"\n Cost function.\n \"\"\"\n def __init__(self, cost_lambda=5.):\n self.cost_lambda = cost_lambda\n\n def position_loss(self, target, prediction, sample_weight=1.):\n centers_target = target[:, :, :, :, 1:4]\n confidence_target = target[:, :, :, :, 0]\n centers_prediction = prediction[:, :, :, :, 1:4]\n\n pos_cost = tf.reduce_sum(tf.square(centers_target - centers_prediction), axis=-1)\n pos_cost = tf.multiply(pos_cost, confidence_target)\n pos_cost = tf.reduce_sum(pos_cost, axis=[1, 2, 3])\n\n pos_cost = tf.scalar_mul(self.cost_lambda, pos_cost)\n pos_cost = tf.multiply(pos_cost, sample_weight)\n\n return tf.reduce_mean(pos_cost, name=\"position_cost\")\n\n def confidence_loss(self, target, prediction, sample_weight=1.):\n confidence_target = target[:, :, :, :, 0]\n confidence_prediction = prediction[:, :, :, :, 0]\n confidence_cost = tf.square(confidence_target - confidence_prediction)\n confidence_cost = tf.reduce_sum(confidence_cost, axis=[1, 2, 3])\n\n confidence_cost = tf.multiply(confidence_cost, sample_weight)\n return tf.reduce_mean(confidence_cost, name=\"confidence_cost\")\n\n def __call__(self, target, prediction, sample_weight=1.):\n cost = tf.add(\n self.position_loss(target, prediction, sample_weight),\n self.confidence_loss(target, prediction, sample_weight),\n name=\"prediction_cost\")\n return cost\n\nclass Model:\n def __init__(self, \n input_shape=(None, default_cube_size, default_cube_size, default_cube_size, default_channel_num),\n cell_size=default_cell_size):\n \n self.input_shape = input_shape\n self.cell_size = cell_size\n self.output_shape = (None, \n input_shape[1] // cell_size, input_shape[2] // cell_size, input_shape[3] // cell_size, 4)\n\n # number of size downsampling depends on cube_size/cell_size ratio\n pooling_num = int(math.log2(cell_size))\n args = {}\n\n # if input grid size is:\n # 64x64x64x11\n self.layers = [\n Conv3d(32, name=\"Conv1\", **args),\n Conv3d(32, stride=2, name=\"Pool1\", **args)]\n # 64x64x64x32\n # 32x32x32x32\n\n if pooling_num - 1 == 1:\n self.layers += [ConvBlock(64, **args)]\n elif pooling_num - 1 == 2:\n self.layers += [\n ConvBlock(32, name=\"ConvBlock1\", **args), \n ConvBlock(64, name=\"ConvBlock2\", **args)]\n # 16x16x16x32\n # 8x8x8x64\n elif pooling_num - 1 == 3:\n self.layers += [\n ConvBlock(32, name=\"ConvBlock1\", **args),\n ConvBlock(64, name=\"ConvBlock2\", **args),\n ConvBlock(64, name=\"ConvBlock3\", **args)]\n \n self.layers += [\n Conv3d(128, name=\"ConvFinal\", **args),\n Conv3d(4, activation=None, use_batch_norm=False, **args),\n ]\n # 8x8x8x128\n # 8x8x8x4\n self.prediction_activation = PredictionActivation()\n\n def build(self, optimizer=tf.train.AdamOptimizer, \n cost_lambda=default_params[\"cost_lambda\"],\n cost_gamma=default_params[\"cost_gamma\"]):\n \"\"\"\n Builds computation graph.\n Args:\n optimizer: tf.train.Optimizer; default=tf.train.AdamOptimizer;\n cost_lambda: float; default=5.;\n parameter lambda for cost function;\n cost_gamma: float; default=1e-5;\n parameter gamma for regularization;\n \"\"\"\n\n # placeholder for input grids\n self.X = tf.placeholder(tf.float32, shape=self.input_shape, name=\"input_grid\")\n # placeholder for target labels\n self.Y = tf.placeholder(tf.float32, shape=self.output_shape, name=\"target\")\n # placeholder for boolean for batch norm \n self.training = tf.placeholder(tf.bool, (), name=\"training\")\n \n x = self.X\n # forward\n for l in self.layers:\n x = l(x, training=self.training)\n # output activation function\n self.output = self.prediction_activation(x, name=\"output\")\n\n # placeholder for learning_rate\n self.learning_rate = tf.placeholder(tf.float32, (), name=\"lrate_placeholder\")\n # not used\n self.sample_weight = tf.placeholder(tf.float32, shape=(None), name=\"sample_weight\")\n\n # loss function\n self.loss = Loss(cost_lambda=cost_lambda)\n # regularization terms\n reg_variables = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n reg_loss = cost_gamma * tf.reduce_sum(reg_variables, name=\"reg_cost\")\n # losses for prediction coordinates and confidence\n self.pos_loss = self.loss.position_loss(self.Y, self.output, self.sample_weight)\n self.conf_loss = self.loss.confidence_loss(self.Y, self.output, self.sample_weight)\n self.total_loss = tf.add_n([reg_loss, self.pos_loss, self.conf_loss], name=\"total_cost\")\n \n # optimizer\n self.optimizer = optimizer(learning_rate=self.learning_rate, name=\"optimizer\")\n # applying gradients\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.train_op = self.optimizer.minimize(self.total_loss)\n # weights saver\n self.saver = tf.train.Saver()\n self.saver_short = None\n self.saver_none = tf.train.Saver(max_to_keep=None)\n\n\n def save(self, path, full=True, step=None):\n \"\"\"\n Saves weights.\n Args:\n path: str; \n path to output file;\n full: bool; default=True;\n if True gradients are saved;\n step: int; default=None;\n global_step for saver;\n \"\"\"\n if full:\n if step == None:\n self.saver_none.save(self.sess, path)\n else:\n self.saver.save(self.sess, path, global_step=step)\n else:\n if self.saver_short == None:\n var_list = []\n for v in tf.global_variables():\n if \"Adam\" not in v.name:\n var_list.append(v)\n self.saver_short = tf.train.Saver(var_list)\n self.saver_short.save(self.sess, path, global_step=step)\n\n def load(self, path, full=False):\n \"\"\"\n Loads graph and weights from file.\n Args:\n path: str;\n filename prefix for .meta file;\n full: bool; default=False;\n if True, gradients and cost tensors are loaded as well.\n \"\"\"\n self.saver = tf.train.import_meta_graph(path + \".meta\")\n self.saver.restore(self.sess, path)\n self.saver_short = None\n self.saver_none = tf.train.Saver(max_to_keep=None)\n graph = tf.get_default_graph()\n self.X = graph.get_tensor_by_name(\"input_grid:0\")\n self.Y = graph.get_tensor_by_name(\"target:0\")\n self.training = graph.get_tensor_by_name(\"training:0\")\n self.output = graph.get_tensor_by_name(\"output:0\")\n if full:\n self.pos_loss = graph.get_tensor_by_name(\"position_cost:0\")\n self.conf_loss = graph.get_tensor_by_name(\"confidence_cost:0\")\n self.total_loss = graph.get_tensor_by_name(\"total_cost:0\")\n self.learning_rate = graph.get_tensor_by_name(\"lrate_placeholder:0\")\n self.sample_weight = graph.get_tensor_by_name(\"sample_weight:0\")\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n self.train_op = graph.get_operation_by_name(\"optimizer\")\n \n\n def init_session(self, gpus=\"\", cpu_only=False):\n \"\"\"\n Initializes tensorflow session.\n Args:\n gpus: str; default=\"\";\n available gpus;\n cpu_only: bool; default=False;\n if True, session will be ran on cpu only.\n \"\"\"\n if cpu_only:\n config = tf.ConfigProto(device_count={'GPU': 0})\n else:\n gpu_options = tf.GPUOptions(visible_device_list=gpus)\n config = tf.ConfigProto(gpu_options=gpu_options)\n self.sess = tf.Session(config=config)\n self.sess.run(tf.global_variables_initializer())\n\n def train_step(self, grids, targets, sample_weight=[], \n minibatch_size=default_params[\"minibatch_size\"], learning_rate=1e-3):\n \"\"\"\n Single train step of model.\n\n Args:\n grids: np.array of shape (n_grids, cube_size, cube_size, cube_size, n_channels);\n input cubic grids for model forward pass;\n targets: np.array of shape (n_grids, N, N, N, 4) where N is the number of cells;\n true target labels for loss calculation;\n sample_weight: not used;\n minibatch_size: int; default=32;\n minibatch size, number of grids in single forward pass; \n n_grids will be splitted to these minibatches;\n learning_rate: float; default=1e-3;\n optimizer learning rate.\n\n Returns: (predictions, [pos_loss, conf_loss, total_loss]):\n predictions: np.array of shape (n_grids, N, N, N, 4);\n model output for each grid;\n pos_loss: float; \n loss value for predictions coordinates;\n conf_loss: float;\n loss value for predictions confidence values;\n total_loss: float;\n total loss value = pos_loss + conf_loss + reg_loss.\n \"\"\"\n\n if len(sample_weight) == 0:\n sample_weight = np.ones((len(targets)))\n prediction_list, pos_loss, conf_loss, total_loss = [], 0., 0., 0.\n for minibatch_index in range(math.ceil(len(grids) / minibatch_size)):\n i_start = minibatch_index * minibatch_size\n sw = sample_weight[i_start : i_start + minibatch_size]\n\n res = self.sess.run([self.train_op, self.output, self.pos_loss, self.conf_loss, self.total_loss],\n feed_dict={self.X : grids[i_start : i_start + minibatch_size],\n self.Y : targets[i_start : i_start + minibatch_size],\n self.sample_weight : sw, self.learning_rate : learning_rate,\n self.training : True})\n prediction_list.append(res[1])\n pos_loss += res[2] * np.sum(sw)\n conf_loss += res[3] * np.sum(sw)\n total_loss += res[4] * np.sum(sw)\n pos_loss /= np.sum(sample_weight)\n conf_loss /= np.sum(sample_weight)\n total_loss /= np.sum(sample_weight)\n return np.concatenate(prediction_list), [pos_loss, conf_loss, total_loss]\n\n def predict(self, grids, minibatch_size=default_params[\"minibatch_size\"]):\n \"\"\"\n Retrieving predictions for input grids.\n\n Args:\n grids: np.array of shape (n_grids, cube_size, cube_size, cube_size, n_channels);\n input cubic grids;\n minibatch_size: int; default=32;\n minibatch size, number of grids in single forward pass; \n n_grids will be splitted to these minibatches.\n \n Returns:\n predictions: np.array of shape (n_grids, N, N, N, 4);\n model output for each grid.\n \"\"\"\n prediction_list = []\n for minibatch_index in range(math.ceil(len(grids) / minibatch_size)):\n i_start = minibatch_index * minibatch_size\n\n predictions = self.sess.run(self.output, \n feed_dict={\n self.X : grids[i_start : i_start + minibatch_size],\n self.training : False})\n prediction_list.append(predictions)\n if len(prediction_list) > 0:\n return np.concatenate(prediction_list)\n else:\n return np.array([])\n\n def __call__(self, grids, **args):\n return self.predict(grids, **args)","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":16320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"431296892","text":"import sqlite3\r\nimport csv\r\n\r\nclass database:\r\n\r\n def __init__(self, path):\r\n self.db = sqlite3.connect(path, check_same_thread=False)\r\n\r\n\r\n def InsertRow(self, tablename, row):\r\n cursor2 = self.db.cursor()\r\n cursor2.execute(f'insert into {tablename} values (?,?,?,?,?,?)', (row[0], row[1], row[2], row[3], row[4], row[5]))\r\n self.db.commit()\r\n return\r\n\r\n def GetRows(self, tablename, query_param1, query_param2):\r\n cursor2 = self.db.cursor()\r\n cursor2.execute(f'SELECT * FROM {tablename} WHERE {query_param1} AND {query_param2}')\r\n rows = cursor2.fetchall()\r\n return rows\r\n\r\n\r\n def ExportCSV(self, tablename):\r\n csv_cursor = self.db.cursor()\r\n csv_cursor.execute(f'SELECT * FROM {tablename}')\r\n with open('export.csv', 'w', newline='') as out_csv_file:\r\n csv_out = csv.writer(out_csv_file)\r\n # write header\r\n csv_out.writerow([d[0] for d in csv_cursor.description])\r\n # write data\r\n for result in csv_cursor:\r\n csv_out.writerow(result)\r\n\r\n out_csv_file.close()\r\n return out_csv_file","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"285708740","text":"import logging\nimport os\nimport StringIO\nimport xml.sax\n\nimport requests\n\nlogging.basicConfig(format='[%(asctime)s] [%(process)d] [%(name)s] '\n '[%(levelname)s] %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S +0000', level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\n_REQUIRED_OPTS = ['WATCHES_URL', 'EVECENTRAL_URL', 'SYSTEM_ID', 'PRICES_URL']\n\n\ndef system_id():\n return os.environ.get('SYSTEM_ID')\n\n\nclass EveCentralMarketStatHandler(xml.sax.ContentHandler):\n def __init__(self):\n xml.sax.ContentHandler.__init__(self)\n # Initialize the flag to false\n self.mode = None\n self.capturing = None\n self.data = {'buy': {}, 'sell': {}, 'system_id': system_id()}\n\n def startElement(self, name, attrs):\n if name in ['buy', 'sell']:\n self.mode = name\n if self.mode and name in ['min', 'max', 'avg', 'median', 'stddev']:\n self.capturing = name\n self.data[self.mode][name] = ''\n\n def endElement(self, name):\n if name in ['buy', 'sell']:\n self.mode = None\n if self.mode and name in ['min', 'max', 'avg', 'median', 'stddev']:\n self.capturing = None\n\n def characters(self, content):\n if self.mode and self.capturing:\n partial = self.data[self.mode][self.capturing]\n self.data[self.mode][self.capturing] = partial + content\n\n def data(self):\n return self.data\n\n\ndef verify_parameters():\n missing = [n for n in _REQUIRED_OPTS if not os.environ.get(n, None)]\n if len(missing) > 0:\n logging.critical('Missing options in environment: %s' % missing)\n exit(1)\n\n\ndef watched_ids(http):\n try:\n wurl = os.environ.get('WATCHES_URL')\n w = http.get(url=wurl)\n except Exception as e:\n logger.exception(e)\n exit(1)\n return [watched['id'] for watched in w.json()]\n\n\ndef record_price(by_id, payload, http):\n try:\n purl = '/'.join([os.environ.get('PRICES_URL'), str(by_id)])\n logger.info('recording price')\n http.post(url=purl, json=payload)\n except Exception as e:\n logger.exception(e)\n exit(1)\n\n\ndef translate(content):\n try:\n parser = xml.sax.make_parser()\n handler = EveCentralMarketStatHandler()\n parser.setContentHandler(handler)\n source = StringIO.StringIO(content)\n logger.info('translating price')\n parser.parse(source)\n payload = handler.data\n except Exception as e:\n logger.exception(e)\n exit(1)\n return payload\n\n\ndef fetch_price(by_id, http):\n try:\n params = {'typeid': by_id, 'usesystem': system_id()}\n ecurl = os.environ.get('EVECENTRAL_URL')\n logger.info('fetching price')\n ec_body = http.get(url=ecurl, params=params).content\n except Exception as e:\n logger.exception(e)\n exit(1)\n return ec_body\n\n\ndef main():\n verify_parameters()\n headers = {'user-agent': 'github.com/eve-basil/checker[0.1.0-dev]'}\n\n session = requests.Session()\n session.headers.update(headers)\n\n for by_id in watched_ids(session):\n logger.info('checking price for type_id %s', by_id)\n ec_body = fetch_price(by_id, session)\n payload = translate(ec_body)\n record_price(by_id, payload, session)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"checker.py","file_name":"checker.py","file_ext":"py","file_size_in_byte":3370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"215049109","text":"from batou.utils import cmd\nfrom batou import output\nimport argparse\nimport os.path\nimport pkg_resources\nimport shutil\n\n\ndef main(destination, **kw):\n develop = os.environ['BATOU_DEVELOP']\n if develop:\n output.annotate(\n 'Initializing with a development copy of batou will cause your '\n 'project to have a reference outside its repository. '\n 'Use at your own risk. ')\n develop = os.path.abspath(develop)\n print(('Bootstrapping new batou project in {}. This can take a while.'\n .format(os.path.abspath(destination))))\n if os.path.exists(destination):\n print(('{} exists already. Not copying template structure.'.format(\n destination)))\n os.chdir(destination)\n else:\n source = os.path.dirname(__file__) + '/init-template'\n shutil.copytree(source, destination)\n os.chdir(destination)\n cmd('hg -y init .')\n for key in list(os.environ):\n if key.startswith('BATOU_'):\n del os.environ[key]\n cmd('./batou --help')\n\n\ndef console_main():\n parser = argparse.ArgumentParser(\n description=\"\"\"\\\nInitialize batou project in the given directory. If the given directory does\nnot exist, it will be created.\n\nIf no directory is given, the current directory is used.\n\"\"\")\n parser.add_argument('destination')\n\n os.environ['BATOU_VERSION'] = pkg_resources.require('batou')[0].version\n os.environ['BATOU_DEVELOP'] = ''\n args = parser.parse_args()\n main(args.destination)\n","sub_path":"src/batou/init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"408148486","text":"import unittest\n\nfrom postpy.admin import (get_user_tables, get_primary_keys,\n get_column_metadata, install_extensions,\n reflect_table, reset)\nfrom postpy.base import Database, Column, PrimaryKey, Table\nfrom postpy.connections import connect\nfrom postpy.fixtures import PostgreSQLFixture\n\n\nclass TestTableStats(PostgreSQLFixture, unittest.TestCase):\n\n @classmethod\n def _prep(cls):\n cls.conn.autocommit = True\n cls.schema = 'stats_test'\n cls.table = 'admin_table_tests'\n create_table_statement = \"\"\"\\\n CREATE TABLE {schema}.{table} (\n mycol CHAR(2),\n mycol2 CHAR(3) NULL,\n PRIMARY KEY (mycol));\"\"\".format(schema=cls.schema,\n table=cls.table)\n\n with cls.conn.cursor() as cursor:\n cursor.execute('CREATE SCHEMA {};'.format(cls.schema))\n cursor.execute(create_table_statement)\n\n def test_get_user_tables(self):\n\n expected = (self.schema, self.table)\n result = get_user_tables(self.conn)\n\n self.assertIn(expected, result)\n\n def test_get_column_meta_data(self):\n expected = [\n {'name': 'mycol',\n 'data_type': 'character(2)',\n 'nullable': False},\n {'name': 'mycol2',\n 'data_type': 'character(3)',\n 'nullable': True}\n ]\n result = list(\n get_column_metadata(self.conn, self.table, schema=self.schema)\n )\n\n self.assertEqual(expected, result)\n\n def test_get_primary_keys(self):\n expected = ['mycol']\n result = list(get_primary_keys(self.conn, self.table, self.schema))\n\n self.assertEqual(expected, result)\n\n def test_reflect_table(self):\n columns = [Column('mycol', data_type='character(2)', nullable=False),\n Column('mycol2', data_type='character(3)', nullable=True)]\n primary_key = PrimaryKey(['mycol'])\n\n expected = Table(self.table, columns, primary_key, schema=self.schema)\n result = reflect_table(self.conn, self.table, self.schema)\n\n self.assertEqual(expected, result)\n\n @classmethod\n def _clean(cls):\n statement = 'DROP SCHEMA IF EXISTS {} CASCADE;'.format(cls.schema)\n\n with cls.conn.cursor() as cursor:\n cursor.execute(statement)\n\n\nclass TestDatabase(unittest.TestCase):\n\n def setUp(self):\n self.db = Database('reset_db_test')\n self.db_query = \"\"\"SELECT datname\n FROM pg_database\n WHERE datistemplate=false;\"\"\"\n self.conn = connect()\n self.conn.autocommit = True\n\n def test_reset(self):\n reset(self.db.name)\n\n with self.conn.cursor() as cursor:\n cursor.execute(self.db_query)\n result = [item[0] for item in cursor.fetchall()]\n\n self.assertIn(self.db.name, result)\n\n def tearDown(self):\n with self.conn.cursor() as cursor:\n cursor.execute(self.db.drop_statement())\n\n self.conn.close()\n\n\nclass TestExtensions(PostgreSQLFixture, unittest.TestCase):\n @classmethod\n def _prep(cls):\n cls.pg_extension = 'sslinfo'\n cls.conn.autocommit = True\n\n def test_install_extensions(self):\n\n install_extensions([self.pg_extension])\n\n @classmethod\n def _clean(cls):\n statement = 'DROP EXTENSION IF EXISTS {};'.format(cls.pg_extension)\n\n with cls.conn.cursor() as cursor:\n cursor.execute(statement)\n","sub_path":"tests/test_admin.py","file_name":"test_admin.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"69200702","text":"# -*- coding: utf-8 -*-\n# flake8: noqa\n# pylint: skip-file\n\"\"\"\nnose tests\n\"\"\"\n\nimport os\n\nfrom .. import _merge as merge\nfrom nose.tools import assert_equals\n\nWINDOWS = os.name == 'nt'\n\n\ndef test_vias_parallel():\n \"\"\"Test 'vias' parallel operation.\"\"\"\n if WINDOWS:\n # appveyor doesn't allow!\n return\n assert_equals(len(repr(merge.query('9783319020983', 'parallel'))) > 100,\n True)\n\ndef test_vias_multi():\n \"\"\"Test 'vias' multi operation.\"\"\"\n if WINDOWS:\n # appveyor doesn't allow!\n return\n assert_equals(len(repr(merge.query('9783319020983', 'multi'))) > 100, True)\n\ndef test_vias_serial():\n \"\"\"Test 'vias' serial operation.\"\"\"\n if WINDOWS:\n # appveyor doesn't allow!\n return\n assert_equals(len(repr(merge.query('9783319020983', 'serial'))) > 100,\n True)\n\ndef test_vias_cache_cleanning():\n \"\"\"Test 'vias' cache cleanning for serial.\"\"\"\n # test if the secondary cache (cache in vias) does clears... sequentially\n assert_equals(len(repr(merge.query('9781680450260', 'serial'))) < 20, True) # NO METADATA\n assert_equals(len(repr(merge.query('9780521581783', 'serial'))) > 100,\n True)\n assert_equals(len(repr(merge.query('9781680450260', 'serial'))) < 20, True) # NO METADATA\n","sub_path":"env/Lib/site-packages/isbnlib/test/test_vias.py","file_name":"test_vias.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"603837514","text":"if __name__ == '__main__':\n L = int(input())\n R = int(input())\n left = min(L,R)\n right = max(L, R)\n max_xor = 0\n for i in range(left, right + 1):\n for j in range(i, right + 1):\n max_xor = max(max_xor, i ^ j)\n print(max_xor)\n","sub_path":"HackerRank/Algorithms/BitManipulation/maximizeXOR/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"380134066","text":"from reading import *\n\n# Below, write:\n# *The cartesian_product function\n# *All other functions and helper functions\n# *Main code that obtains queries from the keyboard,\n# processes them, and uses the below function to output csv results\n\n\n# helper function for outputting tables\n\ndef num_rows(table):\n '''(table) -> Integer\n Get the number of rows of a table.\n '''\n one_column = list(table.keys())[0]\n rows = table[one_column]\n return len(rows)\n\n\ndef print_csv(table):\n '''(table) -> NoneType\n Print a representation of table.\n '''\n columns = list(table.keys())\n print(','.join(columns))\n rows = num_rows(table)\n for i in range(rows):\n cur_column = []\n for column in columns:\n cur_column.append(table[column][i])\n print(','.join(cur_column))\n\n\ndef cartesian_product(tab_1, tab_2):\n '''(table, table) -> table\n Merge the two table into a table that cartesian product.\n '''\n table = {}\n column_1_list = list(tab_1.keys())\n column_2_list = list(tab_2.keys())\n for column in column_1_list + column_2_list:\n table[column] = []\n\n for row_1 in range(num_rows(tab_1)):\n for row_2 in range(num_rows(tab_2)):\n for column_1 in column_1_list:\n value = tab_1[column_1][row_1]\n table[column_1].append(value)\n for column_2 in column_2_list:\n value = tab_2[column_2][row_2]\n table[column_2].append(value)\n\n return table\n\n\ndef process_from(from_str, database):\n '''(string, database) -> table\n Process the \"from string\" to get a result table.\n '''\n from_table_list = from_str.split(\",\")\n query_table = None\n for from_table in from_table_list:\n temp_table = database[from_table]\n if query_table:\n query_table = cartesian_product(query_table, temp_table)\n else:\n query_table = temp_table\n\n return query_table\n\ndef process_where(where_str, query_table):\n '''(string, table) -> table\n Process the \"where string\" to get a result table.\n '''\n if where_str:\n where_list = where_str.split(\",\")\n for optional in where_list:\n\n temp_table = {}\n column_list = query_table.keys()\n for column in column_list:\n temp_table[column] = []\n\n if \"=\" in optional:\n col_1, col_2 = optional.split(\"=\")\n optional_flag = \"=\"\n elif \">\" in optional:\n col_1, col_2 = optional.split(\">\")\n optional_flag = \">\"\n elif \"<\" in optional:\n col_1, col_2 = optional.split(\"<\")\n optional_flag = \"<\"\n\n for i in range(num_rows(query_table)):\n value_1 = query_table[col_1][i]\n if \"'\" in col_2:\n value_2 = col_2[1:-1]\n else:\n value_2 = query_table[col_2][i]\n\n if optional_flag == \"=\" and value_1 == value_2:\n match_flag = True\n elif optional_flag == \">\" and value_1 > value_2:\n match_flag = True\n elif optional_flag == \"<\" and value_1 < value_2:\n match_flag = True\n else:\n match_flag = False\n\n if match_flag:\n for column in column_list:\n temp_table[column].append(query_table[column][i])\n\n query_table = temp_table\n\n return query_table\n\n\ndef process_select(select_str, query_table):\n '''(string, table) -> table\n Process the \"select string\" to get a result table.\n '''\n if select_str == \"*\":\n return query_table\n\n select_list = select_str.split(\",\")\n select_table = {}\n for select in select_list:\n select_table[select] = query_table[select]\n\n return select_table\n\n\ndef process_query(query, database):\n '''(string, database) -> table\n Process the \"query string\" to get the final result table.\n '''\n\n from_where_str = query.split(\"from \")[1]\n from_str = from_where_str.split(\" where \")[0]\n query_table = process_from(from_str, database)\n\n if \"where\" in query:\n where_str = from_where_str.split(\" where \")[1]\n else:\n where_str = \"\"\n query_table = process_where(where_str, query_table)\n\n select_str = query.split(\" from \")[0]\n select_str = select_str.replace(\"select \", \"\")\n query_table = process_select(select_str, query_table)\n\n return query_table\n\n\n\nif(__name__ == \"__main__\"):\n database = read_database()\n while True:\n query = input(\"Enter a SQuEaL query, or a blank line to exit:\")\n if query:\n print_csv(process_query(query, database))\n else:\n break","sub_path":"starter/4/squeal.py","file_name":"squeal.py","file_ext":"py","file_size_in_byte":4790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"301125945","text":"import datetime\nimport os\nimport torch\nimport time\nimport timeit\nimport shutil\nimport torchvision.models as models\nimport numpy as np\nimport torchvision.transforms as standard_transforms\nimport torchvision.utils as vutils\nimport My_train.joint_transforms as joint_transforms\nimport My_train.transforms as extended_transforms\nimport My_train.color_transforms as Colorjitter\n# import My_train.size_transforms as Mytransforms\nfrom My_train import size_transforms as Mytransforms\nimport argparse\nimport torch.nn.functional\nimport torch\n\nfrom PIL import Image\nfrom cfgs import DenseASPP121\nfrom cfgs import DenseASPP161\nfrom tensorboardX import SummaryWriter\nfrom torch import optim\nfrom torch.autograd import Variable\nfrom torch.backends import cudnn\nfrom torch.utils.data import DataLoader\nfrom My_train import segmentation_dataloader\n\n# from models.DenseASPP_v3 import *\n# from models.DenseASPP_v2 import *\nfrom models.DenseASPP_boundary_depthwise import *\n\nfrom My_train.misc import check_mkdir, evaluate, AverageMeter, compute_mean_iou\nfrom collections import OrderedDict\n\nparser = argparse.ArgumentParser(description='DenseASPP training')\nparser.add_argument('--input_height', type=int, help='input height', default=512)\nparser.add_argument('--input_width', type=int, help='input width', default=512)\nparser.add_argument('--train_batch_size', type=int, help='train batch size', default=4)\nparser.add_argument('--val_batch_size', type=int, help='validation batch size', default=4)\nparser.add_argument('--num_threads', type=int, help='number of threads to use for data loading', default=12)\nparser.add_argument('--learning_rate', type=float, help='initial learning rate', default=3e-4)\nparser.add_argument('--num_epochs', type=int, help='number of epochs', default=80)\nparser.add_argument('--weight_decay', type=float, help='weight decay', default=1e-5)\nparser.add_argument('--print_frequency', type=int, help='print frequency', default=10)\nparser.add_argument('--val_save_to_img_file', type=bool, help='save validation image file', default=True)\nparser.add_argument('--val_img_sample_rate', type=float, help='randomly sample some validation results to display', default=0.05)\nparser.add_argument('--checkpoint_path', type=str, help='path ro a specific checkpoint to load',\n default='/home/mk/Semantic_Segmentation/DenseASPP-master/pretrained_model/densenet121.pth')\nparser.add_argument('--GPU', type=int, help='the number of GPU', default=1)\nparser.add_argument('--model_freq', type=int, help='save the model', default=100)\n\nargs = parser.parse_args()\n\ncudnn.benchmark = True\n\ndef poly_lr_scheduler(init_lr, epoch, maxEpoch=args.num_epochs, power=0.9):\n \"init_lr : base learning rate \\\n iter : current iteration \\\n lr_decay_iter : how frequently decay occurs, default is 1 \\\n power : polynomial power\"\n lr = init_lr * ((1 - epoch / maxEpoch) ** power)\n # for param_group in optimizer.param_groups:\n # param_group['lr'] = lr\n return lr\n\ndef main():\n net = DenseASPP_boundary(model_cfg=DenseASPP121.Model_CFG).cuda()\n # densenet121 = models.densenet121(pretrained=True)\n if len(args.checkpoint_path) == 0:\n curr_epoch = 1\n # Initializing 'best_record'\n args.best_record = {'epoch': 0, 'val_loss': 1e10, 'acc': 0, 'acc_cls': 0, 'mean_iu': 0, 'fwavacc': 0}\n else:\n # load the pretrained model\n print('training resumes from ' + args.checkpoint_path)\n # lambda ==> argument: manipulate(argument)\n pretrained_weight = torch.load(args.checkpoint_path, map_location=lambda storage, loc: storage)\n \"\"\" map_location = lambda storage, loc: storage--> Load all tensors onto the CPU, using a function\"\"\"\n new_state_dict = OrderedDict()\n model_dict = net.state_dict()\n for key, value in pretrained_weight.items():\n name = key\n new_state_dict[name] = value\n if name.find('norm') >= 9:\n print('norm contained from pretrained_weight : ', name)\n value.requires_grad = False\n # if name.find('conv0') >= 9:\n # print('norm contained from pretrained_weight : ', name)\n # value.requires_grad = False\n\n new_state_dict.pop('features.conv0.weight')\n new_state_dict.pop('features.norm5.weight')\n new_state_dict.pop('features.norm5.bias')\n new_state_dict.pop('features.norm5.running_mean')\n new_state_dict.pop('features.norm5.running_var')\n new_state_dict.pop('classifier.weight')\n new_state_dict.pop('classifier.bias')\n model_dict.update(new_state_dict)\n net.load_state_dict(model_dict)\n # pretrained_dict = {key: value for key, value in pretrained_dict.items() if key in model_dict}\n # model_dict.update(pretrained_dict)\n # pretrained_dict = {key: value for key, value in pretrained_dict.items() if key != 'classifier.weight' or 'classifier.bias'}\n\n # model.load_state_dict(model_dict, strict=False)\n # model.load_state_dict(new_pretrained_dict, strict=False)\n curr_epoch = 1\n args.best_record = {'epoch': 0, 'val_loss': 1e10, 'acc': 0, 'acc_cls': 0, 'mean_iu': 0, 'fwavacc': 0}\n\n # ---------------------------------- [[ data - augmentation ]] ---------------------------------------------------\n # ----------------------------------------------------------------------------------------------------------------\n # [[joint_transforms]]\n # both raw image and gt are transformed by data-augmentation\n train_joint_transform = joint_transforms.Compose([\n # joint_transforms.ImageScaling(size=[0.5, 2.0]),\n joint_transforms.RandomHorizontallyFlip(),\n joint_transforms.RandomSizedCrop(size=args.input_width),\n ])\n\n # transform : To preprocess images\n # Compose : if there are a lot of preprocessed images, compose plays a role as collector in a single space.\n input_transform = standard_transforms.Compose([\n # Colorjitter.ColorJitter(brightness=[-10, 10]),\n standard_transforms.ColorJitter(hue=0.1),\n standard_transforms.ToTensor(),\n # standard_transforms.Normalize(*my_mean_std)\n ])\n\n target_transform = extended_transforms.MaskToTensor()\n\n train_set = segmentation_dataloader.CityScapes('fine', 'train', joint_transform=train_joint_transform,\n transform=input_transform, target_transform=target_transform)\n train_loader = DataLoader(train_set, batch_size=args.train_batch_size, num_workers=args.num_threads, shuffle=True)\n\n # optimizer = optim.Adam(net.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)\n\n criterion = torch.nn.CrossEntropyLoss(ignore_index=segmentation_dataloader.ignore_label).cuda()\n\n num_training_samples = len(train_set)\n steps_per_epoch = np.ceil(num_training_samples / args.train_batch_size).astype(np.int32)\n num_total_steps = args.num_epochs * steps_per_epoch\n\n print(\"total number of samples: {}\".format(num_training_samples))\n print(\"total number of steps : {}\".format(num_total_steps))\n\n # COUNT_PARAMS\n total_num_paramters = 0\n for param in net.parameters():\n total_num_paramters += np.array(list(param.size())).prod()\n\n print(\"number of trainable parameters: {}\".format(total_num_paramters))\n\n for epoch in range(curr_epoch, args.num_epochs + 1):\n lr_ = poly_lr_scheduler(init_lr=args.learning_rate, epoch=epoch - 1)\n optimizer = optim.Adam(net.parameters(), lr=lr_, weight_decay=args.weight_decay)\n\n train(train_loader, net, criterion, optimizer, epoch, args)\n\n print('Training Done!!')\n\ndef train(train_loader, net, criterion, optimizer, epoch, train_args):\n train_loss = AverageMeter()\n\n # curr_iter : total dataset per epoch\n curr_iter = (epoch - 1) * len(train_loader)\n index = 0\n predictions_all = []\n visual = []\n\n start_time = time.time()\n net.train()\n for i, data in enumerate(train_loader):\n inputs, labels, boundarys = data\n bound_inputs = torch.cat((inputs, boundarys), dim=1)\n\n assert inputs.size()[2:] == labels.size()[1:]\n N = inputs.size(0)\n bound_inputs = Variable(bound_inputs).cuda()\n labels = Variable(labels).cuda()\n\n optimizer.zero_grad()\n\n outputs = net(bound_inputs)\n assert outputs.size()[2:] == labels.size()[1:]\n assert outputs.size()[1] == segmentation_dataloader.num_classes\n\n before_op_time = timeit.default_timer()\n loss = criterion(outputs, labels)\n duration = timeit.default_timer() - before_op_time\n\n loss.backward()\n optimizer.step()\n batch_time = time.time() - start_time\n\n train_loss.update(loss.data[0], N)\n curr_iter += 1\n\n writer.add_scalar('train_loss', train_loss.avg, curr_iter)\n\n if (i + 1) % train_args.print_frequency == 0:\n examples_time = args.train_batch_size / duration\n print('epoch: %d | iter: %d / %d | train loss: %.5f | examples/s: %4.2f | time_elapsed: %.5f''s' %\n (epoch, i + 1, len(train_loader), train_loss.avg, examples_time, batch_time))\n\n # SAVE THE IMAGES\n data_transform = standard_transforms.ToTensor()\n\n np_outputs = outputs.data.cpu().numpy()\n result = np_outputs.argmax(axis=1)\n predictions_all.append(result)\n\n predictions_all = np.concatenate(predictions_all)\n for idx, data in enumerate(predictions_all):\n predictions_pil = segmentation_dataloader.colorize_mask(data)\n predictions = data_transform(predictions_pil.convert('RGB'))\n visual.extend([predictions])\n\n visual = torch.stack(visual, 0)\n visual = vutils.make_grid(visual, nrow=1, padding=0)\n # result = np_outputs.argmax(axis=1)[0]\n # row, col = result.shape\n # dst = np.zeros((row, col, 3), dtype=np.uint8)\n #\n # for i in range(19):\n # dst[result == i] = COLOR_MAP[i]\n # dst = np.array(dst, dtype=np.uint8)\n # dst = cv2.cvtColor(dst, cv2.COLOR_RGB2BGR)\n # if not os.path.exists(os.path.join(ckpt_path, 'TensorboardX', ImageNet, exp_name_ImageNet, 'prediction')):\n # os.makedirs(os.path.join(ckpt_path, 'TensorboardX', ImageNet, exp_name_ImageNet, 'prediction'))\n #\n # cv2.imwrite(os.path.join(ckpt_path, 'TensorboardX', ImageNet, exp_name_ImageNet, 'prediction/%06d.png' %\n # epoch), dst)\n writer.add_image('Output_image_{}'.format(epoch), visual)\n\n # SAVE THE MODEL\n if (i + 1) % train_args.print_frequency == 0:\n torch.save(net.state_dict(), os.path.join(ckpt_path, 'Model', ImageNet, exp_name_ImageNet,\n 'model-{}'.format(idx + 1) + '.pkl'))\n\n with open(os.path.join(ckpt_path, 'TensorboardX', ImageNet, exp_name_ImageNet, 'LR_v0{}_{}.txt'.format(x,version)), 'a') as LRtxt:\n LRtxt.write(\"index : {}, epoch : {}, learning rate : {: f}\".format(index, epoch, optimizer.param_groups[0]['lr']) + '\\n')\n index += 1\n\nif __name__ == '__main__':\n x = 1\n version = '0'\n\n ckpt_path = '../../ckpt'\n ImageNet = 'ImageNet/DenseNet121_v3'\n exp_name_ImageNet = 'segImageNet_v0{}_{}'.format(x, version)\n\n # [[ SummaryWriter]]\n # Writes 'Summary' directly to event files.\n # writer = SummaryWriter(os.path.join(ckpt_path, 'exp', exp_name))\n writer = SummaryWriter(os.path.join(ckpt_path, 'TensorboardX', ImageNet, exp_name_ImageNet))\n\n check_mkdir(ckpt_path)\n check_mkdir(os.path.join(ckpt_path, 'Model', ImageNet, exp_name_ImageNet))\n open(os.path.join(ckpt_path, 'Model', ImageNet, exp_name_ImageNet, str(datetime.datetime.now()) + '.txt'),\n 'w').write(\n str(args) + '\\n\\n')\n\n src = \"/home/mk/Semantic_Segmentation/DenseASPP-master/My_train/segmentation_main_v3.py\"\n src_model = \"/home/mk/Semantic_Segmentation/DenseASPP-master/models/DenseASPP.py\"\n\n copy_path = os.path.join(ckpt_path, 'TensorboardX', ImageNet, exp_name_ImageNet,\n \"segmentation_main_v3_\" + \"v0{}_{}.py\".format(x, version))\n model_copy_path = os.path.join(ckpt_path, 'TensorboardX', ImageNet, exp_name_ImageNet,\n \"DenseASPP_\" + \"v0{}_{}.py\".format(x, version))\n\n shutil.copy(src, copy_path)\n shutil.copy(src_model, model_copy_path)\n\n GPU_ID = args.GPU\n\n main()\n","sub_path":"My_train/segmentation_main_v3_1.py","file_name":"segmentation_main_v3_1.py","file_ext":"py","file_size_in_byte":12771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"540710902","text":"# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors\n# License: GNU General Public License v3. See license.txt\n\nfrom __future__ import unicode_literals\n\nimport frappe\nfrom frappe import _\nfrom frappe.model import no_value_fields\nfrom erpnext.stock.doctype.packing_slip.packing_slip import PackingSlip\nfrom frappe.utils import cint, flt\n\n\nclass CustomPackingSlip(PackingSlip):\n\n\tdef validate(self):\n\t\t\"\"\"\n\t\t\t* Validate existence of submitted Delivery Note\n\t\t\t* Case nos do not overlap\n\t\t\t* Check if packed qty doesn't exceed actual qty of delivery note\n\n\t\t\tIt is necessary to validate case nos before checking quantity\n\t\t\"\"\"\n\t\tself.validate_delivery_note()\n\t\tself.validate_items_mandatory()\n\t\tself.validate_case_nos()\n\t\tself.validate_qty()\n\t\tself.validate_item()\n\n\t\tfrom erpnext.utilities.transaction_base import validate_uom_is_integer\n\t\tvalidate_uom_is_integer(self, \"stock_uom\", \"qty\")\n\t\tvalidate_uom_is_integer(self, \"weight_uom\", \"net_weight\")\n\n\tdef validate_qty(self):\n\t\t\"\"\"Check packed qty across packing slips and delivery note\"\"\"\n\t\t# Get Delivery Note Items, Item Quantity Dict and No. of Cases for this Packing slip\n\t\tdn_details, ps_item_qty, ps_item, no_of_cases = self.get_details_for_packing()\n\n\t\tfor item in dn_details:\n\t\t\tnew_packed_qty = (flt(ps_item_qty[item['item_code']]) * no_of_cases) + \\\n\t\t\t\tflt(item['packed_qty'])\n\t\t\tif new_packed_qty > flt(item['qty']) and no_of_cases:\n\t\t\t\tself.recommend_new_qty(item, ps_item_qty, no_of_cases)\n\n\tdef validate_item(self):\n\t\t\"\"\"Check packed items across packing slips and delivery note\"\"\"\n\t\t# Get Delivery Note Items, Item Quantity Dict and No. of Cases for this Packing slip\n\t\tdn_details, ps_item_qty, ps_item, no_of_cases = self.get_details_for_packing()\n\n\t\tdelivery_note_items = [d['item_code'] for d in dn_details]\n\t\t\n\t\tfor item in ps_item:\n\t\t\tif item not in delivery_note_items:\n\t\t\t\tself.recommend_delete_item(item)\n\n\n\tdef get_details_for_packing(self):\n\t\t\"\"\"\n\t\t\tReturns\n\t\t\t* 'Delivery Note Items' query result as a list of dict\n\t\t\t* Item Quantity dict of current packing slip doc\n\t\t\t* No. of Cases of this packing slip\n\t\t\"\"\"\n\n\t\trows = [d.item_code for d in self.get(\"items\")]\n\n\t\t# also pick custom fields from delivery note\n\t\tcustom_fields = ', '.join(['dni.`{0}`'.format(d.fieldname)\n\t\t\tfor d in frappe.get_meta(\"Delivery Note Item\").get_custom_fields()\n\t\t\tif d.fieldtype not in no_value_fields])\n\n\t\tif custom_fields:\n\t\t\tcustom_fields = ', ' + custom_fields\n\n\t\tcondition = \"\"\n\t\tif rows:\n\t\t\tcondition = \" and item_code in (%s)\" % (\", \".join([\"%s\"]*len(rows)))\n\n\t\t# gets item code, qty per item code, latest packed qty per item code and stock uom\n\t\tres = frappe.db.sql(\"\"\"select item_code, sum(qty) as qty,\n\t\t\t(select sum(psi.qty * (abs(ps.to_case_no - ps.from_case_no) + 1))\n\t\t\t\tfrom `tabPacking Slip` ps, `tabPacking Slip Item` psi\n\t\t\t\twhere ps.name = psi.parent and (ps.docstatus = 1 or ps.docstatus = 0)\n\t\t\t\tand ps.delivery_note = dni.parent and psi.item_code=dni.item_code\n\t\t\t\tand from_case_no != {from_case_no}) as packed_qty,\n\t\t\tstock_uom, item_name, description, dni.batch_no {custom_fields}\n\t\t\tfrom `tabDelivery Note Item` dni\n\t\t\twhere parent=%s {condition}\n\t\t\tgroup by item_code\"\"\".format(condition=condition, custom_fields=custom_fields, from_case_no=self.from_case_no),\n\t\t\ttuple([self.delivery_note] + rows), as_dict=1)\n\n\t\tps_item_qty = dict([[d.item_code, d.qty] for d in self.get(\"items\")])\n\t\tps_item = [d.item_code for d in self.get(\"items\")]\n\t\tno_of_cases = cint(self.to_case_no) - cint(self.from_case_no) + 1\n\n\t\treturn res, ps_item_qty, ps_item, no_of_cases\n\n\n\tdef recommend_new_qty(self, item, ps_item_qty, no_of_cases):\n\t\t\"\"\"\n\t\t\tRecommend a new quantity and raise a validation exception\n\t\t\"\"\"\n\t\titem['recommended_qty'] = (flt(item['qty']) - flt(item['packed_qty'])) / no_of_cases + 1\n\t\titem['specified_qty'] = flt(ps_item_qty[item['item_code']])\n\t\tif not item['packed_qty']: item['packed_qty'] = 0\n\n\t\tfrappe.throw(_(\"Quantity for Item {0} must be less than {1}\").format(item.get(\"item_code\"), item.get(\"recommended_qty\")))\n\n\tdef recommend_delete_item(self, item):\n\t\t\"\"\"\n\t\t\tRecommend deleting the product and raise a validation exception\n\t\t\"\"\"\n\t\tfrappe.throw(_(\"Товар {0} отсутствует в накладной {1}. Удалите данный товар из накладной.\").format(item, self.delivery_note))\n\n","sub_path":"trava_erpnext/overrides/packing_slip.py","file_name":"packing_slip.py","file_ext":"py","file_size_in_byte":4324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"157460612","text":"#!/usr/bin/env python\n\n__author__ = \"Patrick Wieschollek\"\n__email__ = \"patrick@wieschollek.info\"\n\n\nimport tensorflow as tf\nimport stream, network\nimport tfblocks.diary, tfblocks.trainer, tfblocks.callbacks\nimport time, os.path\nimport numpy as np\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string('train_dir', 'cifar10_train/', \n \"\"\"Directory where to write event logs \"\"\"\n \"\"\"and checkpoint.\"\"\")\ntf.app.flags.DEFINE_string('data_dir', 'data', \n \"\"\"Directory of the plain dataset \"\"\")\ntf.app.flags.DEFINE_integer(\"batch_size\", 64, \"number of images in each batch\")\ntf.app.flags.DEFINE_integer(\"epoch_iterations\", 500, \"iterations ine ach epoch\")\ntf.app.flags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')\ntf.app.flags.DEFINE_integer('gpus', 1, 'Initial learning rate.')\n\ndef main(argv=None):\n\n # compute and indidual path from current run\n work_dir = os.path.abspath(os.path.join(FLAGS.train_dir, \"runs\", str(int(time.time()))))\n\n # where does the data comes from ...\n train_data = stream.Stream(FLAGS.data_dir, 'train.h5', FLAGS.batch_size)\n teacher = tfblocks.trainer.Trainer(optimizer=tf.train.AdamOptimizer(FLAGS.learning_rate))\n teacher.init(network.Network, train_data, num=FLAGS.gpus)\n\n # validation data generation\n tf.get_variable_scope().reuse_variables()\n valid_data = stream.Stream(FLAGS.data_dir, 'validation.h5', FLAGS.batch_size)\n valid_net = network.Network()\n valid_net.build(valid_data.next())\n\n # keep track of everything during training\n diary = tfblocks.diary.Diary()\n diary.epochs = 100\n diary.batch_size = FLAGS.batch_size\n diary.batches_per_epoch = FLAGS.epoch_iterations\n\n diary.callbacks.append(tfblocks.callbacks.AccuracyCallback(5000, FLAGS.batch_size, valid_net.accuracy_op))\n diary.callbacks.append(tfblocks.callbacks.EtaCallback())\n\n init_op = tf.initialize_all_variables()\n with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n\n # create all variables\n sess.run(init_op)\n\n # start the data creation mechanism\n train_data.start(sess);\n valid_data.start(sess);\n\n # init all class variables that depends on the current session\n diary.attach(sess, work_dir)\n\n # as long as the worker are creating data and there are iterations left\n # do an update step\n while train_data.exists():\n err = diary.train_step(sess, teacher, train_data, 10)\n\n train_data.stop()\n\n\nif __name__ == '__main__':\n tf.app.run()\n \n","sub_path":"mnist/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"117065384","text":"import copy\nimport itertools\ngrid = 2\ng = [[0 for x in range(grid+1)] for y in range(grid+1)]\ng[0][0] =1\n\nmove_right = (0,1)\nmove_down = (1,0)\npos = [move_right, move_down]\n\nstart = [0,0]\n\ndef move(g, dir):\n f = copy.deepcopy(g)\n for i in range(grid+1):\n find = False\n for j in range(grid+1):\n if g[i][j] == 1:\n pos = i,j\n g[i][j] = 0\n find = True\n break\n if find:\n break\n try:\n pos = (i+dir[0], j+dir[1])\n g[pos[0]][pos[1]] = 1\n moves = True\n return g, moves\n except IndexError as e:\n moves = False\n return f, moves\n\npossible = []\nfor a in pos:\n for b in pos:\n for c in pos:\n for d in pos:\n possible.append((a,b,c,d))\n\nsolutions = []\nfor a in possible:\n within = []\n g = [[0 for x in range(grid+1)] for y in range(grid+1)]\n g[0][0] =1\n for c,b in enumerate(a):\n g,is_possible = move(g,b)\n within.append(b)\n if is_possible == False:\n break\n if c == len(a)-1:\n solutions.append(within)\n\nprint(len(solutions))\n# 6\n","sub_path":"15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"200867433","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom apps.hello.models import Person, RequestsLog\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nimport os\nfrom django.conf import settings\nimport shutil\nimport datetime\nfrom freezegun import freeze_time\n\n\nREQUIRED_FIELDS = [\n 'bio',\n 'date_of_birth',\n 'email',\n 'id',\n 'jabber',\n 'last_name',\n 'name',\n 'other_contacts',\n 'skype',\n 'photo'\n]\n\nREQUEST_DATA = {\n 'method': 'GET',\n 'path': '/requests/',\n 'status_code': 200\n}\n\n\n@override_settings(MEDIA_ROOT=settings.MEDIA_TEST_ROOT)\nclass PersonModelTest(TestCase):\n\n def setUp(self):\n self.test_person = Person.objects.first()\n self.test_img_path = os.path.join(\n settings.BASE_DIR,\n 'assets/img/test_image.png'\n )\n with open(self.test_img_path, 'rb') as test_img:\n self.test_image_1 = SimpleUploadedFile(\n name='test_image_1.png',\n content=test_img.read(),\n content_type='image/png'\n )\n self.test_person.photo = self.test_image_1\n self.test_person.save()\n self.first_photo_file = self.test_person.photo.path\n\n def tearDown(self):\n test_dir = os.path.exists(settings.MEDIA_TEST_ROOT)\n if test_dir:\n shutil.rmtree(settings.MEDIA_TEST_ROOT)\n\n def test_unicode_method(self):\n \"\"\"Ensures, the __unicode__ method return proper string\"\"\"\n test_person = Person.objects.first()\n test_person.name = u'Александр'\n test_person.last_name = u'Юникод'\n test_person.save()\n self.assertEqual(test_person.__unicode__(), u'Александр Юникод')\n\n def test_proper_model_fields(self):\n \"\"\"Check, if person model consist of proper fields\"\"\"\n exist_fields = Person._meta.get_all_field_names()\n self.assertItemsEqual(exist_fields, REQUIRED_FIELDS)\n\n def test_save_method_store_photo_file_to_proper_path(self):\n \"\"\"Check, if save method, store photo_file to proper path\"\"\"\n self.assertTrue(os.path.exists(self.first_photo_file))\n self.assertEqual(\n self.first_photo_file,\n settings.MEDIA_TEST_ROOT + self.test_person.photo.name\n )\n\n def test_save_method_crop_photo_to_proper_size(self):\n \"\"\"Check, if save method, crop image to proper size\"\"\"\n with open(self.test_img_path, 'rb') as test_img:\n self.test_image_2 = SimpleUploadedFile(\n name='test_image_2.png',\n content=test_img.read(),\n content_type='image/png'\n )\n self.test_person.photo = self.test_image_2\n photo_width_before_save = self.test_person.photo.width\n photo_height_before_save = self.test_person.photo.height\n self.assertTrue(\n photo_width_before_save or photo_height_before_save > 200\n )\n self.test_person.save()\n self.assertTrue(\n self.test_person.photo.width <= 200 and\n self.test_person.photo.height <= 200\n )\n self.assertEqual(\n self.test_person.photo.width or self.test_person.photo.height,\n 200\n )\n\n def test_save_method_resize_photo_maintaining_aspect_ratio(self):\n \"\"\"Check, if save method resize photo maintaining_aspect_ratio\"\"\"\n with open(self.test_img_path, 'rb') as test_img:\n self.test_image_2 = SimpleUploadedFile(\n name='test_image_2.png',\n content=test_img.read(),\n content_type='image/png'\n )\n self.test_person.photo = self.test_image_2\n aspect_ratio_before_save = (\n self.test_person.photo.width /\n self.test_person.photo.height\n )\n aspect_ratio_after_save = (\n self.test_person.photo.width /\n self.test_person.photo.height\n )\n self.test_person.save()\n self.assertEqual(\n aspect_ratio_before_save,\n aspect_ratio_after_save\n )\n\n def test_save_method_remove_unused_img(self):\n \"\"\"Check, if model save method delete unused images\"\"\"\n with open(self.test_img_path, 'rb') as test_img:\n self.test_image_2 = SimpleUploadedFile(\n name='test_image_2.png',\n content=test_img.read(),\n content_type='image/png'\n )\n self.test_person.photo = self.test_image_2\n self.test_person.save()\n self.second_photo_file = self.test_person.photo.path\n self.assertTrue(os.path.exists(self.second_photo_file))\n self.assertFalse(os.path.exists(self.first_photo_file))\n\n def test_photo_update_status_return_true(self):\n \"\"\"Check, for True status, if new photo_file is given\"\"\"\n with open(self.test_img_path, 'rb') as test_img:\n self.test_image_2 = SimpleUploadedFile(\n name='test_image_2.png',\n content=test_img.read(),\n content_type='image/png'\n )\n self.test_person.photo = self.test_image_2\n exist_person = Person.objects.filter(id=self.test_person.id).first()\n test_update_status = self.test_person.photo_update_status(exist_person)\n self.test_person.save()\n self.assertTrue(test_update_status)\n\n def test_photo_update_status_return_true_if_photo_remove(self):\n \"\"\"Check, for True status, if photo is remove\"\"\"\n self.test_person.photo = None\n exist_person = Person.objects.filter(id=self.test_person.id).first()\n test_update_status = self.test_person.photo_update_status(exist_person)\n self.test_person.save()\n self.assertTrue(test_update_status)\n\n def test_photo_update_status_return_false(self):\n \"\"\"Check, for False status, if no new photo_file is given\"\"\"\n self.test_person.name = \"Alex\"\n exist_person = Person.objects.filter(id=self.test_person.id).first()\n test_update_status = self.test_person.photo_update_status(exist_person)\n self.test_person.save()\n self.assertFalse(test_update_status)\n\n\nclass RequestsLogModelTest(TestCase):\n\n def setUp(self):\n for i in range(10):\n with freeze_time(\"2012-01-14 12:00:01\") as frozen_time:\n frozen_time.tick(delta=datetime.timedelta(seconds=i))\n RequestsLog(**REQUEST_DATA).save()\n\n def test_get_db_update_status_method_if_None_given(self):\n \"\"\"Must return True, if None given as parameter\"\"\"\n test_db_update_status = RequestsLog.get_db_update_status(None)\n self.assertTrue(test_db_update_status)\n\n def test_get_db_update_status_method_if_DB_has_changed(self):\n \"\"\"Must return True, if DB updates exists\"\"\"\n test_time = \"2012-01-14 12:00:00\"\n test_db_update_status = RequestsLog.get_db_update_status(test_time)\n self.assertTrue(test_db_update_status)\n\n def test_get_db_update_status_method_if_no_DB_changes(self):\n \"\"\"Must return False, if no changes in DB\"\"\"\n test_time = \"2012-01-14 13:00:00\"\n test_db_update_status = RequestsLog.get_db_update_status(test_time)\n self.assertFalse(test_db_update_status)\n\n def test_get_no_viewed_count_method_if_None_given(self):\n \"\"\"Must return all DB entries count, if None given as parameter\"\"\"\n db_entries_count = RequestsLog.objects.count()\n test_count = RequestsLog.get_no_viewed_count(None)\n self.assertEqual(db_entries_count, test_count)\n\n def test_get_no_viewed_count_method_with_proper_parameters(self):\n \"\"\"Must return unviewed requests count, if parameter is given\"\"\"\n last_requests = RequestsLog.objects.all()\n fifth_last_request = last_requests[4].edit_time\n new_test_count = RequestsLog.get_no_viewed_count(\n fifth_last_request.isoformat()\n )\n self.assertEqual(new_test_count, 4)\n\n def test_get_last_edit_time_method(self):\n \"\"\"Must return last edit time\"\"\"\n last_edit_time = RequestsLog\\\n .objects\\\n .order_by('edit_time')\\\n .last()\\\n .edit_time\\\n .isoformat()\n test_edit_time = RequestsLog.get_last_edit_time()\n self.assertEqual(last_edit_time, test_edit_time)\n","sub_path":"apps/hello/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":8410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"402360790","text":"import pandas as pd\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport json\nimport re\n\ndef steamChartScrapper(steamId, release_date) :\n url = 'https://steamcharts.com/app/' + steamId\n\n session = requests.Session()\n retry = Retry(connect=3, backoff_factor=0.5)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n\n response = session.get(url)\n\n content = BeautifulSoup(response.content, 'html.parser')\n\n gamePlayers = content.findAll('tr')\n\n if gamePlayers != [] :\n date_str = gamePlayers[-2].find('td', {'class': 'month-cell left'})\n if date_str is not None :\n date_str = date_str.text\n posToStart = 6\n posToEnd = -5\n date_str = date_str[posToStart:]\n date_str = date_str[:posToEnd]\n date_datetime = datetime.strptime(date_str, '%B %Y').date()\n if date_datetime > release_date :\n num_player_after_month = gamePlayers[-2].find('td', {'class': 'right num-f'})\n if num_player_after_month is not None:\n num_player_after_month = num_player_after_month.text\n else:\n num_player_after_month = None\n else :\n num_player_after_month = None\n else :\n num_player_after_month = None\n else:\n num_player_after_month = None\n\n return num_player_after_month\n\ndef getDescription(steamId) :\n url = \"https://store.steampowered.com/app/\" + steamId + \"/?cc=us\"\n \n session = requests.Session()\n retry = Retry(connect=3, backoff_factor=0.5)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n\n response = session.get(url)\n \n content = BeautifulSoup(response.content, 'html.parser')\n \n gameDescription = content.find('div', attrs = {'id' : 'game_area_description'})\n \n if gameDescription is not None : \n return gameDescription.text\n else :\n return None\n #steamRequest = json.loads(response.text)\n \n #if steamRequest[steamId][\"success\"] == True and 'detailed_description' in steamRequest[steamId][\"data\"].keys() :\n #cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')\n #description = re.sub(cleanr, ' ', steamRequest[steamId]['data']['detailed_description'])\n ##description = BeautifulSoup(steamRequest[steamId]['data']['detailed_description'], 'html.parser').text\n #return description\n #else :\n #return None\n \ndef dataUpdatePlayers() :\n #df = pd.read_csv('dataForMachineLearning.csv')\n \n #for i in range(len(df.index)) :\n #release_date = datetime.strptime(df['release_date'][i], '%m-%d-%Y').date()\n #if release_date.year < 2012 :\n #df.at[i, \"num_players_after_month\"] = None\n #else :\n #df.at[i, \"num_players_after_month\"] = steamChartScrapper(str(df['steamId'][i]), release_date)\n \n #df.to_csv('dataForMachineLearning.csv', index=False)\n df = pd.read_csv('dataForMachineLearning.csv')\n \n df['description'] = ''\n for i in range(len(df.index)) :\n steamId = df['steamId'][i]\n description = getDescription(str(steamId))\n df.loc[i, 'description'] = description\n \n df = df[df.description.notnull()]\n df.to_csv('dataForRecommendation.csv', index=False)\n \ndef dataUpdateRemoveRowsPlayers() :\n df = pd.read_csv('dataForMachineLearning.csv')\n \n df = df[df.num_players_after_month.notnull()]\n \n df.to_csv('dataForMachineLearning.csv', index=False)\n \ndataUpdatePlayers()","sub_path":"dataUpdateProcess.py","file_name":"dataUpdateProcess.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"145129245","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\nimport pymysql\nfrom day07.mydao import DaoStock\nds = DaoStock()\n\nconn = pymysql.connect(user=\"root\", password=\"python\",\n host=\"localhost\", database=\"mypydb\", charset='utf8')\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\nX = list() # []\nY = list()\nZ = list()\n\nidx = 0\nfor c_name in ds.retrieveAll() :\n X.clear()\n Y.clear()\n Z.clear()\n \n for i in range(6) :\n X.append(idx)\n Y.append(i*2)\n Z = ds.get_prices(c_name)\n \n min_z = min(Z)\n max_z = max(Z)\n if (max_z - min_z) == 0 :\n Z[:] = [0 in Z]\n else :\n Z[:] = [(ele - min_z)/(max_z-min_z) for ele in Z]\n \n ax.plot(X, Y, Z)\n idx+=1\n \nprint(3)\nplt.show()\n","sub_path":"HELLOPYTHON/mystock/my3dgraph02_samsung_homework.py","file_name":"my3dgraph02_samsung_homework.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"589230006","text":"import random\nimport math\n\nN_BOXES = 162 #/* Number of disjoint boxes of state space. */\nALPHA = 1000 #/* Learning rate for action weights, w. */\nBETA = 0.5 #/* Learning rate for critic weights, v. */\nGAMMA = 0.95 #/* Discount factor for critic. */\nLAMBDAw = 0.9 #/* Decay rate for w eligibility trace. */\nLAMBDAv = 0.8 #/* Decay rate for v eligibility trace. */\n\nMAX_FAILURES = 100 #/* Termination criterion. */\nMAX_STEPS = 100000\n\n#typedef float vector[N_BOXES];\n\n\"\"\"----------------------------------------------------------------------\n cart_pole: Takes an action (0 or 1) and the current values of the\n four state variables and updates their values by estimating the state\n TAU seconds later.\n----------------------------------------------------------------------\n\"\"\"\n\n#/*** Parameters for simulation ***/\n\nGRAVITY = 9.8\nMASSCART = 1.0\nMASSPOLE = 0.1\nTOTAL_MASS = (MASSPOLE + MASSCART)\nLENGTH = 0.5 #/* actually half the pole's length */\nPOLEMASS_LENGTH = (MASSPOLE * LENGTH)\nFORCE_MAG = 10.0\nTAU = 0.02 #/* seconds between state updates */\nFOURTHIRDS = 1.3333333333333\n\ndef prob_push_right(s):\n return (1.0 / (1.0 + math.exp(-max(-50.0, min(s, 50.0)))))\n\ndef cart_pole(action, x, x_dot, theta, theta_dot):\n if action > 0:\n force = FORCE_MAG\n else:\n force = -FORCE_MAG\n\n costheta = math.cos(theta);\n sintheta = math.sin(theta);\n\n temp = (force + POLEMASS_LENGTH * theta_dot * theta_dot * sintheta)/ TOTAL_MASS;\n\n thetaacc = (GRAVITY * sintheta - costheta* temp)/ (LENGTH * (FOURTHIRDS - MASSPOLE * costheta * costheta/ TOTAL_MASS));\n\n xacc = temp - POLEMASS_LENGTH * thetaacc* costheta / TOTAL_MASS;\n\n #/*** Update the four state variables, using Euler's method. ***/\n\n x += TAU * x_dot;\n x_dot += TAU * xacc;\n theta += TAU * theta_dot;\n theta_dot += TAU * thetaacc;\n return [x, x_dot, theta, theta_dot]\n\n\"\"\"\n/*----------------------------------------------------------------------\n get_box: Given the current state, returns a number from 1 to 162\n designating the region of the state space encompassing the current state.\n Returns a value of -1 if a failure state is encountered.\n----------------------------------------------------------------------*/\n\"\"\"\none_degree = 0.0174532 #/* 2pi/360 */\nsix_degrees = 0.1047192\ntwelve_degrees = 0.2094384\nfifty_degrees = 0.87266\n\ndef get_box(x,x_dot,theta,theta_dot):\n\n box=0;\n\n if (x < -2.4 or x > 2.4 or theta < -twelve_degrees or theta > twelve_degrees):\n return -1 #/* to signal failure */\n\n if (x < -0.8):\n box = 0;\n elif (x < 0.8):\n box = 1;\n else:\n box = 2;\n\n if (x_dot < -0.5):\n pass\n elif (x_dot < 0.5):\n box += 3;\n else:\n box += 6;\n\n if (theta < -six_degrees):\n pass\n elif (theta < -one_degree):\n box += 9;\n elif (theta < 0):\n box += 18;\n elif (theta < one_degree):\n box += 27;\n elif (theta < six_degrees):\n box += 36;\n else:\n box += 45;\n\n if (theta_dot < -fifty_degrees):\n pass\n elif (theta_dot < fifty_degrees):\n box += 54;\n else:\n box += 108;\n\n return box\n\nif __name__ == \"__main__\":\n \"\"\"\n float x, /* cart position, meters */\n x_dot, /* cart velocity */\n theta, /* pole angle, radians */\n theta_dot; /* pole angular velocity */\n vector w, /* vector of action weights */\n v, /* vector of critic weights */\n e, /* vector of action weight eligibilities */\n xbar; /* vector of critic weight eligibilities */\n float p, oldp, rhat, r;\n int box, i, y, steps = 0, failures=0, failed;\n \"\"\"\n steps = 0\n failures = 0\n\n w = [0.0]*N_BOXES\n v = [0.0]*N_BOXES\n e = [0.0]*N_BOXES\n xbar = [0.0]*N_BOXES\n\n print(\"Seed? \")\n i = int(raw_input())\n random.seed(i);\n\n #--- Initialize action and heuristic critic weights and traces. ---*/\n for i in range(N_BOXES):\n w[i] = v[i] = xbar[i] = e[i] = 0.0\n\n #/*--- Starting state is (0 0 0 0) ---*/\n x = x_dot = theta = theta_dot = 0.0\n\n #/*--- Find box in state space containing start state ---*/\n box = get_box(x, x_dot, theta, theta_dot)\n\n #/*--- Iterate through the action-learn loop. ---*/\n while steps < MAX_STEPS and failures < MAX_FAILURES:\n\n steps += 1\n #/*--- Choose action randomly, biased by current weight. ---*/\n randomF = (float(random.random()) / float(((1 << 31) - 1)))\n y = (randomF < prob_push_right(w[box]))\n\n #/*--- Update traces. ---*/\n e[box] += (1.0 - LAMBDAw) * (y - 0.5);\n xbar[box] += (1.0 - LAMBDAv);\n\n #/*--- Remember prediction of failure for current state ---*/\n oldp = v[box];\n\n #/*--- Apply action to the simulated cart-pole ---*/\n x, x_dot, theta, theta_dot = cart_pole(y, x, x_dot, theta, theta_dot);\n\n #/*--- Get box of state space containing the resulting state. ---*/\n box = get_box(x, x_dot, theta, theta_dot);\n\n if (box < 0):\n #/*--- Failure occurred. ---*/\n failed = 1;\n failures+=1;\n print(\"Trial {} was {}steps.\\n\".format(failures, steps));\n steps = 0;\n\n #/*--- Reset state to (0 0 0 0). Find the box. ---*/\n x = x_dot = theta = theta_dot = 0.0;\n box = get_box(x, x_dot, theta, theta_dot);\n\n #/*--- Reinforcement upon failure is -1. Prediction of failure is 0. ---*/\n r = -1.0;\n p = 0.;\n else:\n #/*--- Not a failure. ---*/\n failed = 0;\n\n #/*--- Reinforcement is 0. Prediction of failure given by v weight. ---*/\n r = 0;\n p= v[box];\n\n #/*--- Heuristic reinforcement is: current reinforcement + gamma * new failure prediction - previous failure prediction ---*/\n rhat = r + GAMMA * p - oldp;\n\n for i in range(0, N_BOXES):\n\n #/*--- Update all weights. ---*/\n w[i] += ALPHA * rhat * e[i];\n v[i] += BETA * rhat * xbar[i];\n if v[i] < -1.0:\n v[i] = v[i]\n\n if failed:\n #/*--- If failure, zero all traces. ---*/\n e[i] = 0.;\n xbar[i] = 0.;\n else:\n #/*--- Otherwise, update (decay) the traces. ---*/\n e[i] *= LAMBDAw;\n xbar[i] *= LAMBDAv;\n\n if failures == MAX_FAILURES:\n print(\"Pole not balanced. Stopping after {} failures.\".format(failures))\n else:\n print(\"Pole balanced successfully for at least {} steps\\n\".format(steps));\n\n\n","sub_path":"pole_balance.py","file_name":"pole_balance.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"442970628","text":"# -*- coding: utf-8 -*-\nimport random\n\nfrom django.db import models\nfrom app.investigacion.models import Investigacion\nfrom app.adjuntos.image_functions import ImgOpt\nfrom django.db.models.signals import post_save\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nimport os\n\n\nclass Adjuntos(models.Model):\n investigacion = models.ForeignKey(Investigacion, on_delete=models.CASCADE)\n adj2 = models.FileField(verbose_name='1. Foto de perfil del candidato', upload_to='adj', blank=True, null=True)\n adj3 = models.FileField(verbose_name='2.a Interior derecho', upload_to='adj', blank=True, null=True)\n adj4 = models.FileField(verbose_name='2.b Interior izquierdo', upload_to='adj', blank=True, null=True)\n adj5 = models.FileField(verbose_name='2.c Exterior derecho', upload_to='adj', blank=True, null=True)\n adj6 = models.FileField(verbose_name='2.d Exterior izquierdo', upload_to='adj', blank=True, null=True)\n adj9 = models.FileField(verbose_name='2.e Frente', upload_to='adj', blank=True, null=True)\n\n adj10 = models.FileField(verbose_name='3. Gestor Entrevistador', upload_to='adj', blank=True, null=True)\n adj13 = models.FileField(verbose_name='4. Croquis', upload_to='adj', blank=True, null=True)\n adj11 = models.FileField(verbose_name='5. Aviso Privacidad', upload_to='adj', blank=True, null=True)\n adj12 = models.FileField(verbose_name='6. Constancia', upload_to='adj', blank=True, null=True)\n\n adj14 = models.FileField(verbose_name='7.a Identificación con fotografia', upload_to='adj', blank=True, null=True)\n adj22 = models.FileField(verbose_name='7.b Identificación con fotografia', upload_to='adj', blank=True, null=True)\n adj23 = models.FileField(verbose_name='7.c Identificación con fotografia', upload_to='adj', blank=True, null=True)\n adj24 = models.FileField(verbose_name='7.d Identificación con fotografia', upload_to='adj', blank=True, null=True)\n\n adj17 = models.FileField(verbose_name='8. Acta de nacimiento', upload_to='adj', blank=True, null=True)\n adj16 = models.FileField(verbose_name='9. Comprobante de domicilio', upload_to='adj', blank=True, null=True)\n\n adj8 = models.FileField(verbose_name='10.a Semanas Cotizadas', upload_to='adj', blank=True, null=True)\n adj25 = models.FileField(verbose_name='10.b Semanas Cotizadas', upload_to='adj', blank=True, null=True)\n adj26 = models.FileField(verbose_name='10.c Semanas Cotizadas', upload_to='adj', blank=True, null=True)\n adj27 = models.FileField(verbose_name='10.d Semanas Cotizadas', upload_to='adj', blank=True, null=True)\n adj28 = models.FileField(verbose_name='10.e Semanas Cotizadas', upload_to='adj', blank=True, null=True)\n\n adj7 = models.FileField(verbose_name='11.a Validación de Demandas Laborales', upload_to='adj', blank=True,null=True)\n adj36 = models.FileField(verbose_name='11.b Validacion web', upload_to='adj', blank=True, null=True)\n\n adj18 = models.FileField(verbose_name='Carta Laboral', upload_to='adj', blank=True, null=True)\n adj37 = models.FileField(verbose_name='Carta Laboral Extra', upload_to='adj', blank=True, null=True)\n\n adj19 = models.FileField(verbose_name='Adicionales A', upload_to='adj', blank=True, null=True)\n adj20 = models.FileField(verbose_name='Adicionales B', upload_to='adj', blank=True, null=True)\n adj21 = models.FileField(verbose_name='Adicionales C', upload_to='adj', blank=True, null=True)\n\n adj29 = models.FileField(verbose_name='Adicionales D', upload_to='adj', blank=True, null=True)\n adj30 = models.FileField(verbose_name='Adicionales E', upload_to='adj', blank=True, null=True)\n adj31 = models.FileField(verbose_name='Adicionales F', upload_to='adj', blank=True, null=True)\n adj32 = models.FileField(verbose_name='Adicionales G', upload_to='adj', blank=True, null=True)\n adj33 = models.FileField(verbose_name='Adicionales H', upload_to='adj', blank=True, null=True)\n adj34 = models.FileField(verbose_name='Adicionales I', upload_to='adj', blank=True, null=True)\n\n adj35 = models.FileField(verbose_name='Extra A', upload_to='adj', blank=True, null=True)\n\n def filename(self):\n return os.path.basename(self.file.name)\n\n def __str__(self):\n return u'%s' % self.investigacion\n\n\ndef resize_adjuntos(sender, **kwargs):\n if len(str(kwargs['instance'].adj2)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj2), size_x=1600)\n\n if len(str(kwargs['instance'].adj3)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj3), size_x=1600)\n\n if len(str(kwargs['instance'].adj4)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj4), size_x=1600)\n\n if len(str(kwargs['instance'].adj5)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj5), size_x=1600)\n\n if len(str(kwargs['instance'].adj6)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj6), size_x=1600)\n\n if len(str(kwargs['instance'].adj7)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj7), size_x=1600)\n\n if len(str(kwargs['instance'].adj36)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj36), size_x=1600)\n\n if len(str(kwargs['instance'].adj8)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj8), size_x=1600)\n\n if len(str(kwargs['instance'].adj9)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj9), size_x=1600)\n\n if len(str(kwargs['instance'].adj10)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj10), size_x=1600)\n\n if len(str(kwargs['instance'].adj11)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj11), size_x=1600)\n # adj12\n if len(str(kwargs['instance'].adj12)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj12), size_x=1600)\n\n if len(str(kwargs['instance'].adj13)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj13), size_x=1600)\n\n if len(str(kwargs['instance'].adj14)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj14), size_x=1600)\n\n if len(str(kwargs['instance'].adj16)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj16), size_x=1600)\n if len(str(kwargs['instance'].adj17)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj17), size_x=1600)\n\n if len(str(kwargs['instance'].adj18)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj18), size_x=1600)\n if len(str(kwargs['instance'].adj37)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj37), size_x=1600)\n if len(str(kwargs['instance'].adj19)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj19), size_x=1600)\n if len(str(kwargs['instance'].adj20)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj20), size_x=1600)\n if len(str(kwargs['instance'].adj21)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj21), size_x=1600)\n\n if len(str(kwargs['instance'].adj29)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj29), size_x=1600)\n if len(str(kwargs['instance'].adj30)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj30), size_x=1600)\n if len(str(kwargs['instance'].adj31)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj31), size_x=1600)\n if len(str(kwargs['instance'].adj32)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj32), size_x=1600)\n if len(str(kwargs['instance'].adj33)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj33), size_x=1600)\n if len(str(kwargs['instance'].adj34)):\n ImgOpt.resize(file_path=settings.MEDIA_ROOT + '/' + str(kwargs['instance'].adj34), size_x=1600)\n\n\npost_save.connect(resize_adjuntos, sender=Adjuntos)\n","sub_path":"project/app/adjuntos/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"593847063","text":"# Author: twmicro, chicherintim@gmail.com\n\n# imports\nimport vk_api\nimport time\nimport sys, traceback\nimport datetime\n\n# variables\n\nvalues = {'out':0, 'count':100, 'time_offset':60, 'group_id':160615635}\nOPERATORS = {'+': (1, lambda x, y: x + y), '-': (1, lambda x, y: x - y),\n '*': (2, lambda x, y: x * y), '/': (2, lambda x, y: x / y)}\nPI = 3.14\nCONFIG_VARIABLES = {'П':3.14}\n\n# authorize\n\nvk = vk_api.VkApi(token='cf60cf5f6f4e49')\nvk._auth_token()\n\n# functions\n\ndef write_msg(user_id, s):\n vk.method('messages.send', {'user_id': user_id, 'message': s})\n\ndef now_wd():\n return datetime.datetime.now().weekday() + 1\n\ndef wd_string():\n days = ['понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота', 'воскресенье']\n return days[now_wd() - 1]\n\ndef now_mth():\n months = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь',\n 'Ноябрь', 'Декабрь']\n return months[datetime.datetime.now().month - 1]\ndef eval_(formula):\n def parse(formula_string):\n number = ''\n index = 0\n for s in formula_string:\n #for i in range(0, len(CONFIG_VARIABLES) - 1):\n # if s == CONFIG_VARIABLES.keys()[i]:\n # yield CONFIG_VARIABLES.values()[i]\n if s in '1234567890.':\n number += s\n elif s == 'П':\n yield PI\n elif s == 'И':\n pass\n elif number:\n yield float(number)\n number = ''\n if s in OPERATORS or s in \"()\":\n yield s\n index+=1\n if number:\n yield float(number)\n\n def shunting_yard(parsed_formula):\n stack = []\n for token in parsed_formula:\n if token in OPERATORS:\n while stack and stack[-1] != \"(\" and OPERATORS[token][0] <= OPERATORS[stack[-1]][0]:\n yield stack.pop()\n stack.append(token)\n elif token == \")\":\n while stack:\n x = stack.pop()\n if x == \"(\":\n break\n yield x\n elif token == \"(\":\n stack.append(token)\n else:\n yield token\n while stack:\n yield stack.pop()\n\n def calc(polish):\n stack = []\n for token in polish:\n if token in OPERATORS:\n y, x = stack.pop(), stack.pop()-0\n stack.append(OPERATORS[token][1](x, y))\n else:\n stack.append(token)\n return stack[0]\n\n return calc(shunting_yard(parse(formula)))\n\n# loop\nwhile True:\n try:\n response = vk.method('messages.getConversations', values)\n #if response['items']:\n #values['last_message_id'] = response['items'][0]['id']\n for item in response['items']:\n\n if item['last_message']['text']==\"Привет!\":\n answer = 'И вам привет!'\n elif item['last_message']['text'] == \"Время\":\n time = datetime.datetime.time(datetime.datetime.now())\n answer = str(time.hour) + ':' + str(time.minute)\n elif item['last_message']['text'] == \"День\":\n answer = 'Cегодня ' + wd_string()\n elif item['last_message']['text'] == \"День по счету\":\n answer = 'Cегодня ' + str(now_wd()) + ' день недели'\n elif item['last_message']['text'] == \"Месяц\":\n answer = now_mth()\n elif item['last_message']['text'] == \"Пока\":\n answer = 'Пока'\n elif item['last_message']['text'] == \"Как дела?\":\n answer = 'Хорошо'\n elif item['last_message']['text'] == \"Хей\":\n answer = 'Привет братан'\n else:\n try:\n answer = eval_(item['last_message']['text'])\n except:\n answer = 'Не понял :)'\n write_msg(item['last_message']['from_id'], answer)\n #print(item['last_message']['from_id'])\n print(datetime.datetime.now(),'from id {} sent message = {} we answered = {}'.\n format(item['last_message']['from_id'],item['last_message']['text'],answer))\n time.sleep(0.5)\n except:\n pass\n","sub_path":"VKBot.py","file_name":"VKBot.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"246324648","text":"from __future__ import print_function, division\nfrom builtins import range\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Bandit:\n # a code that simulates casino machines (bandit)\n # goal: pick 3 bandits and find the best moment to play in each one\n\n def __init__(self, m):\n self.m = m\n self.mean = 0 # estimate of bandits mean\n self.N = 0 # number of plays\n\n def pull(self):\n # simulates pulling the bandits arm\n return np.random.randn() + self.m\n\n def update(self, x):\n # x is the latest sample received from the bandit\n self.N += 1\n self.mean = (1 - 1.0 / self.N) * self.mean + 1.0 / self.N * x\n\ndef run_experiment(m1, m2, m3, eps, N):\n # there's 3 different means because we compare 3 bandits in this example\n bandits = [Bandit(m1), Bandit(m2), Bandit(m3)]\n data = np.empty(N)\n \n for i in xrange(N):\n # epsilon greedy\n\n # generate a random number P between 0 and 1\n p = np.random.random()\n\n if p < eps:\n # choose a bandit at random\n j = np.random.choice(3)\n else:\n # choose the bandit with the best current sample mean\n j = np.argmax([b.mean for b in bandits])\n\n # pulling the bandit\n x = bandits[j].pull()\n\n # update the bandit with the reward x got\n bandits[j].update(x)\n\n # for the plot\n data[i] = x\n\n # calculate the cumulative average\n cumulative_average = np.cumsum(data) / (np.arange(N) + 1)\n\n # plot moving average ctr\n plt.plot(cumulative_average)\n plt.plot(np.ones(N) * m1)\n plt.plot(np.ones(N) * m2)\n plt.plot(np.ones(N) * m3)\n plt.xscale('log')\n plt.show()\n\n for b in bandits:\n print(b.mean)\n\n return cumulative_average\n\n\nif __name__ == '__main__':\n # do the same experiment 3 times, with different espilons\n\n # when epsilon is 10%\n c_1 = run_experiment(1.0, 2.0, 3.0, 0.1, 100000)\n\n # when epsilon is 5%\n c_05 = run_experiment(1.0, 2.0, 3.0, 0.05, 100000)\n\n # when epsilon is 1%\n c_01 = run_experiment(1.0, 2.0, 3.0, 0.01, 100000)\n\n # log scale plot\n plt.plot(c_1, label='eps = 0.1')\n plt.plot(c_05, label='eps = 0.05')\n plt.plot(c_01, label='eps = 0.01')\n plt.legend()\n plt.xscale('log')\n plt.show()\n\n # linear plot\n plt.plot(c_1, label='eps = 0.1')\n plt.plot(c_05, label='eps = 0.05')\n plt.plot(c_01, label='eps = 0.01')\n plt.legend()\n plt.show()\n\n","sub_path":"compairing_epsylons.py","file_name":"compairing_epsylons.py","file_ext":"py","file_size_in_byte":2303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"478858173","text":"\"\"\"\n@Project : decaNLP\n@Module : data_load.py\n@Author : Deco [deco@cubee.com]\n@Created : 8/2/18 2:49 PM\n@Desc : \n\"\"\"\nimport logging\nimport logging.handlers\nimport os\nfrom pprint import pformat\nimport torch\nfrom text import torchtext\nimport arguments\nfrom util import (get_splits, set_seed)\n\n\ndef initialize_logger(args, rank='data_load.py'):\n # set up file logger\n logger = logging.getLogger(f'process_{rank}')\n logger.setLevel(logging.DEBUG)\n handler = logging.handlers.RotatingFileHandler(\n os.path.join(args.log_dir, f'process_{rank}.log'),\n maxBytes=1024*1024*10, backupCount=1)\n handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(name)s - %(lineno)d - %(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n handler = logging.StreamHandler()\n handler.setFormatter(formatter)\n handler.setLevel(logging.DEBUG)\n logger.addHandler(handler)\n logger.propagate = False\n return logger\n\n\ndef prepare_data(args, field, logger):\n\n if field is None:\n logger.info(f'Constructing field')\n FIELD = torchtext.data.ReversibleField(\n batch_first=True, init_token='', eos_token='',\n lower=args.lower, include_lengths=True)\n else:\n FIELD = field\n\n logger.debug(FIELD)\n\n train_sets, val_sets, vocab_sets = [], [], []\n # train sets, validation sets\n for task in args.train_tasks:\n logger.info(f'Loading {task}')\n # kwargs = {'test': None}\n # kwargs['subsample'] = args.subsample\n # kwargs['validation'] = None\n kwargs = {'test': None,\n 'subsample': args.subsample,\n # 'subsample': 20000000\n 'validation': None\n }\n logger.info(f'Adding {task} to training datasets')\n split = get_splits(args, task, FIELD, **kwargs)[0]\n # 取了tuple的第一个元素,只保留train_data,不要validation data\n # split = torchtext.datasets.generic.SQuAD.splits(fields=FIELD,\n # root=args.data, **kwargs)\n logger.info(f'{task} has {len(split)} training examples')\n logger.debug(type(split))\n train_sets.append(split)\n\n logger.debug(args.vocab_tasks)\n\n if args.vocab_tasks is not None and task in args.vocab_tasks:\n vocab_sets.extend(split)\n\n logger.debug(train_sets)\n\n # return FIELD, train_sets, val_sets\n\n\ndef main():\n args = arguments.parse()\n if args is None:\n return\n set_seed(args)\n # 给numpy and torch设定seed\n logger = initialize_logger(args)\n logger.info(f'Arguments:\\n{pformat(vars(args))}')\n # 调用vars(args)的format函数,得到字符串?\n # pformat是一种format函数,从pprint中引入的\n\n field, save_dict = None, None\n # tuple unpacking\n if args.load is not None:\n logger.info(f'Loading field from {os.path.join(args.save, args.load)}')\n save_dict = torch.load(os.path.join(args.save, args.load))\n field = save_dict['field']\n # field is the value in the 'field' key of the data\n\n logger.info(field)\n\n # field is None\n prepare_data(args, field, logger)\n # field, train_sets, val_sets = prepare_data(args, field, logger)\n\n\nif __name__ == '__main__':\n# python decaNLP/data_load.py --train_tasks squad --gpus 0 --train_batch_tokens 5000 --val_batch_size 128\n\n main()\n","sub_path":"data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"66185162","text":"#!/usr/bin/env python\n\nimport time\nfrom serialport import board\nimport sys\n\n# Callback function (temp)\nvalue = 0\n\n# delay()\ndef delay(num):\n num = float(num)\n time.sleep(num / 1000.0)\n\ndef print_analog(data):\n global value\n value = data [2]\n\n# digital_write()\ndef digital_write(digital_pin, val):\n board.set_pin_mode(digital_pin, board.OUTPUT, board.DIGITAL)\n board.digital_write(digital_pin, val)\n\n# analog_read()\ndef analog_init(analog_pin):\n board.set_pin_mode(analog_pin, board.INPUT, board.ANALOG)\n\ndef analog_read(analog_pin):\n print(\"Pino: \" + str(analog_pin))\n board.set_pin_mode(analog_pin, board.INPUT, board.ANALOG)\n value = board.analog_read(analog_pin)\n return value\n print(\"Valor: \" + str(value))\n\n# Servo\ndef servo(digital_pin):\n SERVO_BASE = digital_pin\n board.servo_config(SERVO_BASE)\n for pos in range(0, 175):\n board.digital_write(SERVO_BASE, pos)\n delay(0.010)\n for pos in range(175, 0, -1):\n board.digital_write(SERVO_BASE, pos)\n delay(0.010)\n\n# blink()\ndef blink(digital_pin, led_delay, led_range):\n for i in range(led_range):\n digital_write(digital_pin, 1)\n delay(led_delay)\n digital_write(digital_pin, 0)\n delay(led_delay)\n board.reset()\n\n# handler definition\ndef signal_handler (sig, frame):\n print ('You pressed Ctrl+C!!!!')\n if board is not None:\n board.reset ()\n sys.exit (0)\n","sub_path":"scripts/unoIDE/serial/boardsetup.py","file_name":"boardsetup.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"36708671","text":"import sqlite3 as sql\nfrom dataclasses import dataclass\nfrom novelreader.helpers import plog, show\nfrom wescrape.helpers import identify_status\nfrom wescrape.models.novel import Novel, Chapter, Meta, Website, Status\n\n@dataclass\nclass Chapter(Chapter):\n has_read: bool = False\n\nclass Database:\n INSTANCE = None\n\n @classmethod\n def build(cls, db_file):\n \"\"\"Build An Instance Of Database\"\"\"\n if cls.INSTANCE is None:\n cls.INSTANCE = Database(db_file)\n plog([\"created\"], \"database instance\")\n return cls.INSTANCE\n else:\n plog([\"exists\"], \"database instance\")\n return cls.INSTANCE\n \n \n def __init__(self, db_file):\n self.__conn = sql.connect(db_file)\n self.__conn.row_factory = sql.Row\n\n def commit(self):\n self.__conn.commit()\n\n @classmethod\n def instance(cls):\n if cls.INSTANCE is not None:\n return cls.INSTANCE\n else:\n plog([\"missing\"], \"database instance\")\n \n @classmethod\n def close(cls):\n \"\"\"Close Database Connection, Clear Instance\"\"\"\n if cls.INSTANCE is not None:\n cls.INSTANCE.conn.close()\n cls.INSTANCE = None\n plog([\"removed\"], \"database instance\")\n else:\n plog([\"missing\"], \"database instance\")\n\n @property\n def conn(self):\n return self.__conn\n\n # @show\n def __conditions_builder(self, conditions: [(str, any)]): \n if type(conditions) == list:\n values = tuple([c[1] for c in conditions]) \n part = \" AND \".join([f\"{c[0].upper()} = ?\" for c in conditions])\n conditions = \" \".join([\"WHERE\", part]) if len(conditions) > 0 else \"\"\n else: \n values = (conditions[1],)\n conditions = f\"where {conditions[0].upper()} = ?\"\n return conditions, values\n\n # @show\n def __select(self, table: str, cols:[str] = [\"*\",], conditions: [(str, any)] = []):\n cols = \" \".join(cols) if type(cols) == list else cols\n conditions, values = self.__conditions_builder(conditions)\n statement = f\"\"\"SELECT {cols} FROM {table} {conditions}\"\"\".strip().upper()\n rows = self.__conn.execute(statement, values)\n return rows\n\n def __update(self, table: str, cols=[str], conditions=[(str, any)]):\n valid_tables = [\"novels\", \"chapters\", \"metas\"]\n if table.lower() not in valid_tables:\n return None\n cols = \", \".join(cols) if type(cols) == list else cols\n conditions, values = self.__conditions_builder(conditions)\n statement = f\"UPDATE {table} SET {cols} {conditions}\".strip().upper()\n self.__conn.execute(statement, values)\n\n def __convert_row(self, row: dict, obj_type):\n converted_row = None\n if row:\n try:\n if obj_type == Novel:\n converted_row = Novel(\n url=row[\"url\"],\n title=row[\"title\"],\n thumbnail=row[\"thumbnail\"]\n )\n elif obj_type == Chapter:\n converted_row = Chapter(\n id=row[\"chapter_id\"],\n url=row[\"url\"],\n title=row[\"title\"],\n content=row[\"content\"],\n has_read=bool(row[\"has_read\"])\n )\n elif obj_type == Meta:\n converted_row = Meta(\n authors=row[\"authors\"].split(\", \"),\n genres=row[\"genres\"].split(\", \"),\n rating=row[\"rating\"],\n release_date=row[\"release_date\"],\n status=identify_status(row[\"status\"]),\n description=row[\"description\"],\n )\n except Exception as ex:\n raise ex\n return converted_row\n\n def __convert_rows(self, rows: [dict], convert_type):\n converted_rows = []\n if rows:\n for row in rows:\n converted_row = self.__convert_row(row, convert_type)\n if converted_row:\n converted_rows.append(converted_row)\n return converted_rows\n \n # create functions\n def create_novels_table(self):\n statement = \"\"\"CREATE TABLE IF NOT EXISTS NOVELS(\n URL TEXT PRIMARY KEY UNIQUE,\n TITLE TEXT NOT NULL,\n THUMBNAIL TEXT NOT NULL);\n \"\"\"\n self.__conn.execute(statement)\n\n def create_chapters_table(self):\n statement = \"\"\"CREATE TABLE IF NOT EXISTS CHAPTERS(\n URL TEXT PRIMARY KEY,\n CHAPTER_ID TEXT NOT NULL,\n TITLE TEXT NOT NULL,\n CONTENT TEXT,\n NOVEL_URL TEXT NOT NULL,\n HAS_READ INTEGER,\n FOREIGN KEY (NOVEL_URL)\n REFERENCES NOVELS (URL));\n \"\"\"\n self.__conn.execute(statement)\n\n def create_metas_table(self):\n statement = \"\"\"CREATE TABLE IF NOT EXISTS METAS(\n ID INTEGER PRIMARY KEY AUTOINCREMENT,\n AUTHORS TEXT,\n GENRES TEXT,\n RATING TEXT,\n RELEASE_DATE TEXT,\n STATUS TEXT,\n DESCRIPTION TEXT,\n NOVEL_URL TEXT UNIQUE NOT NULL,\n FOREIGN KEY (NOVEL_URL)\n REFERENCES NOVELS (URL));\n \"\"\"\n self.__conn.execute(statement)\n\n # insert functions\n def insert_novel(self, novel: Novel):\n statement = \"\"\"INSERT INTO NOVELS (URL, TITLE, THUMBNAIL) VALUES (?, ?, ?);\"\"\"\n self.__conn.execute(statement, (novel.url, novel.title, novel.thumbnail))\n\n def insert_meta(self, novel_url: str, meta: Meta):\n statement = \"\"\"INSERT INTO \n METAS (\n AUTHORS, GENRES, RATING, STATUS, RELEASE_DATE, DESCRIPTION, NOVEL_URL\n )\n VALUES (?, ?, ?, ?, ?, ?, ?);\"\"\"\n if type(meta) == Meta:\n meta = meta.__dict__\n \n values = (\n \", \".join(meta[\"authors\"]),\n \", \".join(meta[\"genres\"]),\n meta[\"rating\"],\n meta[\"status\"].name,\n meta[\"release_date\"],\n meta[\"description\"],\n novel_url\n )\n self.__conn.execute(statement, values)\n\n def insert_chapter(self, novel_url: str, chapter: Chapter):\n statement = \"\"\"INSERT INTO CHAPTERS (CHAPTER_ID, URL, TITLE, CONTENT, NOVEL_URL) VALUES(?, ?, ?, ?, ?);\"\"\"\n \n if type(chapter) == Chapter:\n chapter = chapter.__dict__\n\n values = (\n chapter[\"id\"],\n chapter[\"url\"],\n chapter[\"title\"],\n chapter[\"content\"],\n novel_url\n )\n self.__conn.execute(statement, values)\n\n def update_chapter(self, chapter: Chapter):\n \"\"\"Update cols of selected chapter whose col URL is `url`\"\"\"\n if type(chapter) == Chapter:\n chapter = chapter.__dict__\n self.update_chapter_v2(chapter)\n # statement = \"\"\"UPDATE CHAPTERS \n # SET CHAPTER_ID = ?,\n # TITLE = ?,\n # CONTENT = ?,\n # HAS_READ = ?\n # WHERE URL = ?;\"\"\"\n\n # values = (\n # chapter[\"id\"],\n # chapter[\"title\"],\n # chapter[\"content\"],\n # chapter[\"has_read\"],\n # chapter[\"url\"]\n # )\n\n # self.__conn.execute(statement, values)\n\n def update_chapter_v2(self, chapter: Chapter):\n self.__update(\n \"chapters\",\n [\"content\"],\n (\"url\", chapter[\"url\"])\n )\n \n def update_meta(self, meta: Meta):\n self.__update(\n \"metas\",\n [\"status\"],\n [(\"novel_url\", meta.novel_url)]\n )\n\n def select_novels(self) -> [Novel]:\n cur = self.__select(\"novels\")\n novel_rows = cur.fetchall()\n # novel_rows = self.__conn.execute(\"\"\"SELECT * FROM NOVELS\"\"\").fetchall()\n novels = self.__convert_rows(novel_rows, Novel)\n return novels\n\n def select_novel(self, novel_url) -> Novel:\n cur = self.__select(\"novels\", conditions=[(\"url\", novel_url)])\n novel_row = cur.fetchone()\n novel = self.__convert_row(novel_row, Novel)\n return novel\n\n def select_chapters(self, novel_url: str) -> [Chapter]:\n cur = self.__select(\"chapters\", conditions=(\"novel_url\", novel_url))\n chapter_rows = cur.fetchall()\n chapters = self.__convert_rows(chapter_rows, Chapter)\n return chapters\n\n def select_chapter(self, chapter_url: str) -> Chapter:\n cur = self.__select(\"chapters\", conditions=(\"url\", chapter_url))\n chapter_row = cur.fetchone()\n chapter = self.__convert_row(chapter_row, Chapter)\n return chapter\n\n def select_metas(self) -> [Meta]:\n cur = self.__select(\"metas\")\n meta_rows = cur.fetchall()\n metas = self.__convert_rows(meta_rows, Meta)\n return metas\n\n def select_meta(self, novel_url) -> Meta:\n cur = self.__select(\"metas\", conditions=(\"novel_url\", novel_url))\n meta_row = cur.fetchone()\n meta = self.__convert_row(meta_row, Meta)\n return meta\n","sub_path":"novelreader/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"569810311","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 22 14:50:38 2019\n\n@author: Shubham\n\"\"\"\n\nimport os, time, random, argparse\nimport os.path as osp\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport collections\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport cv2\nfrom torch.utils import data\nfrom PIL import Image\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import MultiStepLR\nimport torch.optim as optim\nimport time\nimport pickle as pkl\nimport h5py\nimport copy\nimport glob\nimport torchvision.transforms as trans\n\nclass h5_loader(data.Dataset):\n def __init__(self, file_path):\n self.file_list = [f for f in glob.glob(os.path.join(file_path, '*.h5'))]\n self.len = len(self.file_list)\n\n def __getitem__(self, index):\n self.file = h5py.File(self.file_list[index], 'r')\n self.data = self.file.get('Feature')\n self.data = torch.tensor(np.array(self.data)) \n self.label = self.file.get('label')\n return np.array(self.data), np.array(self.label)\n\n def __len__(self):\n return self.len\n\nclass Index_pred(nn.Module):\n def __init__(self, in_channels=60, out_channels=60):\n super(Index_pred, self).__init__()\n self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\n \n def forward(self, x):\n out = self.conv1(x)\n max_val, _ = torch.max(out, dim = 1)\n max_val, _ = torch.max(max_val, dim = 1) \n out = F.sigmoid(out)\n return out\n \ndef train(trainloader, net, criterion, optimizer, device, scheduler, epochs=2):\n for epoch in range(epochs):\n scheduler.step()\n start = time.time()\n running_loss = 0.0\n for i, (images, target) in enumerate(trainloader):\n images = images.to(device)\n target = target.to(device).float()\n target = target/4\n optimizer.zero_grad()\n output = net(images)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n running_loss += loss.item()\n if i % 100 == 99: \n end = time.time()\n print('[epoch %d, iter %5d] loss: %.3f eplased time %.3f' %\n (epoch + 1, i + 1, running_loss / 100, end-start))\n start = time.time()\n running_loss = 0.0\n print('Finished Training')\n \ndef test(testloader, net, device):\n correct = 0\n total = 0\n with torch.no_grad():\n for data in testloader:\n pred, labels = data\n _, c, h, w = pred.shape\n pred = pred.to(device)\n labels = labels.to(device)\n labels = labels/4\n outputs = net(pred)\n # out_c = copy.deepcopy(outputs)\n out_c = outputs\n outputs[(out_c >= 0.0) & (out_c < 0.25)] = 0\n outputs[(out_c >= 0.25) & (out_c < 0.5)] = 1\n outputs[(out_c >= 0.5) & (out_c < 0.75)] = 2\n outputs[(out_c >= 0.75) & (out_c <= 1.0)] = 3\n print(outputs)\n total = c * h * w\n labels = labels * 4\n correct = (outputs.long() == labels.long()).sum().item()\n print('Accuracy of the network on the 1 sample: %d %%' % (\n 100 * correct / total))\n \ndef main(trainloader, testloader):\n os.environ['CUDA_VISIBLE_DEVICES']='2'\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print('Running on device : {}'.format(device))\n #device = torch.device('cpu')\n net = Index_pred().to(device)\n saved_state_dict = torch.load('index_pred.pth')\n net.load_state_dict(saved_state_dict.state_dict())\n criterion = nn.MSELoss()\n # optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9, weight_decay=5e-4)\n optimizer = optim.Adam(net.parameters() ,lr=0.01, eps=1e-08)\n scheduler = MultiStepLR(optimizer, milestones=[50, 100], gamma=0.1)\n # train(trainloader, net, criterion, optimizer, device, scheduler)\n # torch.save(net, 'index_pred1.pth') # save the model\n test(testloader, net, device) # testing\n \nif __name__ == \"__main__\":\n # obg = h5_loader('./SWWAE_dataset/')\n # print(obg[0])\n train_loader = torch.utils.data.DataLoader(h5_loader('./SPN_dataset/'),batch_size=2, shuffle=True, num_workers=1, pin_memory=True) # Data loader for train set\n main(train_loader, train_loader)","sub_path":"SPN_training/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"300344194","text":"import os\nimport requests\nfrom pprint import pprint\nimport pymysql\nimport json\n\ndef get_conn():\n return pymysql.connect(\n host=os.getenv('mysql_host'),\n user=os.getenv('mysql_user'),\n password=os.getenv('mysql_pw'),\n port=3306,\n db='projectdb',\n charset='utf8')\n\nsql_list = []\n\ndate = ''\nmain = ''\ndesc = ''\nmaxtemp = ''\nmintemp = ''\n\nwith open('weathercode.json') as json_file: \n codes = json.load(json_file)\n\napikey = os.getenv('WeatherAPI')\n\nfor citycode, cityname in codes.items():\n url = \"http://api.openweathermap.org/data/2.5/forecast?id={}&APPID={}\".format(citycode, apikey)\n\n res = requests.get(url).text\n\n weather = json.loads(res)\n\n\n for w in weather['list']:\n \n dt = w['dt_txt']\n\n if dt[11:19] not in ('15:00:00', '03:00:00'):\n continue\n else:\n desc = w['weather'][0]['description']\n main = w['weather'][0]['main']\n\n date = dt[0:10]\n\n tp = w['main']['temp']\n temp = round(tp - 273.15)\n\n if (dt[11:19] == '03:00:00'):\n maxtemp = temp\n\n continue\n\n else:\n if maxtemp == \"\":\n maxtemp = 100\n\n mintemp = temp\n\n tupledata = (citycode, cityname, date, main, desc, mintemp, maxtemp)\n\n print(tupledata)\n \n sql_list.append(tupledata)\n\n\nsql_insert = 'insert into Weather(citycode, cityname, dt, main, description, mintemp, maxtemp) values(%s, %s, %s, %s, %s, %s, %s)'\n\nconn = get_conn()\n\n\nwith conn:\n cur = conn.cursor()\n cur.executemany(sql_insert, sql_list)\n\n\nprint(\"The weather data have been successfully stored\")\n\n\n\n\n\n\n\n \n\n\n\n","sub_path":"weather/weathertomysql.py","file_name":"weathertomysql.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"118012435","text":"# GradCAM, Guided Backpropagation, and guided GradCAM utilities\n# Importations\nimport sys\n# sys.path.append('FireOccurrence/experiments')\n\nimport os\nimport numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions\nfrom tensorflow.keras.applications.resnet50 import ResNet50\nfrom tensorflow.keras.models import Model\nfrom tqdm import tqdm\nfrom compress_pickle import dump as cdump\n\nimport tensorflow as tf\nfrom tensorflow.python.framework import ops\ntf.compat.v1.disable_eager_execution()\n\n\n# Build the model\ndef build_model(model=None, \n modelPath=None,\n model_constructor=None,\n dims=(38,31,1),\n pretrained='VGG16'):\n\n # Multiple returns\n if model is None and modelPath is None:\n if pretrained == 'VGG16':\n return VGG16(include_top=True, weights='imagenet')\n elif pretrained == 'ResNet50':\n return ResNet50(include_top=True, weights='imagenet')\n if model is not None:\n # Model from scratch\n model = model\n return model\n \n if modelPath is not None:\n return load_model(modelPath)\n\n# Load and preprocess image\ndef load_image(path,\n targetSize=(32,38),\n preprocess=True):\n \n x = image.load_img(path, target_size=targetSize)\n if preprocess:\n x = image.img_to_array(x)\n x = np.expand_dims(x, axis=0)\n x = preprocess_input(x)\n return x\n\n# Deprocess image\ndef deprocess_image(x):\n \"\"\"Same normalization as in:\n https://github.com/fchollet/keras/blob/master/examples/conv_filter_visualization.py\n \"\"\"\n x = x.copy()\n if np.ndim(x) > 3:\n x = np.squeeze(x)\n # normalize tensor: center on 0., ensure std is 0.1\n x -= x.mean()\n x /= (x.std() + 1e-5)\n x *= 0.1\n\n # clip to [0, 1]\n x += 0.5\n x = np.clip(x, 0, 1)\n\n # convert to RGB array\n x *= 255\n if K.image_data_format() == 'th':\n x = x.transpose((1, 2, 0))\n x = np.clip(x, 0, 255).astype('uint8')\n return x\n\n# Utility function to normalize a tensor by its L2 norm\ndef normalize(x):\n return (x + 1e-10) / (K.sqrt(K.mean(K.square(x))) + 1e-10)\n\n# Guided Model: Changes gradient function for all ReLu activations according to Guided Backpropagation.\ndef build_guided_model(model):\n if \"GuidedBackProp\" not in ops._gradient_registry._registry:\n @ops.RegisterGradient(\"GuidedBackProp\")\n def _GuidedBackProp(op, grad):\n dtype = op.inputs[0].dtype\n return grad * tf.cast(grad > 0., dtype) * \\\n tf.cast(op.inputs[0] > 0., dtype)\n\n g = tf.compat.v1.get_default_graph()\n with g.gradient_override_map({'Relu': 'GuidedBackProp'}):\n new_model = build_model(model)\n return new_model\n\n# Guided Backpropagation method for visualizing input saliency\ndef guided_backprop(input_model,\n images,\n layer_name):\n \n input_imgs = input_model.input\n #print('input_imgs:', input_imgs)\n layer_output = input_model.get_layer(layer_name).output\n grads = K.gradients(layer_output, input_imgs)[0]\n backprop_fn = K.function([input_imgs, K.learning_phase()], [grads])\n grads_val = backprop_fn([images, 0])[0]\n return grads_val\n\n# GradCAM method for visualizing input saliency\ndef grad_cam(input_model,\n image,\n cls,\n layer_name,\n classes=[0],\n targetSize=(32,38)):\n\n #image = np.expand_dims(image, axis=0)\n loss = tf.gather_nd(input_model.output, np.dstack([range(1), classes])[0])\n layer_output = input_model.get_layer(layer_name).output\n grads = K.gradients(loss, layer_output)[0]\n gradient_fn = K.function([input_model.input, K.learning_phase()], [layer_output, grads])\n\n conv_output, grads_val = gradient_fn([image, 0]) \n weights = np.mean(grads_val, axis=(1, 2))\n cams = np.einsum('ijkl,il->ijk', conv_output, weights)\n \n # Process CAMs\n new_cams = np.empty((1, targetSize[0], targetSize[1]))\n #print(\"new_camsShape:\", new_cams.shape)\n for i in range(new_cams.shape[0]):\n cam_i = cams[i] - cams[i].mean()\n cam_i = (cam_i + 1e-10) / (np.linalg.norm(cam_i, 2) + 1e-10)\n new_cams[i] = cv2.resize(cam_i, (targetSize[1], targetSize[0]), cv2.INTER_LINEAR)\n new_cams[i] = np.maximum(new_cams[i], 0)\n new_cams[i] = new_cams[i] / new_cams[i].max()\n \n return np.squeeze(new_cams, axis=0)\n\n# GradCAM method for visualizing input saliency.\n# Same as grad_cam but processes multiple images in one run\ndef grad_cam_batch(input_model,\n images,\n classes,\n layer_name,\n targetSize=(32,38)):\n \n loss = tf.gather_nd(input_model.output, np.dstack([range(images.shape[0]), classes])[0])\n layer_output = input_model.get_layer(layer_name).output\n grads = K.gradients(loss, layer_output)[0]\n gradient_fn = K.function([input_model.input, K.learning_phase()], [layer_output, grads])\n\n conv_output, grads_val = gradient_fn([images, 0]) \n weights = np.mean(grads_val, axis=(1, 2))\n cams = np.einsum('ijkl,il->ijk', conv_output, weights)\n \n # Process CAMs\n new_cams = np.empty((images.shape[0], targetSize[1], targetSize[0]))\n for i in range(new_cams.shape[0]):\n cam_i = cams[i] - cams[i].mean()\n cam_i = (cam_i + 1e-10) / (np.linalg.norm(cam_i, 2) + 1e-10)\n new_cams[i] = cv2.resize(cam_i, targetSize, cv2.INTER_LINEAR)\n new_cams[i] = np.maximum(new_cams[i], 0)\n new_cams[i] = new_cams[i] / new_cams[i].max()\n \n return new_cams\n\n# Compute saliency using all three approaches.\n# -layer_name: layer to compute gradients;\n# -cls: class number to localize (-1 for most probable class).\ndef compute_saliency(model,\n guided_model,\n img_path,\n layer_name='block5_conv3',\n cls=-1,\n visualize=True,\n save=True,\n path=None,\n top_n=2,\n inputSize=(32,38),\n channels=3,\n size=(15, 10)):\n \n # Pre-Process image\n # Loop\n if channels == 1:\n image = cv2.imread(img_path, 0)\n else:\n image = cv2.imread(img_path)\n image = cv2.resize(image, (inputSize[1], inputSize[0]))\n \n if channels == 1:\n image = image.reshape((image.shape[0], image.shape[1], 1))\n \n if channels != 1:\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n \n # To array and process\n image = np.array(image)\n print(\"Shape image:\", image.shape)\n preprocessed_input = image / 255.\n preprocessed_input = np.expand_dims(preprocessed_input, 0)\n print(\"Preprocessed inputs:\", preprocessed_input.shape)\n # Gather predictions\n predictions = model.predict(preprocessed_input)\n \n # Get top n (5 by default)\n top = np.sort(predictions[0])[:top_n][::-1]\n classes = np.argsort(predictions[0])[-top_n:][::-1]\n print(\"top:\", top)\n print(\"predictions:\", predictions)\n print(\"classes:\", classes)\n \n # Predictions\n print('Model prediction:')\n for c, p in zip(classes, np.array(top).flatten()):\n #print(c,p)\n label = 'fire' if c == 1 else 'no_fire'\n print('\\t{:15s}\\t({})\\twith probability {:.3f}'.format(label, c, p))\n \n # If cls = -1, most likely classes\n if cls == -1:\n cls = np.argmax(predictions)\n class_name = \"fire\" if classes[0] == 1 else 'no_fire'\n print(\"Explanation for '{}'\".format(class_name))\n #print(\"cls:\", cls)\n \n # Calculate the 3 methods\n gradcam = generate_gradCAM(batch_size=1, \n layer=layer_name,\n model=model,\n processedimages= preprocessed_input, \n rawimages=preprocessed_input,\n save=False,\n showID=-1,\n title='Test',)\n \n \n #gradcam = grad_cam(model, preprocessed_input / 255., cls, layer_name, classes=classes[cls], targetSize=inputSize)\n print(\"gradcam:\", gradcam.shape)\n gb = guided_backprop(guided_model, preprocessed_input, layer_name)\n print(\"gb:\", gb.shape)\n guided_gradcam = gb * gradcam[..., np.newaxis]\n print(\"guided_backprop:\", guided_gradcam.shape)\n\n # Save outputs\n if save:\n jetcam = cv2.applyColorMap(np.uint8(255 * gradcam), cv2.COLORMAP_JET)\n jetcam = (np.float32(jetcam) + load_image(img_path, preprocess=False)) / 2\n if path is not None:\n gradcamPath = os.path.join(path, 'gradcam.png')\n guidedBackPath = os.path.join(path, 'guided_backprop.png')\n guidedcamPath = os.path.join(path, 'guided_gradcam.png')\n else:\n gradcamPath = 'gradcam.png'\n guidedBackPath = 'guided_backprop.png'\n guidedcamPath = 'guided_gradcam.png'\n \n cv2.imwrite(gradcamPath, np.uint8(jetcam))\n cv2.imwrite(guidedBackPath, deprocess_image(gb[0]))\n cv2.imwrite(guidedcamPath, deprocess_image(guided_gradcam[0]))\n \n # Visualize (show)\n if visualize:\n plt.figure(figsize=size)\n plt.subplot(131)\n plt.title('GradCAM')\n plt.axis('off')\n if len(image.shape) >= 3 and channels == 1:\n image = image.squeeze(-1)\n plt.imshow(image)\n plt.imshow(gradcam[0], cmap='jet', alpha=0.5)\n\n plt.subplot(132)\n plt.title('Guided Backprop')\n plt.axis('off')\n plt.imshow(np.flip(deprocess_image(gb[0]), -1))\n \n plt.subplot(133)\n plt.title('Guided GradCAM')\n plt.axis('off')\n plt.imshow(np.flip(deprocess_image(guided_gradcam[0]), -1))\n plt.show()\n \n return gradcam, gb, guided_gradcam\n\n# Generate gradcam from rawimages\ndef generate_gradCAM(model, \n rawimages,\n processedimages, \n layer, \n batch_size=32, \n save=False,\n savefile=None,\n title='',\n showID=0):\n # Let's set classes for explanations as most probable class for each image.\n top = np.argmax(model.predict(processedimages), 1)\n gradcam = np.empty((processedimages.shape[:-1]))\n \n # Number of pictures\n N = processedimages.shape[0]\n\n # Batch loop\n for i in tqdm(range((N + batch_size - 1) // batch_size)):\n start = i * batch_size\n end = min((i+1) * batch_size, N)\n gradcam[start:end] = grad_cam_batch(model, \n processedimages[start:end],\n top[start:end],\n layer,\n (processedimages.shape[2], processedimages.shape[1]))\n\n # Save file\n if save:\n outfile = 'gradcam.lzma' if savefile is None else savefile\n cdump(gradcam, outfile, compression='lzma')\n\n # Show\n if showID >= 0: \n i = showID\n plt.title(title)\n plt.imshow(rawimages[i])\n plt.imshow(gradcam[i], alpha=0.3, cmap='jet')\n plt.show()\n \n # Return gradcam array\n return gradcam\n\n# Show attention map using the rawimage and gradcam output\ndef show_gradCAM(rawimage, \n gradcam, \n showID=0, \n title=''):\n i = showID\n plt.title(title)\n plt.imshow(rawimage[i])\n plt.imshow(gradcam[i], alpha=0.5, cmap='jet')\n plt.show()\n \n# Generate guided backprop from guided model\ndef generate_guidedbackprop(guided_model, \n processedimages, \n deprocess_object,\n layer, \n batch_size=32, \n save=False,\n savefile=None,\n title='',\n showID=0):\n # Container\n gbp = np.empty((processedimages.shape))\n N = processedimages.shape[0]\n\n # Batch loop\n for i in range((N + batch_size - 1) // batch_size):\n start = i * batch_size\n end = min((i+1) * batch_size, N)\n gbp[start:end] = guided_backprop(guided_model, \n processedimages[start:end], \n layer)\n\n # Save\n if save:\n outfile = 'guided_backprop.lzma' if savefile is None else savefile\n cdump(gradcam, outfile, compression='lzma')\n \n # Show\n if showID >= 0:\n i = showID\n plt.title(title)\n plt.imshow(np.flip(deprocess_object(gbp[i]), -1), cmap='jet')\n plt.show()\n \n # Return guided backprop\n return gbp\n\n# Show guidedbp\ndef show_guidedBP(gbp, \n deprocess_object,\n title='', \n showID=0):\n i = showID\n plt.title(title)\n plt.imshow(np.flip(deprocess_object(gbp[i]), -1), cmap='jet')\n plt.show()\n \n# Generate guided GradCAM\ndef generate_guidedgradCAM(gbp, \n gradcam,\n showID=0,\n save=False,\n savefile=None,\n title='',\n deprocess_object=None):\n # Guided gradCam\n guided_gradcam = gbp * gradcam[..., np.newaxis]\n\n # Save\n if save:\n outfile = 'guided_gradcam.lzma' if savefile is None else savefile\n cdump(guided_gradcam, 'guided_gradcam.lzma', compression='lzma')\n \n # Predictions\n if showID >= 0:\n i = showID\n plt.title(title)\n plt.imshow(deprocess_object(guided_gradcam[i]), \n alpha=0.5, cmap='jet')\n plt.show()\n \n # Return guided gradcam\n return guided_gradcam\n\n# Show guided GradCAM\ndef show_guidedgradCAM(ggcam, \n title='', \n showID=0, \n deprocess_object=None):\n # Predictions\n i = showID\n plt.title(title)\n plt.imshow(deprocess_object(ggcam[i]), \n alpha=0.5, cmap='jet')\n plt.show()\n \n# Process rawimages and gcam and save gcam ones (returns array of images)\ndef gcam_processed(rawimages, \n gcam,\n outGCAM=os.path.join('..', 'exp_outputs', 'GCAM_output'),\n show=False, \n size=(5,5), \n outsize=(128,128)):\n # Process a batch of rawimages\n if not os.path.exists(outGCAM):\n os.makedirs(outGCAM)\n\n # Size\n if show:\n plt.rcParams['figure.figsize'] = size\n\n # Save processed pictures\n for idx, image in enumerate(rawimages):\n fileName = os.path.join(outGCAM, str(idx) + '.png')\n im = plt.imshow(rawimages[idx])\n im2 = plt.imshow(gcam[idx], alpha=0.3, cmap='jet')\n plt.axis('off')\n plt.tight_layout()\n plt.axis(\"tight\") # gets rid of white border\n plt.axis(\"image\") # square up the image instead of filling the \"figure\" space\n plt.savefig(fileName, bbox_inches='tight', pad_inches=0.0)\n\n # Read back the gcam processed\n GCAM_imagesPaths = sorted(list(paths.list_images(outGCAM)))\n GCAM_images = []\n \n # Processe back\n for imagepath in GCAM_imagesPaths:\n image = cv2.imread(imagepath)\n image = cv2.resize(image, outsize)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n GCAM_images.append(image) \n \n # Return\n return GCAM_images\n\n# Process rawimages and gcam and save gcam ones (returns array of images)\ndef gprop_processed(gprop,\n outGPROP=os.path.join('..', 'exp_outputs', 'GPROP_output'),\n deprocess_object=None,\n show=False, \n size=(5,5), \n outsize=(128,128)):\n # Process a batch of rawimages\n if not os.path.exists(outGPROP):\n os.makedirs(outGPROP)\n\n # Save processed pictures\n for idx, image in enumerate(rawimages):\n plt.imsave(os.path.join(outGPROP, str(idx) + '.png'), \n np.flip(deprocess_object(gprop[idx]), -1), \n cmap='jet', format='png')\n \n # Show\n if show:\n plt.rcParams['figure.figsize'] = size\n plt.imshow(np.flip(deprocess_object(gprop[idx]), -1), \n cmap='jet',)\n\n # Read back the gcam processed\n GPROP_imagesPaths = sorted(list(paths.list_images(outGPROP)))\n GPROP_images = []\n \n # Processe back\n for imagepath in GPROP_imagesPaths:\n image = cv2.imread(imagepath)\n image = cv2.resize(image, outsize)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n GPROP_images.append(image) \n \n # Return\n return GPROP_images\n\n# Process rawimages and gcam and save gcam ones (returns array of images)\ndef guidedGCAM_processed(gprop,\n gradcam,\n outGGCAM=os.path.join('..', 'exp_outputs', 'GGCAM_output'),\n deprocess_object=None,\n show=False, \n size=(5,5), \n alpha=0.5,\n outsize=(128,128)):\n # Process a batch of rawimages\n if not os.path.exists(outGGCAM):\n os.makedirs(outGGCAM)\n \n # Guided gradCam\n guided_gradcam = gprop * gradcam[..., np.newaxis]\n\n # Save processed pictures\n for idx, image in enumerate(guided_gradcam):\n plt.imsave(os.path.join(outGGCAM, str(idx) + '.png'), \n np.flip(deprocess_object(guided_gradcam[idx]), -1), \n cmap='jet', format='png')\n \n # Show\n if show:\n plt.rcParams['figure.figsize'] = size\n plt.imshow(np.flip(deprocess_object(guided_gradcam[idx]), -1), \n cmap='jet', alpha=alpha)\n\n # Read back the gcam processed\n GGCAM_imagesPaths = sorted(list(paths.list_images(outGGCAM)))\n GGCAM_images = []\n \n # Processe back\n for imagepath in GGCAM_imagesPaths:\n image = cv2.imread(imagepath)\n image = cv2.resize(image, outsize)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n GGCAM_images.append(image) \n \n # Return\n return GGCAM_images\n\n# Plot all maps in squares\ndef plot_filters(feature_maps, \n size=(20,20), \n cmap=None):\n square = np.sqrt(feature_maps.shape[-1]).astype(np.int)\n ix = 1\n for _ in range(square):\n for _ in range(square):\n # specify subplot and turn of axis\n ax = plt.subplot(square, square, ix)\n ax.set_xticks([])\n ax.set_yticks([])\n\n # plot filter channel in grayscale\n plt.imshow(feature_maps[0, :, :, ix-1], cmap=cmap)\n ix += 1\n\n # show the figure\n plt.rcParams['figure.figsize'] = size[0], size[1]\n plt.show() \n \n# Get conv layers for feature maps\ndef get_featuremaps_model(model, layers_idxs):\n # Check model\n if model == 'VGG16':\n model = VGG16()\n if model == 'ResNet50':\n model = ResNet50()\n \n # Get Outputs\n outputs = [model.layers[i+1].output for i in ixs]\n \n # Generate new model\n model = Model(inputs=model.inputs, outputs=outputs)\n \n # New model with multiple outputs\n return model","sub_path":"src/utils/gradcam_utils_tf2.py","file_name":"gradcam_utils_tf2.py","file_ext":"py","file_size_in_byte":19678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"312009009","text":"import pylab as p\nimport numpy as np\n\n# Setup Parameters\n\n# Values of Mu and Sigma is given \nmu=0.1; \nsigma=0.26; \nS0=39; # Price at time zero\nn_path=1000; # Total number of simulations\nn= n_partitions = 1000; # Number of partitions in the interval \n\n# Create Brownian Paths \nt = p.linspace (0,3,n+1); \ndB = p.randn(n_path,n+1) / p.sqrt(n);\ndB[:,0] = 0; \nB=dB.cumsum(axis=1);\n\n# Calculate stock prices\nnu = mu - sigma*sigma/2;\nS =p.zeros_like(B);\nS[:,0] = S0\nS[:,1:] = S0*p.exp(nu*t[1:]+sigma*B[:,1:]);\n\n#Plot the 5 realizations with x label and y label \nS_plot= S[0:5]\np.plot(t,S_plot.transpose());\np.xlabel('Time, t');\np.ylabel('Stock prices, RM');\np.title('5 REALIZATIONS OF THE GEOMETRIC BROWNIAN MOTION')\np.show();\n\n# Calculate the expected value of S(3)\nlast_price_x = p.array(S[:,-1]);\nexpected_price_S3 = np.mean(last_price_x);\nprint('Expected value, E[S(3)] = ',expected_price_S3);\n\n# Calculate the variance of S(3)\nvariance_S3 = np.var(last_price_x);\nprint('Variance, Var[S(3)] = ',variance_S3);\n\n# Calculate P[S(3)>39]\ny = last_price_x > 39; #find out all the values that are larger than 39\ntotal = p.sum(y) #add together all the values that are larger than 39 \nprobability= total/n_path \nprint('P[S(3)>39] = ' ,probability);\n\n# Calculate E[S(3)|S(3)>39]\nz = p.sum(last_price_x * y) \nexpected_value = z/total\nprint('E[S(3)|S(3)>39] = ' ,expected_value);\n ","sub_path":"gbm.py","file_name":"gbm.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"288651564","text":"\"\"\"\n CDNSim\n\n file: netStreamingPrimitives.py\n\n NEC Europe Ltd. PROPRIETARY INFORMATION\n\n This software is supplied under the terms of a license agreement\n or nondisclosure agreement with NEC Europe Ltd. and may not be\n copied or disclosed except in accordance with the terms of that\n agreement. The software and its source code contain valuable trade\n secrets and confidential information which have to be maintained in\n confidence.\n Any unauthorized publication, transfer to third parties or duplication\n of the object or source code - either totally or in part - is\n prohibited.\n\n Copyright (c) 2016 NEC Europe Ltd. All Rights Reserved.\n\n Author: Anton Ivanov \n\n NEC Europe Ltd. DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,\n INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY\n AND FITNESS FOR A PARTICULAR PURPOSE AND THE WARRANTY AGAINST LATENT\n DEFECTS, WITH RESPECT TO THE PROGRAM AND THE ACCOMPANYING\n DOCUMENTATION.\n\n No Liability For Consequential Damages IN NO EVENT SHALL NEC Europe\n Ltd., NEC Corporation OR ANY OF ITS SUBSIDIARIES BE LIABLE FOR ANY\n DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS\n OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION, OR\n OTHER PECUNIARY LOSS AND INDIRECT, CONSEQUENTIAL, INCIDENTAL,\n ECONOMIC OR PUNITIVE DAMAGES) ARISING OUT OF THE USE OF OR INABILITY\n TO USE THIS PROGRAM, EVEN IF NEC Europe Ltd. HAS BEEN ADVISED OF THE\n POSSIBILITY OF SUCH DAMAGES.\n\n THIS HEADER MAY NOT BE EXTRACTED OR MODIFIED IN ANY WAY.\n\"\"\"\n\nfrom __future__ import print_function\nimport networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy.random\nimport random\nimport Queue\nimport math\nimport csv\nimport sys\nimport os\nimport re\n\nnumpy.random.seed(42)\nrandom.seed(42)\n\nEVENT_RESERVED = 0\nEVENT_USER_REQUEST = 1\nEVENT_STREAM_START = 2\nEVENT_STREAM_COMPLETED = 3\nEVENT_CONSUME_BEGIN = 4\nEVENT_CONSUME_COMPLETE = 5\nEVENT_CONSUME_BUFFER_EMPTY = 6\n\nEVENT_STREAM_EXPAND = 7\nEVENT_NOISE_USER_REQUEST = 8\nEVENT_SWITCH_TO_LIVERATE = 9\nEVENT_CACHE_READY = 10\n\nEVENT_CHANGE_REQUEST_RATE = 11\nEVENT_SIM_FINALIZE = 12\nEVENT_PERIODIC_STATS = 13\n\n\nNAMES_EVENTS = ['---',\n 'Connect reqst',\n 'Dwnl. started',\n 'Dwnl. stopped',\n 'Playing start',\n 'Playing stop',\n 'Buffer empty',\n 'Stream expand',\n 'Noise request',\n 'to live-TRate']\n\nCOLORS_EVENTS = []\nm = plt.cm.get_cmap('Paired')\nfor i in range(1, len(NAMES_EVENTS) + 1):\n COLORS_EVENTS.append(m(float(i) / (len(NAMES_EVENTS) + 1)))\n\nPROPAGATION_DELAY = 0.01\n# Max rates for video streaming quality: 360p, 480p, 720p, 1080p, 2K, 4K\nSTREAM_RATES = [1000000, 2500000, 5000000, 8000000, 10000000, 20000000]\nFAST_BACKBONE_LINK_BANDWIDTH = 40000000000.0 # 40 Gbps\nBACKBONE_LINK_BANDWIDTH = 10000000000.0 # 10 Gbps\nBACKBONE_LINK_DELAY = 0.005 # 5ms in sec\nLAN_LINK_RATE = 25000000.0 # 25 Mbps\nNUMBER_CHANNELS = 200\nEXPAND_INTERVAL = 1 # seconds\n\nMIN_PBK_TIME = 60.0 # sec\nMOD_PBK_TIME = 1800.0 # sec\nMAX_PBK_TIME = 2700.0 # sec\nMEAN_PBK_TIME = (MIN_PBK_TIME + MOD_PBK_TIME + MAX_PBK_TIME) / 3 # sec\n# MEAN_PBK_TIME is valid for triangular distribution\n\nSTREAM_NORMAL = 0\nSTREAM_NOISE = 1\nSTREAM_CACHE = 2\n\nMODEL_USER_BEHAVIOR = True\nLOCAL_CACHE_ONLY = True\n\nglobalStreamID = 0\nglobalNoiseStreamID = 0\nglobalCacheStreamID = 0\nglobalEventID = 0\nglobalCacheID = 1000000\n\n\nclass event:\n __slots__ = ['time', 'objRef', 'type', 'id']\n\n def __init__(self, time, objRef, typ):\n self.time = time\n self.objRef = objRef\n self.type = typ\n global globalEventID\n self.id = globalEventID\n globalEventID += 1\n return\n\n def __lt__(self, other):\n return (self.time, self.id) < (other.time, other.id)\n\n def __ge__(self, other):\n return (self.time, self.id) > (other.time, other.id)\n\n\nclass netLink:\n\n def __init__(self, sim, ca, as_nodeA, as_nodeB):\n self.capacity = float(ca)\n self.netDataStreams = []\n self.as_nodeA = as_nodeA\n self.as_nodeB = as_nodeB\n self.simRef = sim\n return\n\n def __str__(self):\n s = 'netLink: ' + str(self.as_nodeA) + '-' + str(self.as_nodeB) +\\\n ', capacity=' + str(self.capacity) +\\\n ', capacityLeft=' + str(self.getCapacityLeft()) +\\\n ', occupied by ' + str(len(self.netDataStreams)) + ' streams'\n return s\n\n def getCapacityLeft(self):\n capacityLeft = self.capacity\n for s in self.netDataStreams:\n capacityLeft -= s.transmitRate\n return capacityLeft\n\n def getHopsTo(self, link):\n assert link != self\n path = nx.shortest_path(\n self.simRef.urRef.gnGraph.netGraph,\n self.as_nodeA,\n link.as_nodeA\n )\n path.remove(self.as_nodeA)\n path.remove(link.as_nodeA)\n if self.as_nodeB in path:\n path.remove(self.as_nodeB)\n if link.as_nodeB in path:\n path.remove(link.as_nodeB)\n return len(path) + 1\n\n def getFairThroughput(self, nNewStreams):\n res = self.capacity\n nStreams = len(self.netDataStreams) + nNewStreams\n if len(self.netDataStreams) > 0:\n share = self.capacity / nStreams\n nExcludeStreams = 0\n for s in self.netDataStreams:\n if s.bottleneckLink != self and s.transmitRate < share:\n nExcludeStreams += 1\n res -= s.transmitRate\n if nExcludeStreams != nStreams:\n res /= (nStreams - nExcludeStreams)\n return res\n\n def allocateBandwidthForNewStream(self, curTime, newTR):\n for s in self.netDataStreams:\n if newTR < s.transmitRate:\n s.setTransmitRate(newTR, curTime)\n return\n\n def process(self, ev):\n # nothing\n return\n\n\nclass cacheNode:\n\n def __init__(self, sim, gnGraph, ASNum):\n global globalCacheID\n self.id = globalCacheID\n globalCacheID += 1\n self.ASnum = ASNum\n self.simRef = sim\n self.gnGraph = gnGraph\n self.ready = False\n self.waitingStreams = []\n # listStreamsPerChannelPerRate[STREAM_RATE][CHANNEL_NUMBER][STREAM]\n self.cacheStrs = [None] * len(STREAM_RATES) * NUMBER_CHANNELS\n self.lstStrs_Cnl_Rate = [None] * len(STREAM_RATES)\n for j in range(len(STREAM_RATES)):\n self.lstStrs_Cnl_Rate[j] = dict()\n return\n\n def attachNetDataStream(self, stream, curTime):\n if self.ready:\n # attach a stream to the cache instance:\n # a cache stream is created, 'stream' is added as dependent stream\n sRateID = STREAM_RATES.index(stream.consumeRate)\n if stream.channel in self.lstStrs_Cnl_Rate[sRateID]:\n # we have channel with this rate in cache\n self.lstStrs_Cnl_Rate[sRateID][stream.channel].append(\n stream\n )\n else:\n self.lstStrs_Cnl_Rate[sRateID][stream.channel] = [stream]\n if self.cacheStrs[sRateID * NUMBER_CHANNELS + stream.channel] is \\\n None:\n # FIXME: use ip-address as the dest ip instead...\n cSt = netDataStream(\n self.simRef,\n stream.consumeRate,\n stream.srcIP,\n 'cache@'+str(self.ASnum),\n 0,\n stream.channel,\n STREAM_CACHE\n )\n cSt.downCacheRef = self\n path = nx.shortest_path(\n self.gnGraph.netGraph,\n self.ASnum,\n self.gnGraph.ip2as[cSt.srcIP]\n )\n if self.simRef.topArgs.hierarchical:\n # in case of hierarchical caches,\n # on-demand instantiations are not allowed -> 'first=False'\n self.simRef.urRef.routeStreamPath_inclCache(\n path,\n cSt,\n curTime,\n first=False\n )\n else:\n self.simRef.urRef.routeStreamPath(path, cSt, curTime)\n self.cacheStrs[sRateID * NUMBER_CHANNELS + stream.channel] = cSt\n else:\n cSt = self.cacheStrs[sRateID * NUMBER_CHANNELS + stream.channel]\n if cSt.beingConsumed:\n self.simRef.eventPush(\n event(\n curTime + PROPAGATION_DELAY,\n stream,\n EVENT_STREAM_START\n )\n )\n else:\n if self.simRef.topArgs.waitCacheBoot:\n self.waitingStreams.append(stream)\n else:\n return False\n if not stream.connectedToCache:\n stream.upCacheRef = self\n stream.connectedToCache = True\n return True\n\n def detachNetDataStream(self, stream, curTime):\n sRateID = STREAM_RATES.index(stream.consumeRate)\n self.lstStrs_Cnl_Rate[sRateID][stream.channel].remove(stream)\n stream.upCacheRef = None\n if len(self.lstStrs_Cnl_Rate[sRateID][stream.channel]) == 0:\n cSt = self.cacheStrs[sRateID * NUMBER_CHANNELS + stream.channel]\n self.cacheStrs[sRateID * NUMBER_CHANNELS + stream.channel] = None\n cEv = event(curTime, cSt, EVENT_STREAM_COMPLETED)\n cSt.process(cEv)\n if 'static_cache' not in self.gnGraph.netGraph.node[self.ASnum]:\n deleteCache = True\n for sr in range(len(STREAM_RATES)):\n if self.cacheStrs[sr * NUMBER_CHANNELS + stream.channel] \\\n is not None:\n deleteCache = False\n break\n if deleteCache:\n self.gnGraph.netGraph.remove_node(self.id)\n # delete old cache node not to crowd up the topology\n self.gnGraph.netGraph.\\\n node[self.ASnum]['caches'][stream.channel] = None\n self.gnGraph.netGraph.\\\n node[self.ASnum]['nCacheRequests'][stream.channel] = 0\n return\n\n def startDependentStraems(self, cacheStream, curTime):\n cacheStream.updateCounters(curTime)\n cacheStream.beingConsumed = True\n cacheStream.consumePoint = curTime\n channel = cacheStream.channel\n sRateID = STREAM_RATES.index(cacheStream.consumeRate)\n for stream in self.lstStrs_Cnl_Rate[sRateID][channel]:\n if not stream.beingTransmitted:\n self.simRef.eventPush(\n event(\n curTime + PROPAGATION_DELAY,\n stream,\n EVENT_STREAM_START\n )\n )\n return\n\n def getParentCacheStreamTransmitRate(self, stream):\n channel = stream.channel\n sRateID = STREAM_RATES.index(stream.consumeRate)\n cSt = self.cacheStrs[sRateID * NUMBER_CHANNELS + channel]\n return cSt.transmitRate\n\n def getParentCacheStreamBufferSize(self, stream, curTime):\n channel = stream.channel\n sRateID = STREAM_RATES.index(stream.consumeRate)\n cSt = self.cacheStrs[sRateID * NUMBER_CHANNELS + channel]\n cSt.updateCounters(curTime)\n inBuffer = float(cSt.downloadedBit - cSt.consumedBit)\n return inBuffer\n\n def updateDependentStreams(self, cacheStream, curTime):\n channel = cacheStream.channel\n sRateID = STREAM_RATES.index(cacheStream.consumeRate)\n for stream in self.lstStrs_Cnl_Rate[sRateID][channel]:\n if stream.transmitingLive:\n stream.tryUseMaxTRate(curTime)\n return\n\n def process(self, ev):\n if ev.type == EVENT_CACHE_READY:\n self.ready = True\n for s in self.waitingStreams:\n self.attachNetDataStream(s, ev.time)\n self.waitingStreams = []\n else:\n raise Exception(\"Unknown event type:\" + str(ev.type))\n return\n\n\nclass netDataStream:\n def __init__(self, sim, cr, sip, dip, s, cnl=None, strType=STREAM_NORMAL):\n self.downloadedBit = 0\n self.sizeBit = s\n self.transmitRate = 0\n self.transmitPoint = None\n self.consumeRate = float(cr)\n self.srcIP = sip\n self.dstIP = dip\n self.links = []\n self.bottleneckLink = None\n self.simRef = sim\n self.id = 0\n self.beingConsumed = False\n self.beingTransmitted = False\n self.consumePoint = 0\n self.consumedBit = 0\n self.bufferingBegin = 0.0\n self.eventRef_trComplete = None\n self.eventRef_consBegin = None\n self.eventRef_consComplete = None\n self.eventRef_bufferEmpty = None\n self.eventRef_expand = None\n self.eventRef_toLiveTRate = None\n self.stats_startTime = None\n self.stats_bufferingTime = 0.0\n self.stats_bufferingEvents = 0\n self.stats_bitRates = []\n self.collectBitrateStats = False\n self.stats_lastTransmitRate_time = 0\n self.stats_transmitRate_sumRates = 0\n self.stats_transmitRate_sumTime = 0\n self.interestingResult = False\n self.stats_events = []\n self.streamType = strType\n if strType == STREAM_NORMAL or strType == STREAM_NOISE:\n self.links.append(netLink(sim, LAN_LINK_RATE, None, None))\n self.channel = cnl\n self.connectedToCache = False # true when a stream is getting the data\n # from a cache node\n self.upCacheRef = None # link to the upped level cache, the one\n # from which the stream gets its data\n self.downCacheRef = None # link to the lower level cache, used to\n # enable cache hierarchy\n self.transmitingLive = False\n return\n\n def __del__(self):\n self.printStats()\n return\n\n def __str__(self):\n if self.streamType == STREAM_NORMAL:\n s = 'netDataStream-'\n elif self.streamType == STREAM_CACHE:\n s = 'netCacheStream-'\n elif self.streamType == STREAM_NOISE:\n s = 'netNoiseStream-'\n else:\n s = 'unknownStream-'\n s += str(self.id) + ' from: ' + self.srcIP +\\\n (\n '(c' + str(len(self.links)) + ')'\n if self.connectedToCache\n else '(d' + str(len(self.links)) + ')'\n ) +\\\n ', to: ' + self.dstIP + ', transmitRate: ' +\\\n str(self.transmitRate) + 'b/s'\n return s\n\n def printStats(self):\n if self.streamType == STREAM_NORMAL:\n self.simRef.simulationStatistics.append(\n (self.streamType,\n self.id,\n self.channel,\n self.stats_startTime,\n self.stats_bufferingTime,\n self.stats_bufferingEvents,\n self.sizeBit / self.consumeRate,\n self.getAvgTRate(),\n self.consumeRate,\n self.connectedToCache,\n self.srcIP,\n self.dstIP)\n )\n if self.streamType != STREAM_NORMAL:\n return\n s = 'stream-' + str(self.id) +\\\n ' from: ' + self.srcIP + ', to: ' + self.dstIP + '\\n' +\\\n 'start time: {:.2f}'.format(self.stats_startTime) +\\\n ', buffering time: {:.2f}'.format(self.stats_bufferingTime) +\\\n ', buffering events:' + str(self.stats_bufferingEvents) +\\\n ', playback time: {:.2f}'.format(self.sizeBit / self.consumeRate) +\\\n ', avg dwl-rate: {:.2f}'.format(self.getAvgTRate())\n # and draw a plot\n if (self.interestingResult and self.simRef.topArgs.figures)\\\n or self.simRef.topArgs.allfigures:\n self.drawStreamingPlot(s)\n return\n\n def getAvgTRate(self):\n r = float(self.stats_transmitRate_sumRates) / \\\n self.stats_transmitRate_sumTime\n return r\n\n def drawStreamingPlot(self, s):\n downStartX = downStopX = consStartX = consStopX = None\n buffStartX = buffStopX = None\n legendLines = set()\n for time, typ in self.stats_events:\n plt.plot(\n (time, time),\n (0, LAN_LINK_RATE),\n marker='.',\n mec='k',\n mew=0.25,\n ms=5,\n ls='-',\n lw=0.5,\n color=COLORS_EVENTS[typ],\n label=NAMES_EVENTS[typ] if typ not in legendLines else ''\n )\n if typ == EVENT_CONSUME_BEGIN and consStartX is None:\n consStartX = time\n elif typ == EVENT_CONSUME_BEGIN:\n buffStopX = time\n elif typ == EVENT_CONSUME_BUFFER_EMPTY:\n buffStartX = time\n elif typ == EVENT_CONSUME_COMPLETE:\n consStopX = time\n elif typ == EVENT_STREAM_START:\n downStartX = time\n elif typ == EVENT_STREAM_COMPLETED:\n downStopX = time\n if buffStartX is not None and buffStopX is not None:\n plt.plot(\n (buffStartX, buffStopX),\n (self.consumeRate, self.consumeRate),\n color='r',\n ls='-',\n lw=5,\n alpha=0.8,\n solid_capstyle='butt',\n label='Bufferring' if 'Bufferring' not in legendLines\n else ''\n )\n buffStartX = None\n buffStopX = None\n legendLines.add('Bufferring')\n legendLines.add(typ)\n avgTRate = self.getAvgTRate()\n plt.plot(\n (downStartX, downStopX),\n (avgTRate, avgTRate),\n color='c',\n ls=':',\n lw=2,\n alpha=0.7,\n solid_capstyle='butt',\n label='Avg. TRate'\n )\n plt.plot(\n (consStartX, consStopX),\n (self.consumeRate, self.consumeRate),\n color='c',\n ls='-',\n lw=2,\n alpha=0.7,\n solid_capstyle='butt',\n label='Cons. rate'\n )\n x, y = zip(*self.stats_bitRates)\n plt.plot(x, y, lw=1, color='b')\n plt.legend(\n fontsize=7,\n bbox_to_anchor=(1, 1),\n numpoints=1,\n framealpha=0.7\n )\n plt.suptitle(s, fontsize=7)\n plt.ylabel('Bandwidth (b/s)', fontsize=7)\n plt.xlabel('Time (s)', fontsize=7)\n plt.yticks(\n range(\n 0,\n int(LAN_LINK_RATE) + (int(LAN_LINK_RATE)/10),\n int(LAN_LINK_RATE) / 10)\n )\n plt.tick_params(axis='both', which='both', labelsize=5)\n plt.ticklabel_format(style='plain', useOffset=False)\n plt.minorticks_on()\n plt.grid(True)\n plt.savefig(self.simRef.simResDirName + '/fig_' + str(self.id) + '.pdf')\n plt.clf()\n return\n\n def updateCounters(self, curTime):\n if self.beingTransmitted:\n self.downloadedBit +=\\\n (curTime - self.transmitPoint) * self.transmitRate\n self.transmitPoint = curTime\n if self.beingConsumed:\n if self.streamType == STREAM_CACHE \\\n and self.transmitingLive \\\n and self.consumeRate > self.transmitRate:\n self.consumedBit +=\\\n (curTime - self.consumePoint) * self.transmitRate\n else:\n self.consumedBit +=\\\n (curTime - self.consumePoint) * self.consumeRate\n self.consumePoint = curTime\n return\n\n def updateEvent_trComplete(self, curTime):\n if self.beingTransmitted \\\n and self.streamType != STREAM_CACHE:\n expStreamingComplete = \\\n curTime +\\\n float(self.sizeBit - self.downloadedBit) / self.transmitRate\n if self.eventRef_trComplete is None:\n self.eventRef_trComplete = event(\n expStreamingComplete,\n self,\n EVENT_STREAM_COMPLETED\n )\n self.simRef.eventPush(self.eventRef_trComplete)\n else:\n self.simRef.eventUpdateTime(\n self.eventRef_trComplete,\n expStreamingComplete\n )\n else:\n if self.eventRef_trComplete is not None:\n self.simRef.deleteEvent(self.eventRef_trComplete)\n self.eventRef_trComplete = None\n return\n\n def updateEvent_bufferEmpty(self, curTime):\n inBuffer = float(self.downloadedBit - self.consumedBit)\n if -1 < inBuffer < 1:\n inBuffer = 0.0\n if self.transmitRate < self.consumeRate and self.beingConsumed:\n # buffer will become empty\n timeLeft = self.calcBefferEmptyTime(\n inBuffer,\n self.transmitRate,\n self.consumeRate\n )\n if self.eventRef_bufferEmpty is None:\n self.eventRef_bufferEmpty = event(\n curTime + timeLeft,\n self,\n EVENT_CONSUME_BUFFER_EMPTY\n )\n self.simRef.eventPush(self.eventRef_bufferEmpty)\n else:\n self.simRef.eventUpdateTime(\n self.eventRef_bufferEmpty,\n curTime +\n timeLeft\n )\n elif self.eventRef_bufferEmpty is not None:\n # buffer will not become empty\n self.simRef.deleteEvent(self.eventRef_bufferEmpty)\n self.eventRef_bufferEmpty = None\n return\n\n def updateEvent_toLiveTRate(self, curTime):\n if not self.transmitingLive and self.beingTransmitted:\n if self.connectedToCache and self.upCacheRef is not None:\n cacheStreamBufferSize = \\\n self.upCacheRef.getParentCacheStreamBufferSize(\n self, curTime\n )\n timeTillSwitch = \\\n cacheStreamBufferSize / self.transmitRate + curTime\n else:\n bufferSize = self.consumeRate * self.simRef.topArgs.cachesec\n inBuffer = float(self.downloadedBit - self.consumedBit)\n if -1 < inBuffer < 1:\n inBuffer = 0.0\n if self.streamType != STREAM_CACHE:\n if bufferSize > inBuffer + \\\n (self.sizeBit - self.downloadedBit):\n bufferSize = \\\n inBuffer + (self.sizeBit - self.downloadedBit)\n if bufferSize < inBuffer:\n bufferSize = inBuffer\n timeTillSwitch = \\\n (bufferSize - inBuffer) / self.transmitRate + curTime\n if self.eventRef_toLiveTRate is None:\n self.eventRef_toLiveTRate = event(\n timeTillSwitch,\n self,\n EVENT_SWITCH_TO_LIVERATE\n )\n self.simRef.eventPush(self.eventRef_toLiveTRate)\n else:\n self.simRef.eventUpdateTime(\n self.eventRef_toLiveTRate,\n timeTillSwitch\n )\n return\n\n def updateEvent_consumeBegin(self, curTime):\n # when data in buffer must be >= befferSize\n if self.beingConsumed:\n return\n bufferSize = self.consumeRate * self.simRef.topArgs.cachesec\n inBuffer = float(self.downloadedBit - self.consumedBit)\n if -1 < inBuffer < 1:\n inBuffer = 0.0\n if self.streamType != STREAM_CACHE:\n if bufferSize > inBuffer + (self.sizeBit - self.downloadedBit):\n bufferSize = inBuffer + (self.sizeBit - self.downloadedBit)\n if bufferSize < inBuffer:\n bufferSize = inBuffer\n if self.beingTransmitted:\n readyToPlayTime = \\\n (bufferSize - inBuffer) / self.transmitRate + curTime\n if self.eventRef_consBegin is None: # new event\n self.eventRef_consBegin = event(\n readyToPlayTime,\n self,\n EVENT_CONSUME_BEGIN\n )\n self.simRef.eventPush(self.eventRef_consBegin)\n else: # update old\n self.simRef.eventUpdateTime(\n self.eventRef_consBegin,\n readyToPlayTime\n )\n elif bufferSize == inBuffer and inBuffer > 0:\n if self.eventRef_consBegin is not None:\n self.simRef.eventUpdateTime(self.eventRef_consBegin, curTime)\n else:\n if self.eventRef_consBegin is not None:\n self.simRef.deleteEvent(self.eventRef_consBegin)\n self.eventRef_consBegin = None\n return\n\n def updateEvent_consumeComplete(self, curTime):\n # when we finish consuming the file (if no buff.empty occurs)\n if self.streamType == STREAM_CACHE:\n return\n if self.beingConsumed: # need to update event consume complete\n duration = float(self.sizeBit - self.consumedBit) / self.consumeRate\n if self.eventRef_consComplete is None:\n self.eventRef_consComplete = event(\n curTime + duration,\n self,\n EVENT_CONSUME_COMPLETE\n )\n self.simRef.eventPush(self.eventRef_consComplete)\n else:\n self.simRef.eventUpdateTime(\n self.eventRef_consComplete,\n curTime + duration\n )\n else:\n if self.eventRef_consComplete is not None:\n self.simRef.deleteEvent(self.eventRef_consComplete)\n self.eventRef_consComplete = None\n return\n\n def updateEvents(self, curTime):\n self.updateEvent_trComplete(curTime)\n if self.simRef.topArgs.streaming == 'live':\n self.updateEvent_toLiveTRate(curTime)\n if self.streamType != STREAM_NOISE:\n self.updateEvent_bufferEmpty(curTime)\n self.updateEvent_consumeBegin(curTime)\n if not self.beingTransmitted:\n if self.eventRef_expand is not None:\n self.simRef.deleteEvent(self.eventRef_expand)\n self.eventRef_expand = None\n return\n\n def calcBefferEmptyTime(self, buffSize, Vi, Vo):\n # Vi -- download speed\n # Vo -- playback speed\n # Calculate the sum of the first N terms of a geometric series\n if Vi >= Vo:\n raise Exception(\"Series has no sum (diverges) -> \"\n \"Buffer will not become empty\")\n Vi = float(Vi)\n t0 = float(buffSize) / Vo\n if Vi > 0:\n accuracy = 0.001 # seconds\n b = Vi/Vo\n n = math.ceil(math.log(accuracy, b))\n sumN = t0 * (1.0 - math.pow((Vi/Vo), n)) / (1.0 - Vi/Vo)\n else:\n sumN = t0\n return sumN\n\n def startStreaming(self, curTime):\n if self.streamType == STREAM_NOISE:\n global globalNoiseStreamID\n self.id = globalNoiseStreamID\n globalNoiseStreamID += 1\n elif self.streamType == STREAM_CACHE:\n global globalCacheStreamID\n self.id = globalCacheStreamID\n globalCacheStreamID += 1\n elif self.streamType == STREAM_NORMAL:\n global globalStreamID\n self.id = globalStreamID\n globalStreamID += 1\n self.updateBottleneckLink(newStream=1)\n if self.simRef.simulatorReady:\n newTR = self.bottleneckLink.getFairThroughput(1)\n self.stats_lastTransmitRate_time = curTime\n self.setTransmitRate(newTR, curTime)\n for link in self.links:\n link.allocateBandwidthForNewStream(curTime, newTR)\n link.netDataStreams.append(self)\n else:\n # implementing simultaneous start of background noise streams\n # they are all placed onto the links, but have tRate = 0\n newTR = self.bottleneckLink.getFairThroughput(0)\n self.stats_lastTransmitRate_time = curTime\n self.setTransmitRate(newTR, curTime)\n self.eventRef_expand = event(\n curTime + EXPAND_INTERVAL,\n self,\n EVENT_STREAM_EXPAND\n )\n self.simRef.eventPush(self.eventRef_expand)\n return\n\n def setTransmitRate(self, newRate, curTime):\n if newRate != self.transmitRate:\n self.updateCounters(curTime)\n if self.collectBitrateStats:\n self.stats_bitRates.append((curTime, self.transmitRate))\n self.stats_bitRates.append((curTime, newRate))\n self.stats_transmitRate_sumRates += \\\n (curTime - self.stats_lastTransmitRate_time) * self.transmitRate\n self.stats_transmitRate_sumTime += \\\n (curTime - self.stats_lastTransmitRate_time)\n self.stats_lastTransmitRate_time = curTime\n self.transmitRate = newRate\n self.updateEvents(curTime)\n if self.streamType == STREAM_CACHE:\n self.downCacheRef.updateDependentStreams(self, curTime)\n return\n\n def tryUseMaxTRate(self, curTime):\n tr = self.updateBottleneckLink()\n if self.transmitingLive:\n if self.connectedToCache and self.upCacheRef is not None:\n cacheStreamTRate = \\\n self.upCacheRef.getParentCacheStreamTransmitRate(self)\n else:\n cacheStreamTRate = self.consumeRate\n if cacheStreamTRate < tr:\n tr = cacheStreamTRate\n if self.transmitRate != tr:\n self.setTransmitRate(tr, curTime)\n return\n\n def updateBottleneckLink(self, newStream=0):\n self.bottleneckLink = self.links[0]\n minThroughput = self.bottleneckLink.getFairThroughput(newStream)\n for l in self.links:\n tempRateVal = l.getFairThroughput(newStream)\n if tempRateVal < minThroughput:\n minThroughput = tempRateVal\n self.bottleneckLink = l\n return minThroughput\n\n def process(self, ev):\n if ev.type == EVENT_STREAM_START:\n self.beingTransmitted = True\n self.transmitPoint = ev.time\n self.startStreaming(ev.time)\n\n elif ev.type == EVENT_STREAM_COMPLETED:\n self.updateCounters(ev.time)\n self.beingTransmitted = False\n self.eventRef_trComplete = None\n self.setTransmitRate(0, ev.time)\n for link in self.links:\n link.netDataStreams.remove(self)\n if self.connectedToCache:\n self.upCacheRef.detachNetDataStream(self, ev.time)\n if self.streamType == STREAM_NOISE:\n self.simRef.urRef.activeNoiseStreams -= 1\n if self.simRef.simulatorReady \\\n and not self.simRef.simulationDone:\n newEv = self.simRef.urRef.getNoiseEvent(ev.time)\n self.simRef.eventPush(newEv)\n elif self.streamType == STREAM_NORMAL:\n self.simRef.urRef.activeStreams -= 1\n if not self.simRef.urRef.streamGenActive \\\n and (self.simRef.urRef.activeStreams == 0\n and self.simRef.simulatorReady):\n self.simRef.simulationDone = True\n\n elif ev.type == EVENT_STREAM_EXPAND:\n if self.beingTransmitted:\n self.tryUseMaxTRate(ev.time)\n # try to expand every second\n self.eventRef_expand = event(\n ev.time + EXPAND_INTERVAL,\n self,\n EVENT_STREAM_EXPAND\n )\n self.simRef.eventPush(self.eventRef_expand)\n else:\n self.eventRef_expand = None\n return\n # don't let Expand event register in the stream stats\n\n elif ev.type == EVENT_CONSUME_BEGIN:\n self.eventRef_consBegin = None\n self.updateCounters(ev.time)\n self.beingConsumed = True\n self.consumePoint = ev.time\n self.updateEvent_consumeComplete(ev.time)\n self.updateEvent_bufferEmpty(ev.time)\n if self.streamType == STREAM_CACHE:\n self.downCacheRef.startDependentStraems(self, ev.time)\n # statistics\n if self.stats_startTime is None:\n self.stats_startTime = ev.time - self.bufferingBegin\n if self.bufferingBegin != 0:\n self.stats_bufferingTime += ev.time - self.bufferingBegin\n self.bufferingBegin = 0\n\n elif ev.type == EVENT_SWITCH_TO_LIVERATE:\n self.transmitingLive = True\n self.eventRef_toLiveTRate = None\n self.tryUseMaxTRate(ev.time)\n return\n # don't let 'Switch to liveRate' event register in the stream stats\n\n elif ev.type == EVENT_CONSUME_COMPLETE:\n self.updateCounters(ev.time)\n self.beingConsumed = False\n self.eventRef_consComplete = None\n self.updateEvents(ev.time)\n\n elif ev.type == EVENT_CONSUME_BUFFER_EMPTY:\n self.eventRef_bufferEmpty = None\n self.updateCounters(ev.time)\n if self.beingConsumed:\n if self.streamType != STREAM_CACHE:\n # the cache stream continues sending\n self.beingConsumed = False\n self.bufferingBegin = ev.time\n self.updateEvent_consumeBegin(ev.time)\n if self.beingTransmitted:\n self.updateEvent_consumeComplete(ev.time)\n # statistics\n self.stats_bufferingEvents += 1\n if self.collectBitrateStats:\n self.interestingResult = True\n else:\n raise Exception(\"Unknown event type: \" + str(ev.type))\n if self.streamType != STREAM_NOISE:\n self.stats_events.append((ev.time, ev.type))\n return\n\n\nclass userRequests:\n def __init__(self, sim, fName, gnGraph, listHosts, maxHosts,\n maxActiveStreams):\n self.re = re.compile(\n '(\\d+\\.\\d+\\.\\d+\\.\\d+)\\s(\\S+)\\s(\\d+)'\n '\\s(\\d+\\.\\d+)\\s(\\d+\\.\\d+)\\s(\\d+\\.\\d+)\\s(\\d+)',\n re.UNICODE\n )\n self.requestQueue = Queue.Queue()\n self.noiseRequestQueue = Queue.Queue()\n self.gnGraph = gnGraph\n self.listOfHosts = listHosts\n self.traceHostMap = dict()\n self.maxHosts = maxHosts # total number of hosts\n self.simRef = sim\n self.activeStreams = 0\n self.totalStreams = 0\n self.activeStreamsMax = maxActiveStreams\n self.streamGenerationRate = self.calcStreamGenRate(sim.topArgs.reqRate)\n self.streamGenRate_next = 0\n self.streamGenActive = True\n self.activeNoiseStreams = 0\n self.totalNoiseStreams = 0\n self.activeNoiseStreamsMax = int(sim.topArgs.backnoise)\n self.startTime = None\n self.initStreamsList = []\n self.listOfChannels = None\n self.numRequestsPerTimePeriod = 0\n self.streamGenRateScenario = [] # (time, requests per min)\n if sim.topArgs.scenario != '':\n if os.path.isfile(sim.topArgs.scenario):\n print(\"\\tUsing a scenaio file: \" + sim.topArgs.scenario)\n with open(sim.topArgs.scenario, 'rb') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n time, rate = row\n self.streamGenRateScenario.append(\n (float(time), float(rate))\n )\n else:\n print(\"\\tspecified scenaio file not found: \" +\n sim.topArgs.scenario)\n exit(-3)\n if MODEL_USER_BEHAVIOR is True:\n self.startTime = 0.0\n self.traceFile = None\n for t, r in self.streamGenRateScenario:\n self.simRef.eventPush(\n event(t, self, EVENT_CHANGE_REQUEST_RATE)\n )\n self.simRef.eventPush(\n event(sim.topArgs.endtime, self, EVENT_SIM_FINALIZE)\n )\n else:\n self.traceFile = open(fName, 'r')\n self.simRef.eventPush(event(1, self, EVENT_PERIODIC_STATS))\n return\n\n def __del__(self):\n self.traceFile.close()\n\n def calcStreamGenRate(self, userRequest=0.0):\n autoCalcRate = float(self.activeStreamsMax) / MEAN_PBK_TIME\n if userRequest == 0.0:\n result = autoCalcRate\n else:\n result = float(userRequest) / 60\n if result < autoCalcRate:\n print(\n \"\\n\\tinfo: given reqRate (\" + str(60 * result) +\n \") is too small to guarantee \" +\n str(self.simRef.topArgs.active) +\n \" active connections. Try reqRate = \" +\n str(60 * autoCalcRate)\n )\n elif result > autoCalcRate:\n print(\n \"\\n\\tinfo: given reqRate (\" + str(60 * result) +\n \") is too high. Number active connections (\" +\n str(self.simRef.topArgs.active) +\n \") will be exceeded. Try reqRate = \" +\n str(60 * autoCalcRate)\n )\n return result\n\n def genChannelNumber(self):\n channel = numpy.random.zipf(1.2) - 1\n while channel >= NUMBER_CHANNELS:\n channel = numpy.random.zipf(1.2) - 1\n return channel\n\n def getNextEvent(self, curTime):\n if MODEL_USER_BEHAVIOR:\n self.totalStreams += 1\n randHost = random.choice(self.listOfHosts).exploded\n randStartTime = curTime + numpy.random.\\\n standard_gamma(1.0/self.streamGenerationRate)\n randPlayTime = numpy.random.\\\n triangular(MIN_PBK_TIME, MOD_PBK_TIME, MAX_PBK_TIME)\n rateN = numpy.random.poisson(2)\n while rateN > len(STREAM_RATES) - 1:\n rateN = numpy.random.poisson(2)\n randStreamRate = STREAM_RATES[rateN]\n futureRequest = (\n randHost,\n randStreamRate,\n randStreamRate * randPlayTime\n )\n ev = event(randStartTime, self, EVENT_USER_REQUEST)\n else:\n # If we have a trace file with realistic user events...\n futureRequestLine = self.traceFile.readline()\n if futureRequestLine == '':\n return None\n match = self.re.match(futureRequestLine)\n if match is not None:\n if self.startTime is None:\n self.startTime = float(match.group(4))\n # if the trace file is using masked\n # ip-addresses, we have to re-map them\n if match.group(1) not in self.traceHostMap:\n randHost = random.choice(self.listOfHosts).exploded\n self.traceHostMap[match.group(1)] = randHost\n else:\n randHost = self.traceHostMap[match.group(1)]\n futureRequest = (\n randHost,\n STREAM_RATES[2],\n float(match.group(7))\n )\n ev = event(\n float(match.group(4)) - self.startTime,\n self,\n EVENT_USER_REQUEST\n )\n else:\n raise Exception(\n \"Unrecognized format of user behavior trace file,\"\n \" line:\\n\\t>> \" + futureRequestLine\n )\n self.requestQueue.put(futureRequest)\n return ev\n\n def getNoiseEvent(self, curTime):\n self.totalNoiseStreams += 1\n randHost = random.choice(self.listOfHosts).exploded\n randStartTime = curTime + numpy.random.\\\n standard_gamma(MEAN_PBK_TIME/self.activeNoiseStreamsMax)\n randPlayTime = numpy.random.triangular(600, 1800, 3600)\n randStreamRate = STREAM_RATES[int(\n numpy.random.triangular(\n -1, len(STREAM_RATES) / 2, len(STREAM_RATES)\n ))]\n futureNoiseRequest = \\\n (randHost, randStreamRate, randPlayTime * randStreamRate)\n self.noiseRequestQueue.put(futureNoiseRequest)\n ev = event(randStartTime, self, EVENT_NOISE_USER_REQUEST)\n return ev\n\n def routeStreamPath(self, path, s, curTime):\n nodeA = path[0]\n for nodeB in path[1:]:\n if 'p2p_link' not in self.gnGraph.netGraph[nodeA][nodeB]:\n if self.gnGraph.isAccessNode(\n self.gnGraph.netGraph.node[nodeA]['type']\n ) or self.gnGraph.isAccessNode(\n self.gnGraph.netGraph.node[nodeB]['type']\n ):\n self.gnGraph.netGraph[nodeA][nodeB]['p2p_link'] =\\\n netLink(\n self.simRef,\n BACKBONE_LINK_BANDWIDTH,\n nodeA,\n nodeB\n )\n else:\n self.gnGraph.netGraph[nodeA][nodeB]['p2p_link'] =\\\n netLink(\n self.simRef,\n FAST_BACKBONE_LINK_BANDWIDTH,\n nodeA,\n nodeB\n )\n s.links.append(self.gnGraph.netGraph[nodeA][nodeB]['p2p_link'])\n nodeA = nodeB\n if s.streamType == STREAM_NOISE and not self.simRef.simulatorReady:\n for l in s.links:\n l.netDataStreams.append(s)\n self.initStreamsList.append(s)\n else:\n self.simRef.eventPush(\n event(\n curTime + PROPAGATION_DELAY*len(path),\n s,\n EVENT_STREAM_START\n )\n )\n return\n\n def addCacheToAS(self, ASn, curTime, channelNum, static=False):\n if 'caches' not in self.gnGraph.netGraph.node[ASn]:\n self.gnGraph.netGraph.\\\n node[ASn]['caches'] = [None] * NUMBER_CHANNELS\n # 1 vm per channel (all str.Rates)\n if self.gnGraph.netGraph.node[ASn]['caches'][channelNum] is None:\n cache = cacheNode(self.simRef, self.gnGraph, ASn)\n assert cache.id not in self.gnGraph.netGraph\n self.gnGraph.netGraph.add_edge(ASn, cache.id)\n self.gnGraph.netGraph.node[ASn]['caches'][channelNum] = cache\n if static:\n cache.process(\n event(\n curTime,\n cache,\n EVENT_CACHE_READY\n )\n )\n else:\n self.simRef.eventPush(\n event(\n curTime + self.simRef.topArgs.cacheinit,\n cache,\n EVENT_CACHE_READY\n )\n )\n else:\n cache = self.gnGraph.netGraph.node[ASn]['caches'][channelNum]\n return cache\n\n def routeStreamPath_inclCache(self, path, s, curTime, first=True):\n cacheOnDemand = self.simRef.topArgs.ondemandCache\n nodeA = path[0]\n for nodeB in path[1:]:\n # Creating a link between node A and B, if it does not exist yet\n if 'p2p_link' not in self.gnGraph.netGraph[nodeA][nodeB]:\n # if one of the nodes is an 'access' AS node then the link\n # speed is set to BACKBONE_LINK_BANDWIDTH\n if self.gnGraph.isAccessNode(\n self.gnGraph.netGraph.node[nodeA]['type']\n ) or self.gnGraph.isAccessNode(\n self.gnGraph.netGraph.node[nodeB]['type']\n ):\n self.gnGraph.netGraph[nodeA][nodeB]['p2p_link'] = \\\n netLink(\n self.simRef,\n BACKBONE_LINK_BANDWIDTH,\n nodeA,\n nodeB\n )\n else:\n self.gnGraph.netGraph[nodeA][nodeB]['p2p_link'] =\\\n netLink(\n self.simRef,\n FAST_BACKBONE_LINK_BANDWIDTH,\n nodeA,\n nodeB\n )\n if nodeA == path[0] or not LOCAL_CACHE_ONLY:\n # increase the cache-init counter and check the threshold\n if 'nCacheRequests' not in self.gnGraph.netGraph.node[nodeA]:\n self.gnGraph.netGraph.\\\n node[nodeA]['nCacheRequests'] = [0] * NUMBER_CHANNELS\n self.gnGraph.netGraph.\\\n node[nodeA]['nCacheRequests'][s.channel] += 1\n if self.gnGraph.netGraph.\\\n node[nodeA]['nCacheRequests'][s.channel] >= \\\n self.simRef.topArgs.cachethreshold:\n # threshold passed, add a cache\n # (all checks are inside the 'addCacheToAS')\n cache = None\n if 'static_cache' in self.gnGraph.netGraph.node[nodeA]:\n cache = self.addCacheToAS(\n nodeA,\n curTime,\n s.channel,\n static=True\n )\n elif cacheOnDemand and first:\n cache = self.addCacheToAS(nodeA, curTime, s.channel)\n if cache is not None\\\n and cache != s.downCacheRef \\\n and cache.attachNetDataStream(s, curTime):\n # 'attachNetDataStream' returns False if cache is not\n # ready yet, if connected -> stop routing\n break\n # if the stream is not connected to a\n # cache @ node A (or there is no cache @ node A)\n if not s.connectedToCache:\n # add the link from node A to node B to the stream path\n # (! this does not mean adding stream to all links along\n # the path, this is done later)\n s.links.append(self.gnGraph.netGraph[nodeA][nodeB]['p2p_link'])\n nodeA = nodeB\n # background noise streams: adding stream to all links along\n # the path at init time\n if not self.simRef.simulatorReady and s.streamType == STREAM_NOISE:\n for l in s.links:\n l.netDataStreams.append(s)\n self.initStreamsList.append(s)\n else:\n # schedule 'start streaming' events\n if not s.connectedToCache:\n self.simRef.eventPush(\n event(\n curTime + PROPAGATION_DELAY*len(path),\n s,\n EVENT_STREAM_START\n )\n )\n return\n\n def process(self, ev):\n if ev.type == EVENT_USER_REQUEST:\n dest_ip, stream_rate, data_size = self.requestQueue.get()\n hostAs = self.gnGraph.ip2as[dest_ip]\n path = nx.shortest_path(\n self.gnGraph.netGraph,\n hostAs,\n self.gnGraph.contentProvider\n )\n serv_ip = self.gnGraph.netGraph.\\\n node[self.gnGraph.contentProvider]['ip'].exploded\n ds = netDataStream(\n self.simRef,\n stream_rate,\n serv_ip,\n dest_ip,\n data_size,\n self.genChannelNumber()\n )\n ds.bufferingBegin = ev.time\n if self.simRef.topArgs.streaming == 'live':\n self.routeStreamPath_inclCache(path, ds, ev.time)\n else:\n self.routeStreamPath(path, ds, ev.time)\n # statistics for user request\n ds.stats_events.append((ev.time, ev.type))\n self.activeStreams += 1\n self.numRequestsPerTimePeriod += 1\n if self.streamGenActive:\n self.simRef.eventPush(self.getNextEvent(ev.time))\n elif ev.type == EVENT_NOISE_USER_REQUEST:\n dest_ip, stream_rate, data_size = self.noiseRequestQueue.get()\n hostAs = self.gnGraph.ip2as[dest_ip]\n servAs = random.choice(self.gnGraph.contentNodes)\n serv_ip = self.gnGraph.as2ip[servAs][0][1].exploded\n path = nx.shortest_path(self.gnGraph.netGraph, hostAs, servAs)\n ds = netDataStream(\n self.simRef,\n stream_rate,\n serv_ip,\n dest_ip,\n data_size,\n strType=STREAM_NOISE\n )\n self.routeStreamPath(path, ds, ev.time)\n if self.simRef.simulatorReady:\n self.simRef.eventPush(\n event(\n ev.time + PROPAGATION_DELAY*len(path),\n ds,\n EVENT_STREAM_START\n )\n )\n else:\n self.initStreamsList.append(ds)\n self.activeNoiseStreams += 1\n if not self.simRef.simulationDone:\n if not self.simRef.simulatorReady:\n self.simRef.eventPush(self.getNoiseEvent(ev.time))\n if self.activeNoiseStreams >= self.activeNoiseStreamsMax:\n for tmpStream in self.initStreamsList:\n tmpStream.startStreaming(ev.time)\n tmpStream.bufferingBegin = ev.time\n self.initStreamsList = []\n self.simRef.simulatorReady = True\n self.streamGenActive = True\n # start normal stream\n self.simRef.eventPush(self.getNextEvent(ev.time))\n elif ev.type == EVENT_CHANGE_REQUEST_RATE:\n self.streamGenerationRate = self.calcStreamGenRate(\n self.streamGenRateScenario[self.streamGenRate_next][1]\n )\n self.streamGenRate_next += 1\n elif ev.type == EVENT_SIM_FINALIZE:\n print(\"\\n{:.2f}\".format(float(ev.time)) +\n \" sec. -- SIM_FINALIZE: no new streams\")\n self.streamGenActive = False\n elif ev.type == EVENT_PERIODIC_STATS:\n self.simRef.urStatistics_nActCons.append(\n (ev.time, self.activeStreams)\n )\n reqPerSec = float(self.numRequestsPerTimePeriod) / 10 * 60\n self.simRef.urStatistics_nReqPSec.append((ev.time, reqPerSec))\n self.numRequestsPerTimePeriod = 0\n if not self.simRef.simulationDone:\n self.simRef.eventPush(\n event(\n ev.time + 10,\n self,\n EVENT_PERIODIC_STATS\n )\n )\n print(\n '\\r{:.2f}'.format(float(ev.time)) +\n \" sec. simulated. Active Streams = \" +\n str(self.activeStreams), end=\"\"\n )\n sys.stdout.flush()\n else:\n raise Exception(\"Unknown event type:\" + str(ev.type))\n return\n","sub_path":"netStreamingPrimitives.py","file_name":"netStreamingPrimitives.py","file_ext":"py","file_size_in_byte":52354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"426274575","text":"from os.path import isfile\nfrom pagegen.utility import appropriate_markup, DIRDEFAULTFILE\n\n\ndef source_link(site, page):\n\t''' Return link to source file, if it exists '''\n\n\tif isfile(page.target_path + '.txt'):\n\n\t\turl = page.url_path\n\n\t\tif url.endswith('/'):\n\t\t\turl += DIRDEFAULTFILE\n\n\t\thtml = ' '\n\telse:\n\t\thtml = ''\n\n\treturn html\n\n\ndef list_shortcodes(site, page):\n\t''' List built-in shortcodes '''\n\n\tsc_built_in_whitelist = [\n\t\t'figure',\n\t\t'image',\n\t\t'integrity_hash',\n\t\t'menu',\n\t\t'page_url',\n\t\t'youtube',\n\t]\n\n\tscs = site.shortcodes.__repr__()\n\n\thtml = ''\n\n\tfor sc in scs.splitlines():\n\t\tfor bsc in sc_built_in_whitelist:\n\t\t\tif sc.startswith(bsc + '('):\n\t\t\t\thtml += '' + sc + ' '\n\t\t\t\tbreak\n\n\thtml += ' '\n\n\treturn appropriate_markup(page, html)\n","sub_path":"shortcodes.py","file_name":"shortcodes.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"316339003","text":"import json\nimport os\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS, cross_origin\n\napp = Flask(__name__)\napp.config['CORS_HEADERS'] = 'Content-Type'\n\n\ndef openfile(arq):\n json_file = open(file=f'{arq}')\n arquivoo = json.load(json_file)\n json_file.close()\n return arquivoo\n\n\ncors = CORS(app, resources={r\"/data/*\": {\"origins\": \"*\"}})\n\nstatus_all = openfile('status_count.json')\nAlbuquerque = openfile(\n './projetosStatus/status_count_[Albuquerque, Albuquerque and Carvalho Comércio] - Mandatory human-resource open architecture.json')\nBatista = openfile(\n './projetosStatus/status_count_[Batista, Moreira and Pereira LTDA] - Monitored multi-state installation.json')\nCarvalho = openfile(\n './projetosStatus/status_count_[Carvalho, Costa and Costa e Associados] - Ergonomic methodical methodology.json')\nCosta_Comércio = openfile(\n './projetosStatus/status_count_[Costa Comércio Comércio] - Sharable non-volatile internet solution.json')\nCosta_LTDA = openfile(\n './projetosStatus/status_count_[Costa LTDA S.A.] - Total asynchronous secured line.json')\nMelo = openfile(\n './projetosStatus/status_count_[Melo, Melo and Santos e Associados] - Organized impactful instruction set.json')\nPereira = openfile(\n './projetosStatus/status_count_[Pereira - Barros Comércio] - Mandatory fault-tolerant Graphical User Interface.json')\nSantos = openfile(\n './projetosStatus/status_count_[Santos - Batista Comércio] - Stand-alone well-modulated policy.json')\nSouza = openfile(\n './projetosStatus/status_count_[Souza Comércio e Associados] - Innovative background implementation.json')\nXavier = openfile(\n './projetosStatus/status_count_[Xavier EIRELI S.A.] - Vision-oriented holistic architecture.json')\n\n\n@app.route(\"/data/status/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef trello():\n if request.method == \"GET\":\n return jsonify(status_all)\n\n\n@app.route(\"/data/albuquerque/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef albuquerque():\n if request.method == \"GET\":\n return jsonify(Albuquerque)\n\n\n@app.route(\"/data/batista/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef batista():\n if request.method == \"GET\":\n return jsonify(Batista)\n\n\n@app.route(\"/data/carvalho/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef carvalho():\n if request.method == \"GET\":\n return jsonify(Carvalho)\n\n\n@app.route(\"/data/costacomercio/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef costacomercio():\n if request.method == \"GET\":\n return jsonify(Costa_Comércio)\n\n\n@app.route(\"/data/costaltda/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef costaltda():\n if request.method == \"GET\":\n return jsonify(Costa_LTDA)\n\n\n@app.route(\"/data/melo/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef melo():\n if request.method == \"GET\":\n return jsonify(Melo)\n\n\n@app.route(\"/data/pereira/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef pereira():\n if request.method == \"GET\":\n return jsonify(Pereira)\n\n\n@app.route(\"/data/santos/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef santos():\n if request.method == \"GET\":\n return jsonify(Santos)\n\n\n@app.route(\"/data/souza/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef souza():\n if request.method == \"GET\":\n return jsonify(Souza)\n\n\n@app.route(\"/data/xavier/\", methods=[\"GET\"])\n@cross_origin(origin='*', headers=['Content- Type', 'Authorization'])\ndef xavier():\n if request.method == \"GET\":\n return jsonify(Xavier)\n\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"183915548","text":"num1=int(input('Digite o primeiro numero:'))\nnum2=int(input('Digite o segundo numero:'))\nnum3=int(input('Digite o terceiro numero:'))\nif num1>num2 and num1>num3:\n maior=num1\nif num2>num1 and num2>num3:\n maior=num2\nif num3>num1 and num3>num2:\n maior=num3\nif num1\nDate: \nDescription:\n\"\"\"\nimport os\nimport sys\nimport comtypes.client\n\nrutaEspecifica = False\nProgramPath = \"C:\\\\Program Files\\\\Computers and Structures\\\\ETABS 18\\\\ETABS.exe\"\ntry:\n ETABSObject = comtypes.client.GetActiveObject(\"CSI.ETABS.API.ETABSObject\")\n print(\"Coneccion exitosa!.\\nadjuntando a una instancia existente.\")\nexcept (OSError, comtypes.COMError):\n print(\"No se encontró ninguna instancia en ejecución del programa(Etabs).\")\n print(\"Tratando de Ejecutar etabs!.\")\n helper = comtypes.client.CreateObject('ETABSv1.Helper')\n helper = helper.QueryInterface(comtypes.gen.ETABSv1.cHelper)\n if rutaEspecifica:\n try:\n ETABSObject = helper.CreateObject(ProgramPath)\n print(\"Coneccion esitosa!.\\nConexion Manual\")\n except (OSError, comtypes.COMError):\n print(\"Cannot start a new instance of the program from \" + ProgramPath)\n sys.exit(-1)\n else:\n try: \n ETABSObject = helper.CreateObjectProgID(\"CSI.ETABS.API.ETABSObject\") \n print(\"Coneccion esitosa!.\")\n except (OSError, comtypes.COMError):\n print(\"Cannot start a new instance of the program.\")\n sys.exit(-1)\n print(\"Ejecutando etabs!.\")\n ETABSObject.ApplicationStart()\nSapModel = ETABSObject.SapModel\nSapModel.SetModelIsLocked(False)\nres = SapModel.InitializeNewModel()\n\n# === FORMAS DE INICIALIZAR UN MODELO ===\n# res = SapModel.File.NewBlank()\n# res = SapModel.File.NewGridOnly(4,12,12,4,4,24,24)\nres = SapModel.File.NewSteelDeck(4,12.0,12.0,4,4,24.0,24.0)\n\n# Unit Preferences | Preferencias de Unidad\nN_mm_C = 6 #kN_m_c\nSapModel.SetPresentUnits(N_mm_C)\n\n\n# recurso para optener las funciones que se tiene\n# for nombre in dir(SapModel.PropMaterial):\n# if nombre.startswith('__') or nombre.startswith('_'):\n# continue\n# print(f\"{nombre}\")\n\n# 'add ASTM A706 rebar material property in United states Region\n# ret = SapModel.PropMaterial.AddMaterial(\"CONC34\", 2, \"Spain\", \"HA-20\", \"Grade 60\")\n# print(ret)\n\n# Materials | materiales\nSapModel.PropMaterial.SetMaterial(\"CONC35\", 2, -1, \"Comentario...\")\nprint(SapModel.PropMaterial.GetMaterial(\"CONC35\", 2, -1, \"Comentario...\"))\n\n# 'change name of material property\nret = SapModel.PropMaterial.ChangeName(\"CONC35\", \"CONC36\")\n\nret = SapModel.PropMaterial.SetOConcrete_1(\"CONC35\", 35, False, 0, 1, 2, 0.0022, 0.0052, -0.1, 0, 0)\n\n# 'assign other properties\nret = SapModel.PropMaterial.SetOConcrete(\"CONC37\", 5, False, 0, 1, 2, 0.0022, 0.0052)\n\n\n# 'specify temps at which properties will be provided\nMyTemp = [0,50,100]\nret = SapModel.PropMaterial.SetTemp(\"Steel\", 3, MyTemp)\n\n\n\n\n\n# ETABSObject.ApplicationExit(True)\n# clean up variables | limpiamos las variables y eliminamos\nETABSObject, SapModel, res = None, None, None\ndel ETABSObject, SapModel, res","sub_path":"src/EtabsAPI/EtabsAPI09i_NewGridOnly_material.py","file_name":"EtabsAPI09i_NewGridOnly_material.py","file_ext":"py","file_size_in_byte":2902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"163649732","text":"# https://www.kaggle.com/pmarcelino/comprehensive-data-exploration-with-python\n# %% 引入模块\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom scipy import stats\nfrom scipy.stats import norm, skew\nfrom sklearn.base import BaseEstimator, RegressorMixin, TransformerMixin, clone\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.kernel_ridge import KernelRidge\nfrom sklearn.linear_model import Lasso, LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import RandomizedSearchCV, train_test_split\nfrom sklearn.pipeline import Pipeline, make_pipeline\nfrom sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler\nfrom sklearn.tree import DecisionTreeRegressor\n\nplt.style.use(style=\"ggplot\")\nsns.set(color_codes=True)\nprint(\"引入必要模块,完成!\")\n\n# %% 直观观察\n# 发现四个变量与目标值关系密切\n# OverallQual\n# YearBuilt\n# TotalBsmtSF\n# GrLivArea\n\ntrain_data = pd.read_csv('train.csv')\nfigure = plt.figure()\nsns.pairplot(x_vars=['OverallQual', 'GrLivArea', 'YearBuilt', 'TotalBsmtSF'], y_vars=[\n 'SalePrice'], data=train_data, dropna=True)\nplt.show()\n\n\n# %% 观察变量相关性\n\ncorrmat = train_data.corr()\n# plt.subplots(figsize=(12, 9))\n# sns.heatmap(corrmat, vmax=0.9, square=True)\n# plt.show()\n\n# saleprice correlation matrix\nk = 10 # number of variables for heatmap\ncols = corrmat.nlargest(k, 'SalePrice')['SalePrice'].index\n\ncm = np.corrcoef(train_data[cols].values.T)\nsns.set(font_scale=1.25)\nhm = sns.heatmap(cm, cbar=True, annot=True, square=True, fmt='.2f', annot_kws={\n 'size': 10}, yticklabels=cols.values, xticklabels=cols.values)\nplt.show()\n\n# 分析这10个变量\n# GarageCars 和 GarageArea 相似,取 GarageCars\n# TotalBsmtSF 和 1stFloor 相关,取 TotalBsmtSF\n# ToRmsAbvGrd 和 GrLivArea 相关,取 GrLivArea\n\n# scatterplot,两两相关性分析,慎重执行,费CPU,结果见'7-features-scatter.pdf'\n# sns.set()\n# cols = ['SalePrice', 'OverallQual', 'GrLivArea',\n# 'GarageCars', 'TotalBsmtSF', 'FullBath', 'YearBuilt']\n# sns.pairplot(train_data[cols], size=2.5)\n# plt.show()\n\n# %% 处理缺失值\n# missing data\ntotal = train_data.isnull().sum().sort_values(ascending=False)\npercent = (train_data.isnull().sum()/train_data.isnull().count()\n ).sort_values(ascending=False)\nmissing_data = pd.concat([total, percent], axis=1, keys=['Total', 'Percent'])\nmissing_data.head(20)\n\n# 缺失值超过15%的应该删掉该变量,所以'PoolQC', 'MiscFeature' and 'FireplaceQu' 应该可以被删掉。\n# GarageX 系列变量丢失相同的数据,并且 GarageCars 已经表示了这一套变量的含义,所以,其他的这些GarageX变量可以删除。\n# BsmtX同理\n# MasVnrArea 和 MasVnrType 并不是必须的,相关含义已经可以通过YearBuilt和OverallQual所代表。因此这两个变量也可以删除。\n# Electrical 变量只有一个NA值,这条记录删除即可。\n# In summary, to handle missing data, we'll delete all the variables with missing data, except the variable 'Electrical'. In 'Electrical' we'll just delete the observation with missing data.\n# dealing with missing data\ntrain_data = train_data.drop(\n (missing_data[missing_data['Total'] > 1]).index, 1)\ntrain_data = train_data.drop(\n train_data.loc[train_data['Electrical'].isnull()].index)\n# just checking that there's no missing data missing...\ntrain_data.isnull().sum().max()\n\n# %% 处理 OutLiars 异常值\n# 单变量分析 Univariate analysis\n# The primary concern here is to establish a threshold that defines an observation as an outlier. To do so, we'll standardize the data. In this context, data standardization means converting data values to have mean of 0 and a standard deviation of 1.\n# standardizing data\nsaleprice_scaled = StandardScaler().fit_transform(\n train_data['SalePrice'][:, np.newaxis])\nlow_range = saleprice_scaled[saleprice_scaled[:, 0].argsort()][:10]\nhigh_range = saleprice_scaled[saleprice_scaled[:, 0].argsort()][-10:]\nprint('outer range (low) of the distribution:')\nprint(low_range)\nprint('\\nouter range (high) of the distribution:')\nprint(high_range)\n\n# outer range最后两个大于7的断定为异常值,删掉\ntrain_data.drop(train_data[(train_data['GrLivArea'] > 4000) & (\n train_data['SalePrice'] < 200000)].index, inplace=True)\n\n# 二元变量分析 bivariate analysis saleprice/grlivarea\nplt.scatter(x=train_data['TotalBsmtSF'], y=train_data['SalePrice'])\nplt.ylim(0, 800000)\n\n# 另一种画图方式:用pandas里的plot\nvar = 'TotalBsmtSF'\ndata = pd.concat([train_data['SalePrice'], train_data[var]], axis=1)\ndata.plot.scatter(x=var, y='SalePrice', ylim=(0, 800000))\n# %% 深入了解 SalePrice, Who is 'SalePrice'?\n# 应该验证四个假设:\n# 1. 正态性-当谈论正态性时,我们的意思是数据看起来应该像正态分布。 这很重要,因为几个统计检验都依赖于此(例如t统计)。 在本练习中,我们将仅检查“ SalePrice”的单变量正态性(这是一种有限的方法)。 请记住,单变量正态性不能确保多元正态性(这是我们希望拥有的),但可以提供帮助。 要考虑的另一个细节是,在大样本(> 200个观测值)中,正态性不是这样的问题。 但是,如果我们解决正态性,就可以避免很多其他问题(例如,异方差性),这就是我们进行此分析的主要原因。\n# 2. 同方差性 - 我只希望我写的是正确的。 同方差性是指“假设因变量在预测变量范围内表现出相等的方差水平”。 同方差性是理想的,因为我们希望误差项在自变量的所有值上都相同。\n# 3. 线性-评估线性的最常用方法是检查散点图并搜索线性模式。 如果模式不是线性的,则探索数据转换是值得的。 但是,由于我们所看到的大多数散点图似乎都具有线性关系,因此我们不会对此进行讨论。\n# 4. 缺少相关错误-正如定义所暗示的,相关错误发生在一个错误与另一个错误相关时。 例如,如果一个正误差系统地产生一个负误差,则意味着这些变量之间存在关联。 这通常发生在时间序列中,其中某些模式与时间相关。 我们也不会涉及到这一点。 但是,如果检测到某些东西,请尝试添加一个变量,该变量可以解释所获得的效果。 这是相关错误的最常见解决方案。\n# 这里的重点是要以非常精简的方式测试“ SalePrice”。 我们将注意以下事项:\n# 1. 直方图-峰度和偏度。\n# 2. 正态概率图-数据分布应紧跟代表正态分布的对角线。\n\n# histogram and normal probability plot\nsns.distplot(train_data['SalePrice'], fit=norm)\nfig = plt.figure()\nres = stats.probplot(train_data['SalePrice'], plot=plt)\n# 结论:\n# 'SalePrice' is not normal. It shows 'peakedness', positive skewness and does not follow the diagonal line(对角线).\n# 对于正偏度,通过取log来纠正\ntrain_data['SalePrice'] = np.log(train_data['SalePrice'])\n# transformed histogram and normal probability plot\nsns.distplot(train_data['SalePrice'], fit=norm)\nfig = plt.figure()\nres = stats.probplot(train_data['SalePrice'], plot=plt)\n# Done!\n\n# %% 处理 GrLivArea\nsns.distplot(train_data['GrLivArea'], fit=norm)\nfig = plt.figure()\nres = stats.probplot(train_data['GrLivArea'], plot=plt)\n# log\ntrain_data['GrLivArea'] = np.log(train_data['GrLivArea'])\n# transformed histogram and normal probability plot\nsns.distplot(train_data['GrLivArea'], fit=norm)\nfig = plt.figure()\nres = stats.probplot(train_data['GrLivArea'], plot=plt)\n\n# %%timeit\n# 处理 TotalBsmtSF\nsns.distplot(train_data['TotalBsmtSF'], fit=norm)\nfig = plt.figure()\nres = stats.probplot(train_data['TotalBsmtSF'], plot=plt)\n# 对于没有bsmt的数据不能取对数\ntrain_data['TotalBsmtSF'] = train_data['TotalBsmtSF'].apply(\n lambda x: np.log(x) if x != 0 else x)\n\n\nsns.distplot(train_data[train_data['TotalBsmtSF'] > 0]\n ['TotalBsmtSF'], fit=norm)\nfig = plt.figure()\nres = stats.probplot(\n train_data[train_data['TotalBsmtSF'] > 0]['TotalBsmtSF'], plot=plt)\n","sub_path":"DataScience/Kaggle/HoursePrice/Kaggle-learning3.py","file_name":"Kaggle-learning3.py","file_ext":"py","file_size_in_byte":8187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"620396985","text":"# Simple demo of printing the temperature from the first found DS18x20 sensor every second.\r\n# Author: Tony DiCola\r\nimport time\r\n\r\nimport board\r\n\r\nfrom adafruit_onewire.bus import OneWireBus\r\nfrom adafruit_ds18x20 import DS18X20\r\n\r\n\r\n# Initialize one-wire bus on board pin D5.\r\now_bus = OneWireBus(board.D5)\r\n\r\n# Scan for sensors and grab the first one found.\r\nds18_bus=ow_bus.scan()\r\nprint(ds18_bus)\r\n\r\nds18=[]\r\nfor probe in ds18_bus:\r\n print(probe)\r\n ds18.append(DS18X20(ow_bus, probe))\r\n\r\n# Main loop to print the temperature every second.\r\nwhile True:\r\n\r\n for sensor in ds18:\r\n print('{0:0.3f}C'.format(sensor.temperature))\r\n time.sleep(5.0)\r\n","sub_path":"feather/onewire_test.py","file_name":"onewire_test.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"546967230","text":"import classes.functions as f\nimport classes.globals as g\nimport datetime\nimport sys\n\nfrom classes.measure_component import measure_component\nfrom classes.measure_condition import measure_condition\nfrom classes.footnote_association_measure import footnote_association_measure\n\n\nclass measure(object):\n def __init__(self, goods_nomenclature_item_id, quota_order_number_id, origin_identifier, duty_amount,\n monetary_unit_code, measurement_unit_code, measurement_unit_qualifier_code, measure_type_id,\n start_date_override=\"\", end_date_override=\"\", measure_sid=-1):\n # from parameters\n self.goods_nomenclature_item_id = goods_nomenclature_item_id\n self.quota_order_number_id = quota_order_number_id\n self.origin_identifier = origin_identifier\n self.duty_amount = duty_amount\n self.monetary_unit_code = monetary_unit_code\n self.measurement_unit_code = measurement_unit_code\n self.measurement_unit_qualifier_code = measurement_unit_qualifier_code\n self.measure_type_id = measure_type_id\n self.start_date_override = start_date_override\n self.end_date_override = end_date_override\n self.goods_nomenclature_sid = 0\n self.duty_list = []\n\n lx = len(self.goods_nomenclature_item_id)\n if (lx < 10):\n self.goods_nomenclature_item_id += (\"0\" * (10 - lx))\n\n # Get the goods nomenclature SID\n sql = \"\"\"SELECT goods_nomenclature_sid FROM goods_nomenclatures\n WHERE producline_suffix = '80' AND goods_nomenclature_item_id = %s\n AND (validity_end_date is null) ORDER BY validity_start_date DESC LIMIT 1\"\"\"\n params = [\n self.goods_nomenclature_item_id\n ]\n cur = g.app.conn.cursor()\n cur.execute(sql, params)\n rows = cur.fetchall()\n if len(rows) > 0:\n self.goods_nomenclature_sid = rows[0][0]\n else:\n # print(\"Error - incorrect goods nomenclature item ID -\", self.goods_nomenclature_item_id)\n self.goods_nomenclature_sid = -1\n\n # Initialised\n self.justification_regulation_id = \"\"\n self.justification_regulation_role = \"1\"\n self.measure_generating_regulation_role = 1\n self.stopped_flag = \"0\"\n self.additional_code_type_id = \"\"\n self.additional_code_id = \"\"\n self.additional_code_sid = \"\"\n self.reduction_indicator = \"\"\n self.export_refund_nomenclature_sid = \"\"\n\n self.measure_component_list = []\n self.measure_sid = measure_sid\n\n def duty_string(self):\n if self.monetary_unit_code == \"\":\n return str(self.duty_amount) + \"%\"\n else:\n out = \"€\"\n out += format(self.duty_amount, \"^0.3f\")\n if self.measurement_unit_code != \"\":\n out += \" per \" + self.fmt_mu()\n\n if self.measurement_unit_qualifier_code != \"\":\n out += \" (\" + self.fmt_muq() + \")\"\n\n return (out)\n\n def fmt_muq(self):\n if self.measurement_unit_qualifier_code == \"E\":\n return (\"net of drained weight\")\n else:\n return (\"blah blah blah\")\n\n def fmt_mu(self):\n if self.measurement_unit_code == \"TNE\":\n return (\"1000kg\")\n elif self.measurement_unit_code == \"DTN\":\n return (\"100kg\")\n elif self.measurement_unit_code == \"DAP\":\n return (\"Decatonne, corrected according to polarisation\")\n elif self.measurement_unit_code == \"HLT\":\n return (\"hl\")\n else:\n return self.measurement_unit_code\n\n def transfer_sid(self):\n pass\n\n def xml(self):\n if self.goods_nomenclature_sid == -1:\n return \"\"\n\n s = g.app.template_measure\n s = s.replace(\"[TRANSACTION_ID]\", str(g.app.transaction_id))\n s = s.replace(\"[MESSAGE_ID]\", str(g.app.message_id))\n s = s.replace(\"[RECORD_SEQUENCE_NUMBER]\", str(g.app.message_id))\n\n for obj in self.measure_component_list:\n obj.measure_sid = self.measure_sid\n obj.update_type = \"3\"\n\n if self.measure_excluded_geographical_area_list is not None:\n for obj in self.measure_excluded_geographical_area_list:\n obj.measure_sid = self.measure_sid\n obj.update_type = \"3\"\n\n s = s.replace(\"[UPDATE_TYPE]\", \"3\")\n s = s.replace(\"[MEASURE_SID]\", f.mstr(self.measure_sid))\n s = s.replace(\"[MEASURE_TYPE_ID]\", f.mstr(self.measure_type_id))\n s = s.replace(\"[GEOGRAPHICAL_AREA_ID]\", f.mstr(self.geographical_area_id))\n s = s.replace(\"[GOODS_NOMENCLATURE_ITEM_ID]\", f.mstr(self.goods_nomenclature_item_id))\n s = s.replace(\"[VALIDITY_START_DATE]\", self.validity_start_date)\n s = s.replace(\"[MEASURE_GENERATING_REGULATION_ROLE]\", f.mstr(self.measure_generating_regulation_role))\n s = s.replace(\"[MEASURE_GENERATING_REGULATION_ID]\", f.mstr(self.measure_generating_regulation_id))\n if self.validity_end_date is None:\n print(self.goods_nomenclature_item_id, self.quota_order_number_id)\n s = s.replace(\"[VALIDITY_END_DATE]\", f.mstr(self.validity_end_date))\n s = s.replace(\"[JUSTIFICATION_REGULATION_ROLE]\", f.mstr(self.justification_regulation_role))\n s = s.replace(\"[JUSTIFICATION_REGULATION_ID]\", f.mstr(self.justification_regulation_id))\n s = s.replace(\"[STOPPED_FLAG]\", self.stopped_flag)\n s = s.replace(\"[GEOGRAPHICAL_AREA_SID]\", f.mstr(self.geographical_area_sid))\n s = s.replace(\"[GOODS_NOMENCLATURE_SID]\", f.mstr(self.goods_nomenclature_sid))\n s = s.replace(\"[ORDERNUMBER]\", f.mstr(self.quota_order_number_id))\n s = s.replace(\"[ADDITIONAL_CODE_TYPE_ID]\", f.mstr(self.additional_code_type_id))\n s = s.replace(\"[ADDITIONAL_CODE_ID]\", f.mstr(self.additional_code_id))\n s = s.replace(\"[ADDITIONAL_CODE_SID]\", f.mstr(self.additional_code_sid))\n s = s.replace(\"[REDUCTION_INDICATOR]\", f.mstr(self.reduction_indicator))\n s = s.replace(\"[EXPORT_REFUND_NOMENCLATURE_SID]\", f.mstr(self.export_refund_nomenclature_sid))\n\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n s = s.replace(\"\\t\\t\\t\\t\\t\\t \\n\", \"\")\n\n g.app.message_id += 1\n\n self.component_content = \"\"\n self.condition_content = \"\"\n self.condition_component_content = \"\"\n self.exclusion_content = \"\"\n self.footnote_content = \"\"\n self.pts_content = \"\"\n\n for obj in self.measure_component_list:\n self.component_content += obj.xml()\n\n for obj in self.measure_excluded_geographical_area_list:\n obj.measure_sid = self.measure_sid\n self.exclusion_content += obj.measure_xml()\n\n if self.quota_order_number_id[0:3] == \"094\":\n # Add the standard conditions\n self.conditions = []\n my_condition = measure_condition(self.measure_sid, \"C\", 1, \"27\", \"L\", \"001\")\n self.conditions.append(my_condition)\n\n my_condition = measure_condition(self.measure_sid, \"C\", 2, \"07\", None, None)\n self.conditions.append(my_condition)\n\n my_condition = measure_condition(self.measure_sid, \"Q\", 1, \"27\", \"Y\", \"100\")\n self.conditions.append(my_condition)\n\n my_condition = measure_condition(self.measure_sid, \"Q\", 2, \"07\", None, None)\n self.conditions.append(my_condition)\n\n for c in self.conditions:\n self.condition_content += c.xml()\n\n # Add the standard footnote\n self.footnotes = []\n fn = footnote_association_measure(self.measure_sid, \"CD\", \"356\")\n self.footnotes.append(fn)\n\n for fn in self.footnotes:\n self.footnote_content += fn.xml()\n\n s = s.replace(\"[COMPONENTS]\\n\", self.component_content)\n s = s.replace(\"[CONDITIONS]\\n\", self.condition_content)\n s = s.replace(\"[CONDITION_COMPONENTS]\\n\", self.condition_component_content)\n s = s.replace(\"[EXCLUDED]\\n\", self.exclusion_content)\n s = s.replace(\"[FOOTNOTES]\\n\", self.footnote_content)\n s = s.replace(\"[PTS]\\n\", self.pts_content)\n\n return (s)\n","sub_path":"create-data/quotas/classes/measure.py","file_name":"measure.py","file_ext":"py","file_size_in_byte":9278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"308508013","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution(object):\n def getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n a=headA\n b=headB\n while not a==b:\n if a==None:\n a=headB\n else:\n a=a.next\n if b==None:\n b=headA\n else:\n b=b.next\n return a\n\ns=Solution()\nz=ListNode(0)\na=ListNode(1)\nb=ListNode(2)\nc=ListNode(3)\nz.next=a\na.next=c\n# b.next=c\nprint(s.getIntersectionNode(z,b).val)","sub_path":"getIntersectionNode.py","file_name":"getIntersectionNode.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"437891694","text":"import boto.ec2\nimport time\nimport sys\nfrom boto.ec2.regioninfo import RegionInfo\n\n\nCOOKIE = \"COOKIE\"\nPASSWORD = \"PASSWORD\"\n\n\ndef main(argv):\n nInstances = int(argv[1])\n\n while nInstances:\n region = RegionInfo(name='REGION', endpoint='ENDPOINT')\n\n ec2_my_conn = boto.connect_ec2(\n aws_access_key_id='YOUR_ACCESS_KEY',\n aws_secret_access_key='YOUR_SECRET_ACCESS_KEY',\n is_secure=True,\n region=region,\n port=8773,\n path='/services/Cloud',\n validate_certs=False\n )\n\n reservation = ec2_my_conn.run_instances(\n 'ami-190a1773',\n key_name='KEY',\n instance_type='m2.tiny',\n security_groups=['CouchDB nodes', 'ssh'],\n placement='melbourne-qh2'\n )\n\n instance = reservation.instances[0]\n print('New instance with id: {}, was created.'.format(instance.id))\n\n #vol = ec2_my_conn.create_volume(50, 'melbourne-np')\n #print ('A volume with id: {}, has been created'.format(vol.id))\n\n status = instance.state\n while status != 'running':\n time.sleep(2)\n print ('The instance with id: {} is booting, please wait.'.format(instance.id))\n time.sleep(15)\n status = instance.update()\n\n print('The instance is ready')\n\n #ec2_my_conn.attach_volume(vol.id, instance.id, '/dev/vdc')\n #print (\"volume with id{}, was attached to instance with id {}\".format(vol.id, instance.id))\n\n #time.sleep(7)\n #snapshot = ec2_my_conn.create_snapshot(vol.id, 'instance_snapshot')\n #print ('snapshot {}, of volume {}, was created'.format(snapshot.id, vol.id))\n\n #new_vol = snapshot.create_volume('melbourne-np')\n #print ('creating volume from snapshot')\n\n #ec2_my_conn.delete_snapshot(snapshot.id)\n #print ('snapshot with id {}, was deleted'.format(snapshot.id))\n nInstances -= 1\n\n reservations = ec2_my_conn.get_all_reservations()\n\n INVENTORY_PATH = \"couchdb-inventory\"\n\n print('Index\\tID\\t\\tInstance')\n for idx, res in enumerate(reservations):\n print('{}\\t{}\\t{}'.format(idx, res.id, res.instances))\n\n toWrite = \"\"\n for i in range(len(reservations)):\n print('\\nID: {}\\tIP {}\\tPlacement {}'.format(\n reservations[i].id,\n reservations[i].instances[0].private_ip_address,\n reservations[i].instances[0].placement,\n ))\n if (i == 0):\n toWrite += '[nodes]\\n' + str(reservations[i].instances[0].private_ip_address) + '\\n'\n else:\n toWrite += str(reservations[i].instances[0].private_ip_address) + '\\n'\n\n inventoryfile = open(INVENTORY_PATH, 'w+')\n inventoryfile.write(toWrite)\n inventoryfile.close()\n\n DEFAULTS_PATH = \"roles/couchdb/defaults/main.yaml\"\n\n defaultspath = open(DEFAULTS_PATH, 'w+')\n defaultspath.write(\"---\\nCOOKIE: \\\"\"+ COOKIE + \"\\\"\\nN_NODES: \" + argv[1] + \"\\nPASSWORD: \\\"\"+PASSWORD+\"\\\"\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"boto_script.py","file_name":"boto_script.py","file_ext":"py","file_size_in_byte":3061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"578642491","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\ndef bubble_sort(arr):\r\n for i in range(0, len(arr)):\r\n for j in range(i+1, len(arr)):\r\n if arr[j] < arr[i]:\r\n tmp = arr[i]\r\n arr[i] = arr[j]\r\n arr[j] = tmp\r\n\r\nimport csv\r\nimport os\r\nimport time\r\n\r\nif __name__ == \"__main__\":\r\n my_arr = [1,22,9, 15, 18, 3, 2, 6, 8]\r\n bubble_sort(my_arr)\r\n print(my_arr)\r\n\r\n script_dir = os.path.dirname(__file__)\r\n rel_path = \"raw_sort_data\"\r\n file_path = os.path.join(script_dir, rel_path)\r\n with open(file_path, \"r+t\") as f:\r\n reader = csv.reader(f)\r\n sortlist = list(reader)\r\n start_time = time.time()\r\n bubble_sort(sortlist)\r\n end_time = time.time()\r\n print (\"bubble sort 10000 item cost is \" , (end_time-start_time))\r\n","sub_path":"sort/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"651851448","text":"\"\"\"\n# this expects the json(b) decoder to be as such:\nawait conn.set_type_codec(\n 'json',\n encoder=json.dumps,\n decoder=json.loads,\n schema='pg_catalog'\n )\n\"\"\"\nfrom typez import DefineLang, FnArg, FnRecord, TableRecord\n\n\ndef _get_calling_sql(schema: str, fn: FnRecord) -> str:\n arg_sql = \",\\n \".join([\n f\"{fn.args[i].name} => ${i + 1}::{fn.args[i].type}\"\n for i in range(len(fn.args))\n ])\n bindargs = \", \".join([arg.name for arg in fn.args])\n return f\"\"\"return await db.fetch_val(\\\"\\\"\\\"\n SELECT {schema}.{fn.name}(\n {arg_sql}\n )\n \\\"\\\"\\\", ({bindargs}))\"\"\"\n\n\ndef _type_lookup(typename: str) -> str:\n typemap = {\n \"text\": \"str\",\n \"integer\": \"int\",\n \"uuid\": \"str\",\n \"json\": \"Dict\",\n \"jsonb\": \"Dict\",\n \"boolean\": \"bool\",\n \"bytea\": \"bytes\",\n }\n if len(typename) > 2 and typename[-2:] == \"[]\":\n item_type = typemap[typename[:-2]]\n return f\"List[{item_type}]\"\n return typemap[typename]\n\n\ndef _get_fn_args(fn: FnRecord) -> str:\n def fmt_arg(arg: FnArg) -> str:\n arg_type = _type_lookup(arg.type)\n if arg.default is None:\n return f\"{arg.name}: {arg_type}\"\n new_default = arg.default\n if arg.default == \"NULL\":\n new_default = \"None\"\n return f\"{arg.name}: {arg_type} = {new_default}\"\n return \", \".join([fmt_arg(arg) for arg in fn.args])\n\n\ndef get_impl_language_fn_def(schema: str, fn: FnRecord) -> str:\n calling_sql = _get_calling_sql(schema, fn)\n impl_fn_args = _get_fn_args(fn)\n ret_type = _type_lookup(fn.ret_type)\n impl = f\"\"\"async def {fn.name}({impl_fn_args}) -> {ret_type}:\n {calling_sql}\n\n\"\"\"\n return impl\n\n\ndef _snake_case_to_camel(word):\n return ''.join(x.capitalize() or '_' for x in word.split('_'))\n\n\ndef get_impl_language_model_def(schema: str, view: TableRecord):\n nt_name = _snake_case_to_camel(view.name)\n props = [f\"{col.name}: {_type_lookup(col.type)}\" for col in view.columns]\n props_content = \"\\n \".join(props)\n named_tuple = f\"\"\"class {nt_name}(NamedTuple):\n {props_content}\n\"\"\"\n column_content = \"\\n \".join([f\"'{col.name}': {view.name}_table.{col.name},\" for col in view.columns])\n columns = f\"\"\"{view.name}_table = Table(\"{schema}.{view.name}\")\n{view.name} = Box({{\n 'table_ref': {view.name}_table,\n 'get_query': lambda: PostgreSQLQuery.from_({view.name}_table),\n {column_content}\n}})\"\"\"\n return f\"\"\"{named_tuple}\n\n{columns}\"\"\"\n\n\ndef wrap_view_defs(contents: str) -> str:\n return f\"\"\"from typing import NamedTuple, List, Dict\n\nfrom box import Box # type: ignore\nfrom pypika import Table, PostgreSQLQuery, Schema # type: ignore\n\n\n# views = Schema(\"sys\")\n\n{contents}\n\"\"\"\n\n\ndef wrap_fn_defs(contents: str) -> str:\n return f\"\"\"from typing import Dict, List\n\nimport webskeleton.db as db\n\n\n{contents}\n\"\"\"\n","sub_path":"codegen/define/python_define.py","file_name":"python_define.py","file_ext":"py","file_size_in_byte":2923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"4579400","text":"#!/usr/bin/env python3\n\"\"\"LeetCode CLI interface and helper functions.\n\nUsage: lc [-h] [-v] command ...\n\npositional arguments:\n command\n init Initilize at a directory and set up remote GitHub repo.\n new Create a new LeetCode solution from template.\n upload (u) Commit a LeetCode solution and push to GitHub.\n template (t)\n Set up a template file for writing solutions.\n category (c)\n Add/Remove categories which LeetCode problems belong to.\n\noptional arguments:\n -h, --help show this help message and exit\n -v, --version show program's version number and exit\n\"\"\"\n\nimport argparse\nfrom datetime import datetime\nimport os\nimport subprocess\nimport json\n\n__version__ = \"0.2.2\"\n__author__ = \"Weiran Fu\"\n__license__ = \"MIT\"\n\nthis_dir, this_filename = os.path.split(__file__)\nDATA_PATH = os.path.abspath(os.path.join(this_dir, \"data.json\"))\nDEFAULT_TEMPLATE_PATH = os.path.abspath(os.path.join(this_dir, \"template.md\"))\ndata = {}\nTEMPLATE_PATH = \"\"\nBASE_DIR = \"\"\ncategories = []\n# load data from data.json\nwith open(DATA_PATH, 'r') as f:\n data = json.load(f)\n TEMPLATE_PATH = data['template']\n BASE_DIR = data['base_dir']\n categories = data['categories']\nif not TEMPLATE_PATH:\n TEMPLATE_PATH = DEFAULT_TEMPLATE_PATH\n\n\ndef init(args):\n \"\"\"Initialize at current directory.\"\"\"\n data['base_dir'] = os.path.abspath(args.directory)\n data['template'] = \"\"\n with open(DATA_PATH, 'w') as f:\n json.dump(data, f)\n subprocess.call([\"git\", \"init\"], cwd=args.directory)\n subprocess.call([\"git\", \"remote\", \"rm\", \"origin\"],\n cwd=args.directory,\n stderr=subprocess.DEVNULL) # omit error in subprocess\n subprocess.call([\"git\", \"remote\", \"add\", \"origin\", args.remote_repo],\n cwd=args.directory)\n\n\ndef create_file(args):\n \"\"\"Create a new LeetCode solution from template.\"\"\"\n filename = args.filename + \".md\"\n target_path = \"{}/Problems/{}/{}\".format(\n BASE_DIR, args.category,\n filename) if args.category != \"Summary\" else \"{}/Summary/{}\".format(\n BASE_DIR, filename)\n # open the template and read lines\n lines = open(TEMPLATE_PATH, 'r').readlines()\n # update title && category && datetime in solution file\n title = \" \".join([s.capitalize() for s in filename[:-3].split(\"-\")])\n now = datetime.now()\n dt_string = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n # create a new file and write lines\n os.makedirs(os.path.dirname(target_path), exist_ok=True)\n if TEMPLATE_PATH != DEFAULT_TEMPLATE_PATH:\n with open(target_path, 'w') as fp:\n for line in lines:\n fp.write(line)\n else:\n with open(target_path, 'w') as fp:\n fp.write(lines[0])\n for line in lines[1:]:\n if \"title:\" in line:\n fp.write(\"title: Easy Medium Hard | {}\\n\".format(title))\n elif \"Graph\" in line:\n fp.write(\" - {}\\n\".format(args.category))\n elif \"date:\" in line:\n fp.write(\"date: {}\\n\".format(dt_string))\n elif \"TITLE\" in line:\n fp.write(\"# {}\\n\".format(title))\n else:\n fp.write(line)\n subprocess.call([\"open\", target_path])\n\ndef open_file(args):\n \"\"\"Open a LeetCode solution contains this filename.\"\"\"\n searchname = args.filename\n names = []\n paths = []\n for root, dirs, files in os.walk(BASE_DIR):\n for name in files:\n if searchname.lower() in name.lower():\n names.append(name)\n paths.append(os.path.join(root, name))\n if len(names) == 0:\n print(\"Cannot search any solution contains {}.\".format(searchname))\n return\n for i in range(len(names)):\n print(\"{}. {}\".format(i, names[i]))\n num = int(input(\"Please choose one to open:\\n\"))\n subprocess.call([\"open\", paths[num]])\n\ndef upload_files(args):\n \"\"\"Commit a LeetCode solution and push to GitHub.\"\"\"\n subprocess.call([\"git\", \"add\", \".\"], cwd=BASE_DIR)\n subprocess.call([\"git\", \"commit\", \"-m\", args.m], cwd=BASE_DIR)\n subprocess.call([\"git\", \"push\", \"origin\", \"main\"], cwd=BASE_DIR)\n\n\ndef template(args):\n template_path = \"\"\n if args.set:\n if os.path.isabs(args.set):\n template_path = args.set\n else:\n template_path = os.path.abspath(args.set)\n else:\n template_path = DEFAULT_TEMPLATE_PATH\n data['template'] = template_path\n with open(DATA_PATH, 'w') as f:\n json.dump(data, f)\n\n\ndef category_add(args):\n if args.category in categories:\n return\n categories.append(args.category)\n data['categories'] = sorted(categories)\n with open(DATA_PATH, 'w') as f:\n json.dump(data, f)\n\n\ndef category_rm(args):\n if args.category not in categories:\n return\n categories.remove(args.category)\n data['categories'] = categories\n with open(DATA_PATH, 'w') as f:\n json.dump(data, f)\n\n\n# Construct the CLI\nparser = argparse.ArgumentParser(\n description=\"LeetCode CLI interface and helper functions.\",\n prog=\"lc\",\n epilog=\n \"Further documentation is available at .\"\n)\nparser.add_argument(\"-v\",\n \"--version\",\n action=\"version\",\n version='%(prog)s version ' + __version__)\n\n\ndef parser_help(args):\n parser.print_help()\n\n\nparser.set_defaults(func=parser_help)\nsubparsers = parser.add_subparsers(metavar=\"command\")\n\nparser_init = subparsers.add_parser(\n 'init', help=\"Initilize at a directory and set up remote GitHub repo.\")\nparser_init.add_argument(\"directory\",\n metavar=\"\",\n help=\"The path to the directory to initialize at.\")\nparser_init.add_argument(\n \"remote_repo\",\n metavar=\"\",\n help=\"The link of remote GitHub repo to connect with.\")\nparser_init.set_defaults(func=init)\n\nparser_new = subparsers.add_parser(\n \"new\", help=\"Create a new LeetCode solution from template.\")\nparser_new.add_argument(\"filename\",\n metavar=\"\",\n help=\"The filename of LeetCode solution.\")\nparser_new.add_argument(\n \"category\",\n metavar=\"\",\n choices=categories,\n help=\"The category which LeetCode solution belongs to.\")\nparser_new.set_defaults(func=create_file)\n\nparser_open = subparsers.add_parser(\"open\", help=\"Open an existing solution.\")\nparser_open.add_argument(\"filename\", metavar=\"\", help=\"The filename of the solution.\")\nparser_open.set_defaults(func=open_file)\n\nparser_upload = subparsers.add_parser(\n \"upload\",\n aliases=[\"u\"],\n help=\"Commit a LeetCode solution and push to GitHub.\")\nparser_upload.add_argument(\"-m\",\n metavar=\"\",\n default=\":pencil: LeetCode with Me!\",\n help=\"The Git commit message\")\nparser_upload.set_defaults(func=upload_files)\n\nparser_template = subparsers.add_parser(\n \"template\",\n aliases=['t'],\n help=\"Set up a template file for writing solutions.\")\ngroup = parser_template.add_mutually_exclusive_group(\n required=True) # One of -set and --use-default must be chosen\ngroup.add_argument(\"-set\",\n metavar=\"\",\n help=\"The path to the template file.\")\ngroup.add_argument(\"--use-default\",\n action=\"store_true\",\n help=\"Use default template file.\")\ngroup.set_defaults(func=template)\n\nparser_category = subparsers.add_parser(\n 'category',\n aliases=['c'],\n help=\"Add/Remove categories which LeetCode problems belong to.\")\n\n\ndef parser_category_help(args):\n parser_category.print_help()\n\n\nparser_category.set_defaults(func=parser_category_help)\ncategory_subparsers = parser_category.add_subparsers(metavar=\"command\")\n\ncategory_parser_add = category_subparsers.add_parser(\n 'add', help=\"Add a new category.\")\ncategory_parser_add.add_argument(\"category\",\n metavar=\"\",\n help=\"The name of the category.\")\ncategory_parser_add.set_defaults(func=category_add)\n\ncategory_parser_rm = category_subparsers.add_parser('rm',\n help=\"Remove a category.\")\ncategory_parser_rm.add_argument(\"category\",\n metavar=\"\",\n help=\"The name of the category.\")\ncategory_parser_rm.set_defaults(func=category_rm)\n\n\ndef main():\n args = parser.parse_args()\n if \"remote_repo\" not in args and not BASE_DIR:\n parser.error(\n \"Please first initialize at a directory using `lc init `.\"\n )\n if \"set\" in args and args.set:\n if args.set[-3:] != \".md\":\n parser.error(\n \"Please use markdown file as template, e.g. ~/path/to/template.md\"\n )\n args.func(args)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"build/lib/lc/lc.py","file_name":"lc.py","file_ext":"py","file_size_in_byte":9118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"482201244","text":"from matplotlib import pyplot as plt\r\nfrom matplotlib import style\r\n\r\n\r\n#Este algoritmo trabaja de igual forma con las distancias\r\n#Eucledianas y calcula la media de los centroides para redefinir un nuevo centroide que sera\r\n#El cluster.\r\n\r\nstyle.use('ggplot')\r\nimport numpy as np\r\nfrom sklearn.cluster import KMeans\r\n\r\nX = np.array([[1,2],\r\n [1.5, 1.8],\r\n [5,8],\r\n [8,8],\r\n [1,0.6],\r\n [9,11]])\r\n\r\n#plt.scatter(X[:,0],X[:,1],s = 150,c='b')\r\n#plt.show()\r\n\r\nclf = KMeans(n_clusters = 3)\r\nclf.fit(X)\r\n\r\ncentroids = clf.cluster_centers_\r\nlabels = clf.labels_\r\n\r\ncolors = 10*[\"g.\",\"r.\",\"c.\",\"b.\",\"k.\"]\r\n\r\nfor i in range(len(X)):\r\n plt.plot(X[i][0],X[i][1],colors[labels[i]],markersize = 10)\r\n\r\nplt.scatter(centroids[:,0],centroids[:,1],marker = 'x',s = 150, linewidth = 5)\r\nplt.show()\r\n","sub_path":"UnsupervisedMachineLearning/KMeansSklearn.py","file_name":"KMeansSklearn.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"538385809","text":"import argparse\nimport json\nimport operator\nfrom functools import reduce\n\nimport numpy\n\nimport onnx.numpy_helper\nimport onnx.external_data_helper\n\nLARGE_TENSOR_DATA_THRESHOLD = 100\n\n\ndef is_large_tensor(tensor, threshold):\n size = reduce(operator.mul, tensor.dims, 1)\n return size > threshold\n\n\ndef _is_stripped(tensor):\n for external_data in tensor.external_data:\n if external_data.key != 'location':\n continue\n try:\n external_value_dict = json.loads(external_data.value)\n return external_value_dict.get('type', '') == 'stripped'\n except ValueError:\n # Invalid JSON, indicating `external_data.value` contains\n # a file path\n continue\n return False\n\n\ndef _strip_raw_data(tensor):\n arr = onnx.numpy_helper.to_array(tensor)\n meta_dict = {}\n meta_dict['type'] = \"stripped\"\n meta_dict['average'] = float(numpy.average(arr))\n meta_dict['variance'] = float(numpy.var(arr))\n onnx.external_data_helper.set_external_data(tensor,\n location=json.dumps(meta_dict),\n length=len(tensor.raw_data))\n tensor.data_location = onnx.TensorProto.EXTERNAL\n tensor.ClearField('raw_data')\n tensor.ClearField('float_data')\n return tensor\n\n\ndef _strip_large_initializer_raw_data(onnx_model, large_tensor_threshold):\n for init in onnx_model.graph.initializer:\n if _is_stripped(init):\n continue\n if is_large_tensor(init, large_tensor_threshold):\n _strip_raw_data(init)\n\n\ndef _strip_large_tensor_tool_impl(onnx_path, out_onnx_path,\n large_tensor_threshold):\n onnx_model = onnx.load(onnx_path, load_external_data=False)\n _strip_large_initializer_raw_data(onnx_model, large_tensor_threshold)\n with open(out_onnx_path, 'wb') as fp:\n fp.write(onnx_model.SerializeToString())\n\n\ndef _strip_large_tensor_tool():\n parser = argparse.ArgumentParser()\n parser.add_argument('onnx_path', type=str)\n parser.add_argument('--out_onnx_path', type=str, default=None)\n parser.add_argument('--large_tensor_threshold',\n type=int,\n default=LARGE_TENSOR_DATA_THRESHOLD)\n args = parser.parse_args()\n out_onnx_path = args.out_onnx_path\n if out_onnx_path is None:\n out_onnx_path = args.onnx_path\n\n _strip_large_tensor_tool_impl(args.onnx_path, out_onnx_path,\n args.large_tensor_threshold)\n\n\nif __name__ == '__main__':\n _strip_large_tensor_tool()\n","sub_path":"pytorch_pfn_extras/onnx/strip_large_tensor.py","file_name":"strip_large_tensor.py","file_ext":"py","file_size_in_byte":2614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"494470583","text":"from __future__ import print_function\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import cm, pyplot as plt\nfrom sklearn.externals import joblib\nfrom hmmlearn.hmm import GaussianHMM\nimport ipdb\nimport os\nimport ConfigParser\nprint(__doc__)\n\n\n\n\n# read the current file path\nfile_path = os.path.dirname(__file__)\n# read model cfg file\ncp_models = ConfigParser.SafeConfigParser()\ncp_models.read(os.path.join(file_path, '../cfg/models.cfg'))\ndatasets_path = os.path.join(file_path, cp_models.get('datasets', 'path'))\n\n# load dataset\ndatasets_raw = joblib.load(os.path.join(datasets_path, 'pkl/datasets_raw.pkl'))\n\n# task name\ntask_name = joblib.load(os.path.join(datasets_path, 'pkl/task_name_list.pkl'))\n\n# joint number\nnum_joints = cp_models.getint('datasets', 'num_joints')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n###############################################################################\n# Get quotes from Yahoo! finance\ndate1 = \"1996-2-1\"\ndate2 = \"2004-4-12\"\n\n\nmondays = WeekdayLocator(MONDAY) # major ticks on the mondays\nalldays = DayLocator() # minor ticks on the days\nweekFormatter = DateFormatter('%b %d') # e.g., Jan 12\ndayFormatter = DateFormatter('%d') # e.g., 12\n\nquotes = pd.read_csv('data/yahoofinance-INTC-19950101-20040412.csv',\n index_col=0,\n parse_dates=True,\n infer_datetime_format=True)\n\nquotes = quotes[(quotes.index >= date1) & (quotes.index <= date2)]\n# Unpack quotes\ndates = np.array((quotes.index))\nclose_v = np.array(quotes['Close'])\nvolume = np.array(quotes['Volume'])[1:]\n\n# Take diff of close value. Note that this makes\n# ``len(diff) = len(close_t) - 1``, therefore, other quantities also\n# need to be shifted by 1.\ndiff = np.diff(close_v)\ndates = dates[1:]\nclose_v = close_v[1:]\n\n# Pack diff and volume for training.\nX = np.column_stack([diff, volume])\n\n###############################################################################\n# Run Gaussian HMM\nprint(\"fitting to HMM and decoding ...\", end=\"\")\n\n# Make an HMM instance and execute fit\nmodel = GaussianHMM(n_components=4, covariance_type=\"diag\", n_iter=1000).fit(X)\n\n# Predict the optimal sequence of internal hidden state\nhidden_states = model.predict(X)\n\nprint(\"done\")\n\n###############################################################################\n# Print trained parameters and plot\nprint(\"Transition matrix\")\nprint(model.transmat_)\nprint()\n\nprint(\"Means and vars of each hidden state\")\nfor i in range(model.n_components):\n print(\"{0}th hidden state\".format(i))\n print(\"mean = \", model.means_[i])\n print(\"var = \", np.diag(model.covars_[i]))\n print()\n\nfig, axs = plt.subplots(model.n_components, sharex=True, sharey=True)\ncolours = cm.rainbow(np.linspace(0, 1, model.n_components))\nfor i, (ax, colour) in enumerate(zip(axs, colours)):\n # Use fancy indexing to plot data in each state.\n mask = hidden_states == i\n ax.plot_date(dates[mask], close_v[mask], \".-\", c=colour)\n # ipdb.set_trace()\n ax.set_title(\"{0}th hidden state\".format(i))\n\n # Format the ticks.\n ax.xaxis.set_major_locator(YearLocator())\n ax.xaxis.set_minor_locator(MonthLocator())\n\n ax.grid(True)\n\nplt.show()\n","sub_path":"scripts/train_startpoint_hmm.py","file_name":"train_startpoint_hmm.py","file_ext":"py","file_size_in_byte":3175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"269958136","text":"from django.test import LiveServerTestCase\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport unittest\n\nMAX_WAIT = 10\n\n\nclass NewVisitorTest(LiveServerTestCase):\n\n def setUp(self):\n self.browser = webdriver.Firefox()\n\n def tearDown(self):\n self.browser.quit()\n\n def wait_for_row_in_list_table(self, row_text):\n start_time = time.time()\n while True:\n try:\n table = self.browser.find_element_by_id('id_list_table')\n rows = table.find_elements_by_tag_name('tr')\n self.assertIn(row_text, [row.text for row in rows])\n return\n except (AssertionError, WebDriverException) as e:\n if time.tiem() - start_time > MAX_WAIT:\n raise e\n time.sleep(0.5)\n\n\n def test_can_start_a_list_and_retrieve_it_later(self):\n # Edith has heard about a cool new online to-do app. She goes \n # to check out its homepage\n self.browser.get(self.live_server_url)\n\n # She notices the page title and hearder mention to-do lists\n self.assertIn('To-Do', self.browser.title)\n header_text = self.browser.find_element_by_tag_name('h1').text\n self.assertIn('To-Do', header_text)\n\n # She is invited to enter a to-do item straight away\n inputbox = self.browser.find_element_by_id('id_new_item')\n self.assertEqual(\n inputbox.get_attribute('placeholder'),\n 'Enter a to-do item'\n )\n\n # She types \"Buy peacock feathers\" into a text box (Edith's bobby \n # is typing fly-fishing lures)\n inputbox.send_keys(\"Buy peacock feathers\")\n\n # When she hits enter, the page updates, and now the page lists \n # \"1: Buy peacock features\" as an item in a to-do list \n inputbox.send_keys(Keys.ENTER)\n time.sleep(1)\n\n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n # There is still a text box inviting her to add another item. She \n # enters \"Use peacock feathers to make a fly\" (Edith is very \n # methodical)\n inputbox = self.browser.find_element_by_id('id_new_item')\n inputbox.send_keys('Use peacock feathers to make a fly')\n inputbox.send_keys(Keys.ENTER)\n time.sleep(2)\n\n # The page updates again, and now shows both items on her list. \n self.wait_for_row_in_list_table('1: Buy peacock feathers')\n self.wait_for_row_in_list_table('2: Use peacock feathers to make a fly')\n\n # Edith wonders whether the site will remember her list. Then she\n # sees that the site has generated a unique URL for her -- there \n # is some explanatory etext to htat effect \n self.fail('Finish the test!')\n\n # Satisfied, she goes back to sleep\n\n","sub_path":"functional_tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"182011359","text":"import numpy as np\nimport tensorflow as tf\n\n### RGB mean value ###\nmean_R, mean_G, mean_B = 124.2, 123.4, 123.7\nstd = 69.68\nrgb = 123.767\nmean_RGB = [[rgb, rgb, rgb] for i in range(32*32)]\n#mean_RGB = [mean_R for i in range(32*32)] + [mean_G for i in range(32*32)] + [mean_B for i in range(32*32)]\n\n### VGGNet model ###\nclass SparseResNet(object):\n def __init__(self, config, is_training = False):\n self.num_classes = config.num_classes\n self.num_classes2 = config.num_classes2\n self.num_classes3 = config.num_classes3\n\n self.dataset = config.dataset\n self.lr = config.learning_rate\n self.beta = config.beta\n\n self.image_size = 32\n self.input_channel = 3\n self.n = config.num_layers\n\n self.batch_size = config.batch_size\n self.num_epoch = config.num_epoch\n self.print_step = config.print_step\n self.is_training = is_training\n\n\n self.X = X = tf.placeholder(tf.float32, shape = [None, self.input_channel*(self.image_size**2)], name = 'X_placeholder')\n self.Y1 = Y1 = tf.placeholder(tf.float32, shape = [None, self.num_classes], name = 'Y1_placeholder')\n self.Y2 = Y2 = tf.placeholder(tf.float32, shape = [None, self.num_classes2], name = 'Y2_placeholder')\n self.Y3 = Y3 = tf.placeholder(tf.float32, shape = [None, self.num_classes3], name = 'Y3_placeholder')\n\n self.learning_rate = tf.placeholder(tf.float32, [], name = 'learning_rate')\n\n x = tf.reshape(X, [-1, self.input_channel, self.image_size, self.image_size])\n x = tf.cast(tf.transpose(x, [0, 2, 3, 1]), tf.float32)\n #x = tf.reshape(X, [-1, self.image_size, self.image_size, self.input_channel])\n ### pixel normalization ###\n '''\n print('Image standardization')\n x = tf.map_fn(lambda k: tf.image.per_image_standardization(k), x, dtype=tf.float32)\n '''\n\n ### flip, crop and padding ###\n if self.is_training==True:\n print('Training Model')\n print('image randomly flip')\n x = tf.map_fn(lambda k: tf.image.random_flip_left_right(k), x, dtype = tf.float32)\n\n if self.is_training==True:\n print('image crop and padding')\n x = tf.map_fn(lambda k: tf.random_crop(\n tf.image.pad_to_bounding_box(k, 4, 4, 40, 40), [32, 32, 3]), \n x, dtype = tf.float32)\n\n #first layer\n lv1, lv2, lv3 = self.first_layer(x)\n\n first_layers = [lv1, lv1, lv2, lv1, lv2, lv3]\n\n # c 16 \n ## h_layers = [h1lv1, h2lv1, h2lv2, h3lv1, h3lv2, h3lv3] ##\n h_layers = self.res_block(first_layers, 16, 'b1-layer-'+str(0), True)\n for i in range(1, self.n):\n h_layers = self.res_block(h_layers, 16, 'b1-layer-'+str(i))\n\n # c 32\n for i in range(self.n):\n h_layers = self.res_block(h_layers, 32, 'b2-layer-'+str(i))\n\n # c 64\n for i in range(self.n):\n h_layers = self.res_block(h_layers, 64, 'b3-layer-'+str(i))\n\n h1lv1 = h_layers[0]\n h2lv1 = h_layers[1]\n h2lv2 = h_layers[2]\n h3lv1 = h_layers[3]\n h3lv2 = h_layers[4]\n h3lv3 = h_layers[5]\n h1lv1 = self.layers_batch_norm(h_layers[:1], 'fc-lv1-l')[0]\n h2lv1, h2lv2 = self.layers_batch_norm(h_layers[1:3], 'fc-lv2-l')\n h3lv1, h3lv2, h3lv3 = self.layers_batch_norm(h_layers[3:], 'fc-lv3-l')\n\n h_layers = [h1lv1, h2lv1, h2lv2, h3lv1, h3lv2, h3lv3]\n h_layers = self.relu_global_pool(h_layers)\n\n lv1 = h_layers[0]\n lv2 = tf.concat(h_layers[1:3], 1)\n lv3 = tf.concat(h_layers[3:], 1)\n\n y1 = self.fc(lv1, self.num_classes, 'fc-lv1')\n y2 = self.fc(lv2, self.num_classes2, 'fc-lv2')\n y3 = self.fc(lv3, self.num_classes3, 'fc-lv3')\n \n self.loss1 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y1,logits=y1))\n self.loss2 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y2,logits=y2))\n self.loss3 = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=Y3,logits=y3))\n\n correct_predict1 = tf.equal(tf.argmax(y1,1), tf.argmax(Y1,1))\n correct_predict2 = tf.equal(tf.argmax(y2,1), tf.argmax(Y2,1))\n correct_predict3 = tf.equal(tf.argmax(y3,1), tf.argmax(Y3,1))\n self.accur1 = tf.reduce_mean(tf.cast(correct_predict1, tf.float32))\n self.accur2 = tf.reduce_mean(tf.cast(correct_predict2, tf.float32))\n self.accur3 = tf.reduce_mean(tf.cast(correct_predict3, tf.float32))\n\n t_vars = tf.trainable_variables()\n self.l1_vars = [v for v in t_vars if 'lv1' in v.name]\n self.l2_vars = self.l1_vars + [v for v in t_vars if 'lv2' in v.name]\n self.l3_vars = self.l2_vars + [v for v in t_vars if 'lv3' in v.name]\n\n # print vars\n from pprint import pprint\n #if self.is_training:\n #pprint(t_vars)\n #pprint(self.l1_vars)\n #pprint(self.l2_vars)\n\n self.regularizer1 = self.l2loss(self.l1_vars)\n self.regularizer2 = self.l2loss(self.l2_vars)\n self.regularizer3 = self.l2loss(self.l3_vars)\n\n self.loss1 += self.beta * self.regularizer1\n self.loss2 += self.beta * self.regularizer2\n self.loss3 += self.beta * self.regularizer3\n\n with tf.variable_scope(tf.get_variable_scope(), reuse = tf.AUTO_REUSE):\n optimizer = tf.train.MomentumOptimizer(self.learning_rate, 0.9, name='1', use_nesterov=True)\n optimizer2 = tf.train.MomentumOptimizer(self.learning_rate, 0.9, name='2', use_nesterov=True)\n optimizer3 = tf.train.MomentumOptimizer(self.learning_rate, 0.9, name='3', use_nesterov=True)\n self.train_step1 = optimizer.minimize(self.loss1, var_list = self.l1_vars)\n self.train_step2 = optimizer2.minimize(self.loss2, var_list = self.l2_vars)\n self.train_step3 = optimizer3.minimize(self.loss3, var_list = self.l3_vars)\n\n ### functions ###\n def first_layer(self, x):\n with tf.variable_scope('input'):\n if not self.is_training:\n tf.get_variable_scope().reuse_variables()\n #c_init = tf.truncated_normal_initializer(stddev=5e-2)\n #c_init = tf.contrib.layers.xavier_initializer()\n #n = np.sqrt(6/(3*3*(3+16)))\n n = np.sqrt(2.0 / (3*3*16))\n c_init = tf.random_normal_initializer(stddev = n)\n #c_init = tf.random_uniform_initializer(-n, n)\n #b_init = tf.constant_initializer(0.0)\n\n out1 = tf.contrib.layers.conv2d(x, 12, [3,3], activation_fn=None, \n weights_initializer=c_init, scope='lv1')\n out2 = tf.contrib.layers.conv2d(x, 2, [3,3], activation_fn=None, \n weights_initializer=c_init, scope='lv2')\n out3 = tf.contrib.layers.conv2d(x, 2, [3,3], activation_fn=None, \n weights_initializer=c_init, scope='lv3')\n return out1, out2, out3\n\n def res_block(self, x_list, out, scope, activate_before_residual=False):\n num_in = int(x_list[3].shape[3]) + int(x_list[4].shape[3]) + int(x_list[5].shape[3])\n if out//num_in == 2:\n stride = 2\n else:\n stride = 1\n\n with tf.variable_scope(scope, reuse = tf.AUTO_REUSE):\n if activate_before_residual:\n x11 = self.layers_batch_norm(x_list[:1], 'lv1-res1-')[0]\n x21, x22 = self.layers_batch_norm(x_list[1:3], 'lv2-res1-')\n x31, x32, x33 = self.layers_batch_norm(x_list[3:], 'lv3-res1-')\n\n x_list = [x11, x21, x22, x31, x32, x33]\n x_list = self.layers_relu(x_list)\n shortcut = x_list\n\n x11 = self.lv1conv(x_list[0], out*3/4, stride, 'lv1-res1-')\n x21, x22 = self.lv2conv(x_list[1], x_list[2], out*3/4, out/8, stride, 'lv2-res1-')\n x31, x32, x33 = self.lv3conv(x_list[3], x_list[4], x_list[5],\n out*3/4, out/8, out/8, stride, 'lv3-res1-')\n\n x21 = tf.add(x11, x21)\n x31 = tf.add(x21, x31)\n x32 = tf.add(x22, x32)\n else:\n shortcut = x_list\n\n x11 = self.layers_batch_norm(x_list[:1], 'lv1-res1-')[0]\n x21, x22 = self.layers_batch_norm(x_list[1:3], 'lv2-res1-')\n x31, x32, x33 = self.layers_batch_norm(x_list[3:], 'lv3-res1-')\n\n x_list = [x11, x21, x22, x31, x32, x33]\n x_list = self.layers_relu(x_list)\n\n x11 = self.lv1conv(x_list[0], out*3/4, stride, 'lv1-res1-')\n x21, x22 = self.lv2conv(x_list[1], x_list[2], out*3/4, out/8, stride, 'lv2-res1-')\n x31, x32, x33 = self.lv3conv(x_list[3], x_list[4], x_list[5],\n out*3/4, out/8, out/8, stride, 'lv3-res1-')\n\n x21 = tf.add(x11, x21)\n x31 = tf.add(x21, x31)\n x32 = tf.add(x22, x32)\n\n x_list = [x11, x21, x22, x31, x32, x33]\n x11 = self.layers_batch_norm(x_list[:1], 'lv1-res2-')[0]\n x21, x22 = self.layers_batch_norm(x_list[1:3], 'lv2-res2-')\n x31, x32, x33 = self.layers_batch_norm(x_list[3:], 'lv3-res2-')\n\n x_list = [x11, x21, x22, x31, x32, x33]\n x_list = self.layers_relu(x_list)\n\n x11 = self.lv1conv(x_list[0], out*3/4, 1, 'lv1-res2-')\n x21, x22 = self.lv2conv(x_list[1], x_list[2], out*3/4, out/8, 1, 'lv2-res2-')\n x31, x32, x33 = self.lv3conv(x_list[3], x_list[4], x_list[5],\n out*3/4, out/8, out/8, 1, 'lv3-res2-')\n\n x21 = tf.add(x11, x21)\n x31 = tf.add(x21, x31)\n x32 = tf.add(x22, x32)\n\n if int(num_in) != out:\n shortcut = self.layers_shortcut(shortcut)\n\n x_list[0] = x11 + shortcut[0]\n x_list[1] = x21 + shortcut[1]\n x_list[2] = x22 + shortcut[2]\n x_list[3] = x31 + shortcut[3]\n x_list[4] = x32 + shortcut[4]\n x_list[5] = x33 + shortcut[5]\n\n return x_list\n\n def lv1conv(self, x, dim, stride, scope):\n with tf.variable_scope(scope):\n if not self.is_training:\n tf.get_variable_scope().reuse_variables()\n #n = np.sqrt(6/(4 * 4 * (int(x.shape[3]) + dim)))\n #c_init = tf.random_uniform_initializer(-n, n)\n #c_init = tf.truncated_normal_initializer(stddev=5e-2)\n #c_init = tf.contrib.layers.xavier_initializer()\n #b_init = tf.constant_initializer(0.0)\n n = np.sqrt(2.0 / (3*4*dim))\n c_init = tf.random_normal_initializer(stddev = n)\n\n out = tf.contrib.layers.conv2d(x, dim, [3,3], stride, activation_fn=None, \n weights_initializer=c_init)\n return out\n\n def lv2conv(self, x1, x2, dim1, dim2, stride, scope):\n with tf.variable_scope(scope):\n if not self.is_training:\n tf.get_variable_scope().reuse_variables()\n #n = np.sqrt(6/(4 * 4 * (int(x1.shape[3]) + dim1)))\n #n = np.sqrt(6 / (3 * 3 * int(x1.shape[3] + x2.shape[3]) * (dim1 + dim2)))\n #c_init = tf.random_uniform_initializer(-n, n)\n #c_init = tf.contrib.layers.xavier_initializer()\n #c_init = tf.truncated_normal_initializer(stddev=5e-2)\n #b_init = tf.constant_initializer(0.0)\n n = np.sqrt(2.0 / (3*4*dim1))\n c_init = tf.random_normal_initializer(stddev = n)\n\n concat_x = tf.concat((x1, x2), 3)\n\n out1 = tf.contrib.layers.conv2d(x2, dim1, [3,3], stride, \n activation_fn=None, weights_initializer=c_init, scope='l1')\n out2 = tf.contrib.layers.conv2d(concat_x, dim2, [3,3], stride, \n activation_fn=None, weights_initializer=c_init, scope='l2')\n return out1, out2\n\n def lv3conv(self, x1, x2, x3, dim1, dim2, dim3, stride, scope):\n with tf.variable_scope(scope):\n if not self.is_training:\n tf.get_variable_scope().reuse_variables()\n #n = np.sqrt(6/(4 * 4 * (int(x1.shape[3]) + dim1)))\n #n = np.sqrt(6 / (3 * 3 * int(x1.shape[3] + x2.shape[3]) * (dim1 + dim2)))\n #c_init = tf.random_uniform_initializer(-n, n)\n #c_init = tf.contrib.layers.xavier_initializer()\n #c_init = tf.truncated_normal_initializer(stddev=5e-2)\n #b_init = tf.constant_initializer(0.0)\n n = np.sqrt(2.0 / (3*4*dim1))\n c_init = tf.random_normal_initializer(stddev = n)\n\n concat_x3 = tf.concat((x1, x2, x3), 3)\n\n out1 = tf.contrib.layers.conv2d(x3, dim1, [3,3], stride, activation_fn=None, \n weights_initializer=c_init, scope='l1')\n out2 = tf.contrib.layers.conv2d(x3, dim2, [3,3], stride, \n activation_fn=None, weights_initializer=c_init, scope='l2')\n out3 = tf.contrib.layers.conv2d(concat_x3, dim3, [3,3], stride, \n activation_fn=None, weights_initializer=c_init, scope='l3')\n return out1, out2, out3\n\n def fc(self, x, dim, scope):\n with tf.variable_scope(scope):\n if not self.is_training:\n tf.get_variable_scope().reuse_variables()\n #f_init = tf.truncated_normal_initializer(stddev=5e-2)\n #f_init = tf.contrib.layers.xavier_initializer()\n #f_init = tf.uniform_unit_scaling_initializer(factor=1.0)\n f_init = tf.variance_scaling_initializer(scale=1.0, distribution='uniform')\n b_init = tf.constant_initializer(0.0)\n return tf.contrib.layers.fully_connected(x, dim, activation_fn=None,\n weights_initializer=f_init, biases_initializer=b_init)\n\n def layers_shortcut(self, l_list):\n out = []\n for l in l_list:\n out.append(self.shortcut(l))\n return out\n\n def shortcut(self, x):\n input_c = x.shape[3]\n pool = tf.nn.avg_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='VALID')\n return tf.pad(pool, [[0,0], [0,0], [0,0], [input_c//2, input_c//2]])\n\n def layers_batch_norm(self, l_list, scope):\n out = []\n for i in range(len(l_list)):\n out.append(self.batch_norm(l_list[i], scope+str(i)))\n return out\n\n def batch_norm(self, input_layer, scope):\n BN_DECAY = 0.999 #0.9\n BN_EPSILON = 1e-5 #1e-3\n dimension = int(input_layer.shape[3])\n with tf.variable_scope(scope): \n if not self.is_training:\n tf.get_variable_scope().reuse_variables()\n mean, variance = tf.nn.moments(input_layer, axes=[0, 1, 2])\n beta = tf.get_variable('beta', dimension, tf.float32,\n initializer=tf.constant_initializer(0.0, tf.float32))\n gamma = tf.get_variable('gamma', dimension, tf.float32,\n initializer=tf.constant_initializer(1.0, tf.float32))\n bn_layer = tf.nn.batch_normalization(input_layer, mean, variance, beta, gamma, BN_EPSILON)\n '''\n mu = tf.get_variable('mu', dimension, tf.float32,\n initializer=tf.constant_initializer(0.0, tf.float32),\n trainable=False)\n sigma = tf.get_variable('sigma', dimension, tf.float32,\n initializer=tf.constant_initializer(1.0, tf.float32),\n trainable=False)\n \n if self.is_training is True:\n mean, variance = tf.nn.moments(input_layer, axes=[0, 1, 2])\n train_mean = tf.assign(mu, mu*BN_DECAY + mean*(1-BN_DECAY))\n train_var = tf.assign(sigma, sigma*BN_DECAY + variance*(1 - BN_DECAY))\n \n with tf.control_dependencies([train_mean, train_var]):\n return tf.nn.batch_normalization(input_layer, mean, variance, beta, gamma, BN_EPSILON )\n else:\n bn_layer = tf.nn.batch_normalization(input_layer, mu, sigma, beta, gamma, BN_EPSILON)\n '''\n \n return bn_layer\n\n def layers_relu(self, l_list):\n out = []\n for l in l_list:\n out.append(self.relu(l))\n return out\n\n def relu(self, x):\n leakiness = 0.1\n return tf.where(tf.less(x, 0.0), leakiness*x, x, name='leaky_relu')\n\n def l2loss(self, var_list):\n regul = tf.nn.l2_loss(var_list[0])\n for v in var_list[1:]:\n regul += tf.nn.l2_loss(v)\n return regul\n\n def relu_global_pool(self, l_list):\n out = []\n for l in l_list:\n out.append(tf.reduce_mean(self.relu(l), [1,2]))\n return out\n","sub_path":"basemodel/sparseresnet.py","file_name":"sparseresnet.py","file_ext":"py","file_size_in_byte":16761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"443502111","text":"from __future__ import annotations\n\nfrom typing import Any\n\nfrom checkov.common.util.type_forcers import force_int\nfrom checkov.common.models.enums import CheckCategories, CheckResult\nfrom checkov.terraform.checks.resource.base_resource_value_check import BaseResourceCheck\n\n\nclass BranchProtectionReviewNumTwo(BaseResourceCheck):\n def __init__(self) -> None:\n name = \"Ensure at least two approving reviews for PRs\"\n id = \"CKV_GIT_5\"\n supported_resources = [\"github_branch_protection_v3\", \"github_branch_protection\"]\n categories = [CheckCategories.GENERAL_SECURITY]\n super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources)\n\n def scan_resource_conf(self, conf: dict[str, list[Any]]) -> CheckResult:\n if conf.get(\"required_pull_request_reviews\") and isinstance(conf.get(\"required_pull_request_reviews\"), list):\n review = conf.get(\"required_pull_request_reviews\")[0]\n if review.get(\"required_approving_review_count\") and isinstance(review.get(\"required_approving_review_count\"),list):\n count = force_int(review.get(\"required_approving_review_count\")[0])\n if count and count >= 2:\n return CheckResult.PASSED\n self.evaluated_keys = [\"required_pull_request_reviews/[0]/required_approving_review_count\"]\n return CheckResult.FAILED\n\n\ncheck = BranchProtectionReviewNumTwo()\n","sub_path":"checkov/terraform/checks/resource/github/BranchProtectionReviewNumTwo.py","file_name":"BranchProtectionReviewNumTwo.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"13185442","text":"import random\nimport string\nimport time\nfrom datetime import date, timedelta\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.select import Select\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom datetime import datetime\n\n\nclass Input_RESI_SFR:\n\n def __init__(self, app):\n self.app = app\n self.id_of_listing = None\n self.price = None\n self.today = None\n self.list_agent = None\n self.login = None\n self.wait = WebDriverWait(self.app.wd, 10)\n\n def start_listing_tab(self):\n wd = self.app.wd\n\n property_subtype = Select(wd.find_element(By.ID, \"Input_171\"))\n property_subtype.select_by_visible_text('Single Family Residence')\n\n structure_type = wd.find_element(By.CSS_SELECTOR, \"option[value='HOUZ']\")\n structure_type.click()\n\n association = Select(wd.find_element(By.ID, \"Input_177\"))\n association.select_by_index(2)\n\n restrictions = Select(wd.find_element(By.ID, \"Input_178\"))\n restrictions.select_by_index(2)\n\n tax_legal_description = wd.find_element(By.ID, \"Input_174\")\n tax_legal_description.send_keys(\"Tax Legal Description tests text\")\n\n def status_tab(self):\n wd = self.app.wd\n\n # status_btn = wd.find_element(By.ID, \"m_rpPageList_ctl02_lbPageLink\")\n status_btn = wd.find_element(By.XPATH, \"//a[normalize-space()='Status']\")\n status_btn.click()\n\n status_fld = Select(wd.find_element(By.ID, \"Input_182\"))\n status_fld.select_by_visible_text(\"Active\")\n\n def listing_tab(self):\n wd = self.app.wd\n\n listing_btn = wd.find_element(By.XPATH, \"//a[normalize-space()='Listing']\")\n listing_btn.click()\n\n self.list_agent = self.login\n agent_id = wd.find_element(By.ID, \"Input_146_displayValue\")\n agent_id.send_keys(self.list_agent)\n\n self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, \"div[class='TBXFilter']\")))\n wd.find_element(By.CSS_SELECTOR, \"div[class='TBXFilter']\").click()\n\n confirm_btn = wd.find_element(By.CSS_SELECTOR, \"a[href*=Input_146_Refresh]\")\n confirm_btn.click()\n\n expiration_date = wd.find_element(By.ID, \"Input_181\")\n self.today = date.today()\n expiration_date_value = self.today + +timedelta(random.randint(1, 14))\n expiration_date.send_keys(expiration_date_value.strftime(\"%m/%d/%y\"))\n\n price_type = Select(wd.find_element(By.ID, \"Input_184\"))\n price_type.select_by_index(2)\n\n price_element = wd.find_element_by_id(\"Input_185\")\n price_verification_element = wd.find_element_by_id(\"Input_1241\")\n self.price = random.randint(150000, 5000000)\n price_element.send_keys(self.price)\n price_verification_element.send_keys(self.price)\n\n ownership = Select(wd.find_element(By.ID, \"Input_186\"))\n ownership.select_by_index(7)\n\n wd.execute_script(\"window.scrollTo(0, 400)\")\n\n listing_terms_list = wd.find_elements_by_css_selector(\"[name='Input_188']\")\n listing_terms_list[random.randrange(len(listing_terms_list))].click()\n\n special_listing_conditions = wd.find_elements_by_css_selector(\"[name='Input_189']\")\n special_listing_conditions[random.randrange(len(special_listing_conditions))].click()\n\n wd.execute_script(\"window.scrollTo(0, 300)\")\n\n buyer_agency_compensation = wd.find_element_by_id(\"Input_206\")\n buyer_agency_compensation.send_keys(random.randint(1, 100))\n buyer_agency_compensation_type = Select(wd.find_element(By.ID, \"Input_207\"))\n buyer_agency_compensation_type.select_by_index(2)\n\n transaction_broker_compensation = wd.find_element_by_id(\"Input_1189\")\n transaction_broker_compensation.send_keys(random.randint(1, 100))\n transaction_broker_compensation_type = Select(wd.find_element(By.ID, \"Input_1190\"))\n transaction_broker_compensation_type.select_by_index(2)\n\n dual_variable_compensation = Select(wd.find_element(By.ID, \"Input_208\"))\n dual_variable_compensation.select_by_index(2)\n\n submitted_prospect = Select(wd.find_element(By.ID, \"Input_209\"))\n submitted_prospect.select_by_index(2)\n\n def marketing_tab(self):\n wd = self.app.wd\n marketing_btn = wd.find_element(By.XPATH, \"//a[normalize-space()='Marketing']\")\n marketing_btn.click()\n\n internet_entire_listing_display = Select(wd.find_element(By.ID, \"Input_198\"))\n internet_entire_listing_display.select_by_index(2)\n\n wd.execute_script(\"window.scrollTo(0, 200)\")\n\n confirm_syndication_choices = wd.find_element_by_id(\"Input_202\")\n confirm_syndication_choices.click()\n\n def location_tab(self):\n wd = self.app.wd\n location_btn = wd.find_element(By.XPATH, \"//a[normalize-space()='Location']\")\n location_btn.click()\n # County\n all_counties = wd.find_elements_by_xpath(\"//select[@id='Input_221']//option\")\n number_of_county = random.randint(1, len(all_counties) - 1)\n county = Select(wd.find_element(By.ID, \"Input_221\"))\n county.select_by_index(number_of_county)\n # Street\n street = wd.find_element_by_id(\"Input_222\")\n street.send_keys(random.randint(1, 99999))\n # Street name\n street_name = wd.find_element_by_id(\"Input_224\")\n street_name_val = ''.join(random.choice(string.ascii_letters + \" \" * 15) for f in range(20))\n street_name.send_keys(street_name_val)\n # City\n city = wd.find_element_by_id(\"Input_227_TB\")\n city.send_keys(\"Denver\")\n wd.find_element_by_id(\"Input_227_TB\").send_keys(Keys.ENTER)\n # ZIP Code\n zip_code = wd.find_element_by_id(\"Input_228\")\n zip_code.send_keys(random.randint(80000, 89999))\n # Parcel Number\n parcel_number = wd.find_element_by_id(\"Input_173\")\n parcel_number.send_keys(random.randint(100000, 999999))\n # Tax Annual Amount\n tax_annual_amount = wd.find_element_by_id(\"Input_231\")\n tax_annual_amount.send_keys(random.randint(500, 6500))\n # Tax Year\n tax_year = wd.find_element_by_id(\"Input_232\")\n tax_year.send_keys(random.randint(2000, 2020))\n # Subdivision Name\n subdivision_name = wd.find_element_by_id(\"Input_250\")\n subdivision_name.send_keys(\n str(random.randint(2000, 2020)) + \" \" + ''.join(\n random.choice(string.ascii_letters + \" \" * 15) for i in range(20)))\n # Latitude\n latitude = wd.find_element_by_id(\"INPUT__146\")\n latitude.send_keys(str(random.uniform(36.993045, 45.001320))[0:9])\n # Longitude\n longitude = wd.find_element_by_id(\"INPUT__168\")\n longitude.send_keys(str(random.uniform(-111.055198, -102.042131))[0:11])\n # School District\n school_district = wd.find_element_by_id('Input_397_TB')\n school_district.send_keys(\"Akron\")\n school_district.send_keys(Keys.ENTER)\n # Elementary School\n el_school = wd.find_element_by_id('Input_252_TB')\n el_school.send_keys(\"Akron\")\n el_school.send_keys(Keys.ENTER)\n # Middle Or Junior School\n mid_school = wd.find_element_by_id('Input_253_TB')\n mid_school.send_keys(\"Akron\")\n mid_school.send_keys(Keys.ENTER)\n # High School\n high_school = wd.find_element_by_id('Input_254_TB')\n high_school.send_keys(\"Akron\")\n high_school.send_keys(Keys.ENTER)\n\n def building_tab(self):\n wd = self.app.wd\n\n # TODO Different names of the tab...\n building_btn = wd.find_element_by_id('m_rpPageList_ctl08_lbPageLink')\n building_btn.click()\n\n year_built = wd.find_element_by_id(\"Input_258\")\n year_built.send_keys(random.randint(1950, 2020))\n\n levels = wd.find_element_by_css_selector(\"[value='ONE']\")\n levels.click()\n\n cons_materials = wd.find_element_by_id(\"Input_260_ADOB\")\n cons_materials.click()\n\n wd.execute_script(\"window.scrollTo(0, 300)\")\n\n roof = wd.find_elements_by_css_selector(\"[name='Input_266']\")\n roof[random.randint(1, 8)].click()\n\n lot_size_area = wd.find_element_by_id(\"Input_1218\")\n lot_size_area.send_keys(str(random.uniform(0.01, 9.99))[0:4])\n\n lot_size_measurement = Select(wd.find_element(By.ID, \"Input_1219\"))\n lot_size_measurement.select_by_index(1)\n\n # Scroll down\n wd.execute_script(\"window.scrollTo(0, 1000)\")\n\n water_included = Select(wd.find_element_by_id(\"Input_398\"))\n water_included.select_by_index(2)\n\n def parking_tab(self):\n wd = self.app.wd\n parking_btn = wd.find_element_by_id(\"m_rpPageList_ctl12_lbPageLink\")\n parking_btn.click()\n\n paring_type = Select(wd.find_element_by_id(\"_Input_323__REPEAT0_302\"))\n paring_type.select_by_index(2)\n\n of_spaces = wd.find_element_by_id(\"_Input_323__REPEAT0_303\")\n of_spaces.send_keys(random.randint(1, 10))\n\n def interior_tab(self):\n wd = self.app.wd\n interior_btn = wd.find_element_by_id(\"m_rpPageList_ctl14_lbPageLink\")\n interior_btn.click()\n\n above_grade = wd.find_element_by_id(\"Input_332\")\n above_grade.send_keys(random.randint(500, 2500))\n\n living_area = wd.find_element_by_id(\"Input_334\")\n living_area.send_keys(random.randint(2500, 3500))\n\n area_total = wd.find_element_by_id(\"Input_333\")\n area_total.send_keys(random.randint(4500, 6000))\n\n basement = Select(wd.find_element_by_id(\"Input_176\"))\n basement.select_by_index(2)\n\n wd.execute_script(\"window.scrollTo(0, 300)\")\n\n room_type = Select(wd.find_element_by_id(\"_Input_1115__REPEAT0_336\"))\n room_type.select_by_index(2)\n\n room_level = Select(wd.find_element_by_id(\"_Input_1115__REPEAT0_337\"))\n room_level.select_by_index(2)\n\n # Scroll down\n # wd.execute_script(\"window.scrollTo(0, 300)\")\n # time.sleep(1)\n # heating = wd.find_element_by_id(\"Input_347_ASLR\")\n # heating.click()\n\n try:\n wd.execute_script(\"window.scrollTo(0, 300)\")\n time.sleep(1)\n heating = wd.find_element_by_id(\"Input_347_ASLR\")\n heating.click()\n except Exception as e:\n print(e)\n now = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n wd.get_screenshot_as_file('screenshot-%s.png' % now)\n\n cooling = wd.find_element_by_id(\"Input_348_ACRM\")\n cooling.click()\n\n def remarks_tab(self):\n wd = self.app.wd\n remarks_btn = wd.find_element_by_id(\"m_rpPageList_ctl16_lbPageLink\")\n remarks_btn.click()\n\n exclusions = wd.find_element_by_id(\"Input_390\")\n exclusions.send_keys(''.join(random.choice(string.ascii_letters) for i in range(20)))\n\n contract_earnest = wd.find_element_by_id(\"Input_393\")\n contract_earnest.send_keys(''.join(random.choice(string.ascii_letters) for i in range(20)))\n\n def submit_listing(self):\n wd = self.app.wd\n submit = wd.find_element_by_link_text(\"Submit Property\")\n submit.click()\n listing_id = wd.find_element_by_id(\"m_lbLinkToFull\")\n self.id_of_listing = listing_id.text\n print()\n print(\"LISTING ID: \" + str(self.id_of_listing))\n\n def change_status_to_pending(self):\n wd = self.app.wd\n\n wd.get(\"http://reco.matrixstaging.com/Matrix/Input\")\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_tbQuickEditCommonID_m_txbInternalTextBox\").send_keys(\n self.id_of_listing)\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_lbQuickEdit\").click()\n wd.find_element_by_link_text(\"Change to Pending\").click()\n\n Select(wd.find_element(By.ID, \"Input_704\")).select_by_index(random.randint(1, 9))\n wd.find_element(By.ID, \"Input_94\").send_keys(str(date.today().strftime(\"%m/%d/%y\")))\n wd.find_element(By.ID, \"m_lbSubmit\").click()\n\n def change_status_to_withdrawn(self):\n wd = self.app.wd\n\n wd.get(\"http://reco.matrixstaging.com/Matrix/Input\")\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_tbQuickEditCommonID_m_txbInternalTextBox\").send_keys(\n self.id_of_listing)\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_lbQuickEdit\").click()\n wd.find_element(By.LINK_TEXT, \"Change to Withdrawn\").click()\n wd.find_element(By.ID, \"m_lbSubmit\").click()\n\n def change_status_to_expired(self):\n wd = self.app.wd\n\n wd.get(\"http://reco.matrixstaging.com/Matrix/Input\")\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_tbQuickEditCommonID_m_txbInternalTextBox\").send_keys(\n self.id_of_listing)\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_lbQuickEdit\").click()\n\n wd.find_element(By.LINK_TEXT, \"Change to Expired\").click()\n wd.find_element(By.ID, \"m_lbSubmit\").click()\n\n def change_status_to_closed(self):\n wd = self.app.wd\n\n wd.get(\"http://reco.matrixstaging.com/Matrix/Input\")\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_tbQuickEditCommonID_m_txbInternalTextBox\").send_keys(\n self.id_of_listing)\n wd.find_element(By.ID, \"m_lvInputUISections_ctrl0_lbQuickEdit\").click()\n\n wd.find_element(By.LINK_TEXT, \"Change to Closed\").click()\n\n close_price = wd.find_element_by_id('Input_84')\n close_price_verification = wd.find_element_by_id('Input_1254')\n\n close_price.send_keys(self.price)\n close_price_verification.send_keys(self.price)\n\n commission_modified = Select(wd.find_element_by_id(\"Input_714\"))\n commission_modified.select_by_index(3)\n\n buyer_financing = wd.find_elements_by_css_selector(\"[name='Input_715']\")\n buyer_financing[random.randrange(len(buyer_financing))].click()\n\n close_date_el = wd.find_element_by_id(\"Input_85\")\n close_date_el.send_keys(self.today.strftime(\"%m/%d/%y\"))\n\n buyer_mls_id = wd.find_element_by_id('Input_141_displayValue')\n buyer_mls_id.send_keys(self.list_agent)\n time.sleep(2)\n buyer_mls_id.send_keys(Keys.ENTER)\n\n concessions = Select(wd.find_element_by_id(\"Input_717\"))\n concessions.select_by_index(3)\n\n concessions_amount = wd.find_element_by_id('Input_718')\n concessions_amount.send_keys(random.randint(100, 5000))\n\n closing_comments = wd.find_element_by_id('Input_719')\n closing_comments.send_keys(\"test_test\")\n\n wd.find_element(By.ID, \"m_lbSubmit\").click()\n\n def create_active(self):\n self.start_listing_tab()\n self.status_tab()\n self.listing_tab()\n self.marketing_tab()\n self.location_tab()\n self.building_tab()\n self.parking_tab()\n self.interior_tab()\n self.remarks_tab()\n self.submit_listing()\n\n def create_pending(self):\n self.create_active()\n self.change_status_to_pending()\n\n def create_withdrawn(self):\n self.create_active()\n self.change_status_to_withdrawn()\n\n def create_closed(self):\n self.create_active()\n self.change_status_to_pending()\n self.change_status_to_closed()\n\n def create_expired(self):\n self.create_active()\n self.change_status_to_expired()\n\n def populate_input_form(self, mls_status, login):\n\n self.login = login\n\n if mls_status == 'active':\n self.create_active()\n elif mls_status == 'pending':\n self.create_pending()\n elif mls_status == 'withdrawn':\n self.create_withdrawn()\n elif mls_status == 'expired':\n self.create_expired()\n elif mls_status == 'closed':\n self.create_closed()\n else:\n print(\"Not ready\")\n","sub_path":"page_methods/Matrix/input/input_resi_sfr_methods.py","file_name":"input_resi_sfr_methods.py","file_ext":"py","file_size_in_byte":15930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"535296762","text":"class Node:\n def __init__(self, key, value):\n self.item = (key, value)\n self.next = None\n\nclass MyHashMap:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.size = 0\n self.capacity = 3000\n self.data = [None] * self.capacity\n \n\n def put(self, key: int, value: int) -> None:\n \"\"\"\n value will always be non-negative.\n \"\"\"\n index = hash(key) % self.capacity\n if self.data[index] == None:\n self.data[index] = Node(key, value)\n self.size += 1\n else:\n pointer = self.data[index]\n while pointer:\n if pointer.item[0] == key:\n pointer.item = (key, value)\n return\n if not pointer.next: break\n pointer = pointer.next \n pointer.next = Node(key, value)\n self.size += 1\n\n def get(self, key: int) -> int:\n \"\"\"\n Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key\n \"\"\"\n index = hash(key) % self.capacity \n pointer = self.data[index]\n while pointer:\n if pointer.item[0] == key:\n return pointer.item[1]\n pointer = pointer.next\n return -1\n\n def remove(self, key: int) -> None:\n \"\"\"\n Removes the mapping of the specified value key if this map contains a mapping for the key\n \"\"\"\n index = hash(key) % self.capacity\n if self.data[index] == None:\n return\n \n pointer = prev = self.data[index]\n if pointer.item[0] == key:\n self.data[index] = pointer.next\n self.size -= 1\n else:\n pointer = pointer.next\n while pointer:\n if pointer.item[0] == key:\n prev.next = pointer.next\n self.size -= 1\n return\n prev = pointer\n pointer = pointer.next\n \n# Your MyHashMap object will be instantiated and called as such:\n# obj = MyHashMap()\n# obj.put(key,value)\n# param_2 = obj.get(key)\n# obj.remove(key)","sub_path":"week-2/hashmaps-hashsets/DesignHashmap.py","file_name":"DesignHashmap.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"553787063","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 18 10:51:09 2017\n\n@author: liming\n\nThis model imatates the google cifar10 codes\nwww.github.com/tensorflow/models/blob/master/tutorials/image/cifar10/cifar10.py\n\"\"\"\n\n#%%\n\nimport tensorflow as tf\n\n#%%\n\ndef inference(images, batch_size, n_classes):\n ''' build the model\n Args:\n images: one batch of images, 4D tensor, tf.float32, \n [batch_size, width, height, channels]\n batch_size: how many images in one batch\n Returns:\n output tensor with the computed logits, float, [batch_size, n_classes]\n '''\n\n # conv1\n # shape = [kernel size, kernel size, channels, kernel numbers]\n with tf.variable_scope('conv1') as scope:\n weights = tf.get_variable('weights',\n shape = [3,3,1,32],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(stddev = 0.1, dtype = tf.float32))\n biases = tf.get_variable('biases',\n shape = [32],\n dtype = tf.float32,\n initializer = tf.constant_initializer(0.1))\n conv = tf.nn.conv2d(images, weights, strides = [1,1,1,1], padding = 'SAME')\n pre_activation = tf.nn.bias_add(conv, biases)\n \n conv1 = tf.nn.relu(pre_activation, name = scope.name)\n \n # pool1 and norm1 \n with tf.variable_scope('pooling_norm1') as scope:\n pool1 = tf.nn.max_pool(conv1, ksize = [1,2,2,1], strides = [1,2,2,1],\n padding = 'SAME', name = 'pooling1')\n norm1 = tf.nn.lrn(pool1, depth_radius = 4, bias = 1.0, \n alpha = 0.001/9.0, beta = 0.75, name = 'norm1')\n \n # conv2\n with tf.variable_scope('conv2') as scope:\n weights = tf.get_variable('weights',\n shape = [3,3,32,32],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(stddev = 0.1, dtype = tf.float32))\n \n biases = tf.get_variable('biases',\n shape = [32],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(0.1))\n conv = tf.nn.conv2d(norm1, weights, strides = [1,1,1,1], padding = 'SAME')\n conv = tf.nn.bias_add(conv, biases)\n conv2 = tf.nn.relu(conv, name = scope.name)\n \n # pool2 and norm2\n with tf.variable_scope('pooling_norm2') as scope:\n norm2 = tf.nn.lrn(conv2, depth_radius = 4, bias = 1.0, alpha = 0.001/9.0,\n beta = 0.75, name = 'norm2')\n pool2 = tf.nn.max_pool(norm2, ksize = [1,2,2,1], strides = [1,1,1,1],\n padding = 'SAME', name = 'pooling2')\n \n # local3\n with tf.variable_scope('local3') as scope:\n reshape = tf.reshape(pool2, shape = [batch_size, -1])\n dim = reshape.get_shape()[1].value\n weights = tf.get_variable('weights',\n shape = [dim, 128],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(stddev = 0.005, dtype = tf.float32))\n biases = tf.get_variable('biases',\n shape = [128],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(0.1))\n local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name = scope.name)\n \n # local4\n with tf.variable_scope('local4') as scope:\n weights = tf.get_variable('weights',\n shape = [128, 128],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(stddev = 0.005, dtype = tf.float32))\n biases = tf.get_variable('biases',\n shape = [128],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(0.1))\n local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name = scope.name)\n \n # softmax\n with tf.variable_scope('softmax_linear') as scope:\n weights = tf.get_variable('weights',\n shape = [128, n_classes],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(stddev = 0.005, dtype = tf.float32))\n biases = tf.get_variable('biases',\n shape = [n_classes],\n dtype = tf.float32,\n initializer = tf.truncated_normal_initializer(0.1))\n softmax_linear = tf.add(tf.matmul(local4,weights), biases, name = 'softmax_linear')\n \n \n return softmax_linear\n\ndef losses(logits, labels):\n ''' Compute loss from logits and labels\n Args:\n logits: logits tensor, float, [batch_size, n_classes]\n labels: label tensor, tf.int32, [batch_size]\n Returns:\n loss tensor of float type\n '''\n \n with tf.variable_scope('loss') as scope:\n # do not need one hot encoding if use the sparse softmax\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = logits,\n labels = labels,\n name = 'xentropy_per_example')\n loss = tf.reduce_mean(cross_entropy, name = 'loss')\n # show in tensor board\n tf.summary.scalar(scope.name + '/loss', loss)\n \n return loss\n\ndef training(loss, learning_rate):\n '''\n Args:\n loss: loss tensor, from losses()\n \n Returns:\n train_op: the op for training\n '''\n with tf.name_scope('optimizer'):\n optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate)\n global_step = tf.Variable(0, name = 'global_step', trainable = False)\n train_op = optimizer.minimize(loss, global_step = global_step)\n \n return train_op\n \n \ndef evaluation(logits, labels):\n '''\n Args:\n logits: Logits tensor, float [batch_size, n_classes]\n labels: Labels tensor, int32 [batch_size], with value in the range [0, n_classes]\n Returns:\n A scalar int32 tensor with the number of example (out of batch_size) that\n were predicted correctly\n '''\n with tf.variable_scope('accuracy') as scope:\n # 1 means use the largest number of prediction\n # e.g. the probability of 1 is 0.7, the probability of 0 is 0.3\n # choose 1, compare with label\n correct = tf.nn.in_top_k(logits, labels, 1)\n correct = tf.cast(correct, tf.float16)\n accuracy = tf.reduce_mean(correct)\n tf.summary.scalar(scope.name + '/accuracy', accuracy)\n \n return accuracy\n","sub_path":"PKLot/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"89120678","text":"# !/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Time : 2018/11/12 23:47\n# @Author : zhushaoxin\n# @Email : 185250613@qq.com\n# @File : XlsEngine.py\n\n\n\nimport xlrd\nimport xlwt\n\nclass XlsEngine_rd():\n\n def __init__(self, filename):\n self.xls_name = filename\n self.xlrd_object = None\n self.xlwt_object = None\n self.isopenfailed = True\n\n def xlrd_open(self):\n try:\n #xlrd.Book.encoding=\"utf-8\"\n self.xlrd_object = xlrd.open_workbook(self.xls_name)\n self.isopenfailed = False\n except Exception as e:\n self.isopenfailed = True\n self.xlrd_object = None\n print(e)\n return [self.isopenfailed, self.xlrd_object]","sub_path":"src/interfacetest/iutil/XlsEngine.py","file_name":"XlsEngine.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"249061432","text":"class Solution(object):\n def findTargetSumWays(self, nums, S):\n \"\"\"\n :type nums: List[int]\n :type S: int\n :rtype: int\n \"\"\"\n # find a + set P and - set N such that \n # sum(P) - sum(N) = S\n # 2*sum(P) = S + sum(nums)\n # thus find a subset P such that its sum is (S+sum(nums)) / 2\n def helper(nums, target):\n dp = [0 for i in range(target+1)]\n dp[0] = 1\n for num in nums:\n for i in range(target, num-1, -1):\n dp[i] += dp[i-num]\n return dp[target]\n \n \n total = sum(nums)\n if total < S or (S+total) % 2 != 0:\n return 0\n return helper(nums, (S+total) >> 1)\n","sub_path":"python_solutions/494-target-sum.py","file_name":"494-target-sum.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"424021686","text":"\"\"\"\nImplementation of the `Task` class.\n\"\"\"\nfrom copy import deepcopy\nfrom datetime import timedelta\nfrom enum import Enum\nfrom typing import Dict, Optional, Any, Iterator, Tuple, List\n\nfrom .core import Connection\nfrom .common import TimeInterval\nfrom .dataset import Dataset\nfrom .job import Job\nfrom .module import Module\nfrom .process import Process\nfrom .user import User\nfrom .type import ApiType, ApiQuery, ApiQueryOrder\n\n\nclass TaskStatus(Enum):\n SCHEDULED = \"scheduled\"\n RUNNING = \"running\"\n PAUSING = \"pausing\"\n PAUSED = \"paused\"\n COMPLETED = \"completed\"\n TERMINATING = \"terminating\"\n TERMINATED = \"terminated\"\n CANCELED = \"canceled\"\n ERROR = \"error\"\n\n\nclass TaskStage(Enum):\n BEGIN = \"begin\"\n TRAINING = \"training\"\n PREDICTING = \"predicting\"\n EVALUATING = \"evaluating\"\n END = \"end\"\n\n\nclass TaskStageIntervals:\n \"\"\"The TaskStageIntervals class contains information about task stage intervals.\n\n ...\n Attributes:\n -----------\n identifier: str\n A unique identifier of the user (i.e. the username).\n name: str\n The full name of the user.\n status: str\n The current status of the user. Can be 'active' or 'archived'.\n \"\"\"\n\n def __init__(self, input: Dict[str, Any]) -> None:\n self._dict: Dict[str, Any] = deepcopy(input)\n\n @property\n def training(self) -> Optional[TimeInterval]:\n value = self._dict.get(\"training\")\n return TimeInterval(value) if value is not None else None\n\n @property\n def predicting(self) -> Optional[TimeInterval]:\n value = self._dict.get(\"predicting\")\n return TimeInterval(value) if value is not None else None\n\n @property\n def evaluating(self) -> Optional[TimeInterval]:\n value = self._dict.get(\"evaluating\")\n return TimeInterval(value) if value is not None else None\n\n def __iter__(self) -> Iterator[Tuple[str, Any]]:\n for (k, v) in self._dict:\n yield (k, v)\n\n\nclass TaskStageDurations:\n \"\"\"The TaskStageIntervals class contains information about task stage intervals.\n\n ...\n Attributes:\n -----------\n identifier: str\n A unique identifier of the user (i.e. the username).\n name: str\n The full name of the user.\n status: str\n The current status of the user. Can be 'active' or 'archived'.\n \"\"\"\n\n def __init__(self, input: Dict[str, Any]) -> None:\n self._dict: Dict[str, Any] = deepcopy(input)\n\n @property\n def training(self) -> Optional[timedelta]:\n value = self._dict.get(\"training\")\n return timedelta(milliseconds=int(value)) if value is not None else None\n\n @property\n def predicting(self) -> Optional[timedelta]:\n value = self._dict.get(\"predicting\")\n return timedelta(milliseconds=int(value)) if value is not None else None\n\n @property\n def evaluating(self) -> Optional[timedelta]:\n value = self._dict.get(\"evaluating\")\n return timedelta(milliseconds=int(value)) if value is not None else None\n\n def __iter__(self) -> Iterator[Tuple[str, Any]]:\n for (k, v) in self._dict:\n yield (k, v)\n\n\nclass Task(ApiType['Task']):\n \"\"\"The Task class contains information about datasets.\n\n ...\n Attributes:\n -----------\n identifier: str\n A unique identifier of the user (i.e. the username).\n name: str\n The full name of the user.\n status: str\n The current status of the user. Can be 'active' or 'archived'.\n \"\"\"\n\n def __init__(self, input: Dict[str, Any]) -> None:\n if \"id\" not in input:\n raise ValueError(\"Invalid input dictionary: It must contain an 'id' key.\")\n\n super().__init__(input)\n \n @classmethod\n def create_ref(cls, id: str) -> 'Task':\n return Task({\"id\": id})\n\n @property\n def id(self) -> str:\n return self._dict[\"id\"]\n\n @property\n def job(self) -> Optional[Job]:\n value = self._dict.get(\"job\")\n return Job({\"id\": value}) if value is not None else None\n\n @property\n def process(self) -> Optional[Process]:\n value = self._dict.get(\"process\")\n return Process({\"id\": value}) if value is not None else None\n\n @property\n def user(self) -> Optional[User]:\n value = self._dict.get(\"user\")\n return User({\"id\": value}) if value is not None else None\n\n @property\n def dataset(self) -> Optional[Dataset]:\n value = self._dict.get(\"dataset\")\n return Dataset({\"id\": value}) if value is not None else None\n\n @property\n def model(self) -> Optional[Module]:\n value = self._dict.get(\"model\")\n return Module({\"id\": value}) if value is not None else None\n\n @property\n def objective(self) -> Optional[Module]:\n value = self._dict.get(\"objective\")\n return Module({\"id\": value}) if value is not None else None\n\n @property\n def alt_objectives(self) -> Optional[List[Module]]:\n value = self._dict.get(\"alt-objectives\")\n return [Module({\"id\": x}) for x in value] if value is not None else None\n\n @property\n def config(self) -> Optional[str]:\n value = self._dict.get(\"config\")\n return str(value) if value is not None else None\n\n @property\n def quality(self) -> Optional[float]:\n value = self._dict.get(\"quality\")\n return float(value) if value is not None else None\n\n @property\n def quality_train(self) -> Optional[float]:\n value = self._dict.get(\"quality-train\")\n return float(value) if value is not None else None\n\n @property\n def quality_expected(self) -> Optional[float]:\n value = self._dict.get(\"quality-expected\")\n return float(value) if value is not None else None\n\n @property\n def alt_qualities(self) -> Optional[List[float]]:\n value = self._dict.get(\"alt-qualities\")\n return [float(x) for x in value] if value is not None else None\n\n @property\n def status(self) -> Optional[TaskStatus]:\n value = self._updates.get(\"status\") or self._dict.get(\"status\")\n return TaskStatus(value) if value is not None else None\n\n @status.setter\n def status(self, value: Optional[TaskStatus] = None) -> None:\n if value is not None:\n self._updates[\"status\"] = value.value\n else:\n self._updates.pop(\"status\")\n\n @property\n def status_message(self) -> Optional[str]:\n value = self._dict.get(\"status-message\")\n return str(value) if value is not None else None\n\n @property\n def stage(self) -> Optional[TaskStage]:\n value = self._dict.get(\"stage\")\n return TaskStage(value) if value is not None else None\n\n @property\n def stage_times(self) -> Optional[TaskStageIntervals]:\n value = self._dict.get(\"stage-times\")\n return TaskStageIntervals(value) if value is not None else None\n\n @property\n def stage_durations(self) -> Optional[TaskStageDurations]:\n value = self._dict.get(\"stage-durations\")\n return TaskStageDurations(value) if value is not None else None\n\n @property\n def running_duration(self) -> Optional[timedelta]:\n value = self._dict.get(\"running-duration\")\n return timedelta(milliseconds=int(value)) if value is not None else None\n\n def __iter__(self) -> Iterator[Tuple[str, Any]]:\n for (k, v) in self._dict:\n yield (k, v)\n\n def get(self, connection: Connection) -> 'Task':\n url = connection.url(\"tasks/\" + self.id)\n return self._get(connection, url)\n\n def patch(self, connection: Connection) -> 'Task':\n url = connection.url(\"tasks/\" + self.id)\n return self._patch(connection, url)\n \n def get_predictions(self, connection: Connection) -> bytes:\n url = connection.url(\"tasks/\" + self.id + \"/predictions.tar\")\n return self._download(connection, url)\n \n def get_parameters(self, connection: Connection) -> bytes:\n url = connection.url(\"tasks/\" + self.id + \"/parameters.tar\")\n return self._download(connection, url)\n \n def get_image(self, connection: Connection) -> bytes:\n url = connection.url(\"tasks/\" + self.id + \"/image/download\")\n return self._download(connection, url)\n\n\nclass TaskQuery(ApiQuery['Task', 'TaskQuery']):\n\n VALID_SORTING_FIELDS = [\"id\", \"process\", \"job\", \"user\", \"dataset\", \"objective\", \"model\", \"quality\", \"quality-train\", \"quality-expected\", \"creation-time\", \"status\", \"stage\"]\n\n def __init__(self, id: Optional[List[str]] = None, user: Optional[User] = None,\n dataset: Optional[Dataset] = None, model: Optional[Module] = None,\n objective: Optional[Module] = None, alt_objective: Optional[Module] = None,\n process: Optional[Process] = None, job: Optional[Job] = None,\n status: Optional[TaskStatus] = None, stage: Optional[TaskStage] = None, \n order_by: Optional[str] = None, order: Optional[ApiQueryOrder] = None,\n limit: Optional[int] = None, cursor: Optional[str] = None) -> None:\n super().__init__(order_by, order, limit, cursor)\n self.T = Task\n\n if id is not None:\n self._query[\"id\"] = id\n if user is not None:\n self._query[\"user\"] = user.id\n if dataset is not None:\n self._query[\"dataset\"] = dataset.id\n if model is not None:\n self._query[\"model\"] = model.id\n if objective is not None:\n self._query[\"objective\"] = objective.id\n if alt_objective is not None:\n self._query[\"alt-objective\"] = alt_objective.id\n if process is not None:\n self._query[\"process\"] = process.id\n if job is not None:\n self._query[\"job\"] = job.id\n if status is not None:\n self._query[\"status\"] = status.value\n if stage is not None:\n self._query[\"stage\"] = stage.value\n\n def run(self, connection: Connection) -> Tuple[List[Task], Optional['TaskQuery']]:\n url = connection.url(\"tasks\")\n return self._run(connection, url)","sub_path":"client/python/easemlclient/easemlclient/model/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":10066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"240140133","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n\n\"\"\"策略路由自动选路\n1. 使用此功能时,会配置多条相同源地址且相同目的地址的策略路由,这些路由归为同一组,可以有多组。\n2. 每组策略路由,实质上只有优先级最小的那条生效,此处称为首条路由。当开启此功能时,\n 每组有一条为主路由,其他为备用路由,且主路由的优先级值最小,此时主路由也就是首条路由。\n3. 每次遍历,判断主路由是否生效,若生效,确保主路由为首条路由;若失效,判断当前首条路由是否生效,生效则跳过这组;\n 如果首条路由也失效,从备用路由中选择一条有效的路由,与之交换;\n\"\"\"\nimport sys\nimport time\nimport json\nimport psutil\nfrom commands import getstatusoutput\nfrom itertools import groupby\nfrom logging import getLogger\nfrom copy import deepcopy\n\nfrom netaddr import IPNetwork, IPAddress\n\nfrom db.mysql_db import select, select_one, update\nfrom networking.tactics_route import TacticsRoute\nfrom networking.nat64 import exec_cmd\nfrom firedam.nat import set_nat\nfrom utils.logger_init import get_logger\n\n\nget_logger('main', '/usr/local/bluedon/log/best_routing.log')\nget_logger('best_routing', '/usr/local/bluedon/log/best_routing.log')\n\n\ndef proc_snat(route):\n \"\"\"根据策略路由的下一跳,找到对应的snat,修改snat的目标地址为,与下一跳同网段的ip(次ip在网口上)\"\"\"\n iface = route.get('sIfaceName', '')\n jump_id = route['iSourceIPID']\n if iface.startswith('ppp'):\n conver_value = iface\n else:\n next_jump = IPAddress(route['sJumpName'])\n all_networks = []\n for addrs in psutil.net_if_addrs().values():\n all_networks.extend([IPNetwork('{}/{}'.format(i.address, i.netmask))\n for i in addrs if i.family == 2])\n for i in all_networks:\n if next_jump in i.cidr:\n conver_value = i.ip.format()\n break\n update('UPDATE m_tbSnat SET sConverTypeValue=? WHERE sSourceIP=?',\n conver_value, jump_id)\n getLogger('main').info('change snat sSourceIP: %s, sConverTypeValue to %s', jump_id, conver_value)\n set_nat('SNAT', active='reboot')\n\n\ndef get_routes_from_db():\n \"\"\"从数据库获取策略路由\n return:\n raw_routes: 路由数据 {id: data_dict, id: data_dict}\n group_routes: {(目的地址, 源地址): [路由id列表]}\n main_routes: {(目的地址, 源地址): 主路由ID}\n \"\"\"\n\n all_routes = select('SELECT * FROM m_tbstrategyroute WHERE iStatus=1;')\n if not all_routes: return ({}, {}, {})\n raw_routes = {i['id']: i for i in all_routes if i}\n all_routes.sort(key=lambda i: (i['sTargetIPAddr'], i['sSourceIPAddr']))\n group_routes = {}\n main_routes = {}\n for k, v in groupby(all_routes, key=lambda i: (i['sTargetIPAddr'], i['sSourceIPAddr'])):\n v = list(v) # 原始的v是生成器,只能进行一次迭代\n main_routes[k] = sorted(v, key=lambda i: i['RouteModel'], reverse=True)[0]['id'] # RouteModel, 1 为主路由\n group_routes[k] = [i['id'] for i in sorted(v, key=lambda i: i['sPriority']) if i] # 按优先级排序\n return raw_routes, group_routes, main_routes\n\n\ndef check_route_status(route):\n \"\"\"判断当前路由是否有效\n args:\n route: 数据库中一条路由记录\n return:\n 1 --> 有效\n 0 --> 无效\n \"\"\"\n\n iface = route.get('sIfaceName', '')\n addr = route.get('sJumpName', '')\n if iface.startswith('ppp'): # 拨号口的策略路由\n all_ifaces = psutil.net_if_addrs()\n # 拨号口存在,并且获取到了ip,则判定这条路由有效\n if (iface in all_ifaces and\n len([i for i in all_ifaces[iface] if i.family == 2]) >= 1):\n return 1\n return 0\n\n for i in range(1, 4):\n status = getstatusoutput('ping -i 0.2 -I %s -W 1 -c %s %s' % (iface, i, addr))[0]\n if status == 0: break\n getLogger('main').info('ping %s via %s : %s', addr, iface, status)\n return 1 if status == 0 else 0\n\n\ndef swap_route(routes, first, tomove):\n \"\"\"将一条策略路由与首条交换\n args:\n routes: 含有所有路由的一个字典,以路由的id为key\n first: 当前首条路由的id\n tomove: 替换当前首条路由的路由id\n \"\"\"\n # 保存修改优先级之前的数据\n old_first = deepcopy(routes[first])\n old_tomove = deepcopy(routes[tomove])\n # 交换raw_routes中两条策略的优先级\n routes[tomove]['sPriority'], routes[first]['sPriority'] = \\\n routes[first]['sPriority'], routes[tomove]['sPriority']\n # 修改数据库中两条策略的优先级\n update('update m_tbstrategyroute set sPriority=? where id=?',\n routes[first]['sPriority'], routes[first]['id'])\n update('update m_tbstrategyroute set sPriority=? where id=?',\n routes[tomove]['sPriority'], routes[tomove]['id'])\n # 删除旧路由,添加新路由\n TacticsRoute(old_first, 'del').modify()\n TacticsRoute(routes[tomove], 'add').modify()\n TacticsRoute(old_tomove, 'del').modify()\n TacticsRoute(routes[first], 'add').modify()\n proc_snat(routes[tomove]) # 切换snat\n getLogger('main').info('swap route: %s <--> %s', first, tomove)\n\n\ndef best_routing():\n \"\"\"策略路由自动切换主备,主函数\"\"\"\n\n getLogger('main').info('Best Routing start.')\n raw_routes, group_routes, main_routes = get_routes_from_db()\n if len(raw_routes) < 1:\n getLogger('main').info('no routes!!')\n return\n\n while True:\n for source, routes in group_routes.iteritems():\n if len(routes) == 1: continue\n main = main_routes[source]\n if check_route_status(raw_routes[main]) == 1: # 主路由通\n if group_routes[source][0] == main: continue\n swap_route(raw_routes, group_routes[source][0], main) # 将主路由切回首条\n _index = routes.index(main)\n group_routes[source][0], group_routes[source][_index] = \\\n group_routes[source][_index], group_routes[source][0]\n elif check_route_status(raw_routes[routes[0]]) == 1: # 首条通\n continue\n else:\n for i in range(1, len(routes)):\n if check_route_status(raw_routes[routes[i]]) == 1: # 从备选里选一条通的,替换首条\n swap_route(raw_routes, group_routes[source][0], routes[i])\n group_routes[source][0], group_routes[source][i] = \\\n group_routes[source][i], group_routes[source][0]\n break\n time.sleep(5)\n\n\ndef start_best_routing(action):\n status, output = exec_cmd('systemctl status best-routing')\n if status and 'not-found' in output:\n exec_cmd('/usr/bin/cp /usr/local/bluedon/conf/systemctl/best-routing.service /usr/lib/systemd/system')\n exec_cmd('systemctl disable best-routing')\n if str(action) == '1':\n exec_cmd('systemctl start best-routing')\n else:\n exec_cmd('systemctl stop best-routing')\n\n\ndef recover(_type):\n data = select_one('SELECT sValue FROM m_tbconfig WHERE sName=\"AutoSelect\"')\n action = json.loads(data['sValue'])['iTurnOn'] if data else 0\n if _type != 'boot_recover':\n action = 0\n start_best_routing(action)\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n best_routing()\n elif len(sys.argv) == 2:\n recover(_type=sys.argv[1])\n","sub_path":"chuhuo_2.71/bluedon/networking/best_routing.py","file_name":"best_routing.py","file_ext":"py","file_size_in_byte":7608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"545843649","text":"import scrapy\n\nclass PostsSpider(scrapy.Spider):\n # pages = int(input('How many pages of news do you want to scrape: '))\n pages = 999\n if pages >= 1000 or type(pages) != int:\n raise ValueError(\n \"The value you entered is either too big or invalid. Please enter a number that is less than 1000\")\n\n name = \"news\"\n # start_urls = ['https://chicago.suntimes.com/search?page={}&q=gun+violence'.format(i + 701) for i in range(pages)]\n start_urls = ['https://chicago.suntimes.com/search?page={}&q=gun'.format(i + 1) for i in range(pages)]\n\n def parse(self, response):\n for new in response.css('div.c-compact-river'):\n for n in new.css(\"div.c-compact-river__entry\"):\n yield {\n 'section': n.css('ul.c-entry-box--compact__labels li a span::text').get(),\n 'title': n.css('h2.c-entry-box--compact__title a::text').get(),\n 'description': n.css('p.c-entry-box--compact__dek::text').get(),\n 'name': n.css(\n 'div.c-byline span.c-byline-wrapper span.c-byline__item span.c-byline__author-name::text').get(),\n 'created': n.css(\n 'div.c-byline span.c-byline-wrapper span.c-byline__item time.c-byline__item::text').get().strip(),\n 'image-link': n.css(\"div.c-entry-box--compact__image img::attr(src)\").extract()[1]\n }\n","sub_path":"sunscrawl/spiders/posts_spider.py","file_name":"posts_spider.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"53106029","text":"from datetime import datetime\nfrom iso8601 import parse_date\nfrom op_robot_tests.tests_files.service_keywords import get_now\nfrom calendar import monthrange\n\n\ndef newtend_date_picker_index(isodate):\n now = get_now()\n date_str = '01' + str(now.month) + str(now.year)\n first_day_of_month = datetime.strptime(date_str, \"%d%m%Y\")\n mod = first_day_of_month.isoweekday() - 2\n iso_dt = parse_date(isodate)\n # last_day_of_month = monthrange(now.year, now.month)[1]\n # LOGGER.log_message(Message(\"last_day_of_month: {}\".format(last_day_of_month), \"INFO\"))\n if now.day > iso_dt.day:\n mod = monthrange(now.year, now.month)[1] + mod\n return mod + iso_dt.day\n\n\ndef update_data_for_newtend(tender_data):\n tender_data.data.procuringEntity['name'] = u\"openprocurement\"\n return tender_data\n","sub_path":"newtend_service.py","file_name":"newtend_service.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"208025701","text":"# -*- coding: utf-8 -*-\nimport q71\nfrom stemming.porter2 import stem\n\nfilename = 'sentiment.txt'\n\ndef rm_stopword(words):\n not_stopwords = []\n for w in words:\n if not q71.chk_stopword(w):\n not_stopwords.append(w)\n return not_stopwords\n\ndef get_stem(words):\n stem_words = []\n for w in words:\n stem_words.append(stem(w))\n return stem_words\n\ndef main():\n fr = open(filename, 'r')\n for line in fr.readlines():\n line = line.rstrip('\\n')\n label = int(line[:2])\n words = line[3:].split(' ')\n stem_words = get_stem(rm_stopword(words))\n print(\"\\t\".join([str(label)] + stem_words))\n\nif __name__ == '__main__':\n main()\n","sub_path":"q72.py","file_name":"q72.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"148575066","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n\nclass Note(models.Model):\n text = models.CharField(max_length=1000, verbose_name='note text')\n color = models.CharField(default=\"#000000\", max_length=9, verbose_name='note color')\n date = models.DateTimeField('date published')\n owner = models.ForeignKey('auth.User', related_name='notes', on_delete=models.CASCADE)\n\n class Meta:\n ordering = ['-date']\n","sub_path":"server/notes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"191134105","text":"import numpy as np\r\nimport os\r\n\r\n\r\ndef FGcal(path, name):\r\n stasMap = np.load(path)\r\n deletmap = np.copy(stasMap)\r\n for i in range(8468):\r\n for j in range(8468):\r\n if i==j:\r\n deletmap[i,j] = 0\r\n deletmap = deletmap*10000\r\n Flux = np.sum(deletmap, axis=0)\r\n Gush = -(np.sum(deletmap, axis=1))\r\n print(\"Saving%s\"%(name))\r\n np.save(\"FluxOf%s.npy\" % (name,), Flux)\r\n np.save(\"GushOf%s.npy\" % (name,), Gush)\r\n\r\n\r\nrootdir = \"/home/guoxiaobo96/OT/part2/\"\r\nlist1 = os.listdir(rootdir)\r\nfileDir = []\r\nfileNames = []\r\nfor i in range(0,len(list1)):\r\n if list1[i].endswith(\".npy\"):\r\n path = os.path.join(rootdir, list1[i])\r\n fileDir.append(path)\r\n fileNames.append(list1[i])\r\nfor i in range(0,len(fileDir)):\r\n FGcal(fileDir[i], fileNames[i])","sub_path":"OT Calculation in ADHD200/Calculation OT/Codes_Used_in_server_repeated/SumAnalysisP2.py","file_name":"SumAnalysisP2.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"609528331","text":"import abc\nfrom abc import ABC\nfrom enum import Enum\nfrom typing import List, Tuple, Callable\n\nfrom goose.exceptions import PlayerAlreadyExists, GameOver\nfrom goose.game import BaseGame, roll_dice\nfrom goose.parsers import BaseCommandParser\nfrom goose.rules import BasicMoveRule, BridgeMoveRule, GooseMoveRule, Move, \\\n BounceMoveRule, PrankMoveRule\n\n\nclass BaseAddPlayerOutputRenderer(ABC):\n \"\"\"\n Base class for objects that render the output of a add player command\n \"\"\"\n\n @abc.abstractmethod\n def render(self, player: str, player_already_existed: bool) -> str:\n \"\"\"\n\n :param player: player's name\n :param player_already_existed: true if the player already existed\n :return: the output for the user\n \"\"\"\n pass\n\n\nclass AddPlayerOutputRenderer(BaseAddPlayerOutputRenderer):\n def __init__(self, game: BaseGame):\n self._game = game\n\n def render(self, player: str, player_already_existed: bool) -> str:\n if player_already_existed:\n return f'{player}: already existing player'\n return f'players: {\", \".join(self._game.get_players())}'\n\n\nclass BaseMovePlayerOutputRenderer(ABC):\n \"\"\"\n Base class for objects that render the output of a move player command\n \"\"\"\n\n @abc.abstractmethod\n def render(self,\n player: str,\n dice: Tuple[int, ...],\n win: bool,\n moves: List[Move]) -> str:\n \"\"\"\n\n :param player: player's name\n :param dice: the dice rolled\n :param win: if the player has won\n :param moves: list of BaseMoveRule applied\n :return: the output for the user\n \"\"\"\n pass\n\n\nclass MovePlayerOutputRenderer(BaseMovePlayerOutputRenderer):\n def __init__(self, game: BaseGame):\n self._game = game\n self._aliases = {k: v for k, v in\n self._game.get_space_aliases().items() if\n v != 'The Goose'}\n\n def render(self,\n player: str,\n dice: Tuple[int, ...],\n win: bool,\n moves: List[Move]) -> str:\n\n start_pos = moves[0].start_pos\n res = f'{player} rolls {\", \".join([str(d) for d in dice])}. '\n res += f'{player} moves ' \\\n f'from {self._aliases.get(start_pos, start_pos)} to '\n\n for move in moves:\n if isinstance(move.rule_applied, BasicMoveRule):\n # In case of bouncing, move.end_pos is greater than n_spaces\n # (temporarily),we'll print just n_spaces\n end_pos = min(self._game.n_spaces, move.end_pos)\n res += f'{self._aliases.get(end_pos, end_pos)}'\n\n elif isinstance(move.rule_applied, BridgeMoveRule):\n res += f'. {player} jumps to {move.end_pos}'\n\n elif isinstance(move.rule_applied, GooseMoveRule):\n res += f', The Goose. ' \\\n f'{player} moves again and goes to {move.end_pos}'\n\n elif isinstance(move.rule_applied, BounceMoveRule):\n res += f'. {player} bounces! ' \\\n f'{player} returns to {move.end_pos}'\n\n elif isinstance(move.rule_applied, PrankMoveRule):\n res += f'. On {move.start_pos} there is {move.player}, ' \\\n f'who returns to {move.end_pos}'\n if win:\n res += f'. {player} Wins!!'\n return res\n\n\nclass BaseTextUI(ABC):\n \"\"\"\n Base class for objects that implements a textual interfaces\n \"\"\"\n\n @property\n @abc.abstractmethod\n def game(self) -> BaseGame:\n pass\n\n @property\n @abc.abstractmethod\n def parser(self) -> BaseCommandParser:\n pass\n\n @property\n @abc.abstractmethod\n def add_player_renderer(self) -> BaseAddPlayerOutputRenderer:\n pass\n\n @property\n @abc.abstractmethod\n def move_player_renderer(self) -> BaseMovePlayerOutputRenderer:\n pass\n\n @abc.abstractmethod\n def process_command(self, string: str) -> str:\n \"\"\"\n Processes the input command\n :param string: input command\n :return: output for the user\n \"\"\"\n pass\n\n\nclass TextUI(BaseTextUI):\n \"\"\"\n Basic implementation of BaseTextUI\n \"\"\"\n\n class Command(Enum):\n ADD_PLAYER = \"add player\"\n MOVE_PLAYER = \"move\"\n\n UNKNOWN_COMMAND_MSG = 'Error, unknown command'\n\n def __init__(self,\n game: BaseGame,\n parser: BaseCommandParser,\n add_player_renderer: BaseAddPlayerOutputRenderer,\n move_player_renderer: BaseMovePlayerOutputRenderer,\n roll_dice_func: Callable[..., int] = None\n ):\n \"\"\"\n\n :param game: the game\n :param parser: a parser to parse command\n :param add_player_renderer: renderer for add player command\n :param move_player_renderer: renderer for move player command\n :param roll_dice_func: function for rolling dice\n (default goose,game.roll_dice)\n \"\"\"\n self._game = game\n self._parser = parser\n self._init_parser(parser)\n self._add_player_renderer = add_player_renderer\n self._move_player_renderer = move_player_renderer\n self._commands = {\n self.Command.ADD_PLAYER: self._add_player,\n self.Command.MOVE_PLAYER: self._move_player\n }\n self.roll_dice_func = roll_dice_func or roll_dice\n\n @property\n def game(self) -> BaseGame:\n return self._game\n\n @property\n def parser(self) -> BaseCommandParser:\n return self._parser\n\n @property\n def add_player_renderer(self) -> BaseAddPlayerOutputRenderer:\n return self._add_player_renderer\n\n @property\n def move_player_renderer(self) -> BaseMovePlayerOutputRenderer:\n return self._move_player_renderer\n\n @staticmethod\n def _move_player_parse_func(args):\n \"\"\"\n Function used for cast to int argument of move player command\n :param args:\n :return:\n \"\"\"\n return [int(arg) if idx > 0 else arg for\n idx, arg in enumerate(args)]\n\n def _init_parser(self, parser):\n parser.add_command(self.Command.ADD_PLAYER.value)\n parser.add_command(\n self.Command.MOVE_PLAYER.value,\n self._move_player_parse_func\n )\n\n def _add_player(self, player: str) -> str:\n \"\"\"\n Function called for add player command\n :param player: player's name\n :return: output for the user\n \"\"\"\n\n player_existed = False\n try:\n self._game.add_player(player)\n except PlayerAlreadyExists:\n player_existed = True\n return self._add_player_renderer.render(player, player_existed)\n\n def _move_player(self, player: str, *dice: int) -> str:\n \"\"\"\n Function called for the move player command\n :param player: player's name\n :param dice: dice rolled\n :return: output for the user\n \"\"\"\n\n dice = dice or self.roll_dice_func(self._game.n_dice,\n self._game.dice_faces)\n win, moves = self._game.move_player(player, *dice)\n\n return self._move_player_renderer.render(player, dice, win, moves)\n\n def _help(self):\n return f\"\"\"Commands:\n add player {{PLAYER}}\n move {{PLAYER}} [{\", \".join([\"N\" for _ in range(self._game.n_dice)])}]\n with 1 <= N <= {self._game.dice_faces}\n \"\"\"\n\n def process_command(self, string: str) -> str:\n \"\"\"\n Processes a command and return the output\n (or the help in case of error)\n :param string: command and args to execute\n :return: output for the user\n \"\"\"\n\n try:\n command_and_args = self._parser.parse(string)\n if command_and_args is None:\n return f'{self.UNKNOWN_COMMAND_MSG}.\\n{self._help()}'\n\n command, args = command_and_args\n return self._commands[self.Command(command)](*args)\n\n except KeyError:\n return f'{self.UNKNOWN_COMMAND_MSG}.\\n{self._help()}'\n\n except GameOver as ex:\n return f' Game Over: {ex}'\n\n except Exception as ex:\n return f'Error while processing command {string}.\\n{self._help()}'\n\n\ndef create_default_ui(game: BaseGame):\n \"\"\"\n Create the default ui. i.e TextUI\n :param game: a BaseGame\n :return: the ui\n \"\"\"\n from goose.parsers import RegexCommandParser\n parser = RegexCommandParser()\n add_player_renderer = AddPlayerOutputRenderer(game)\n move_player_renderer = MovePlayerOutputRenderer(game)\n return TextUI(game, parser, add_player_renderer, move_player_renderer)\n","sub_path":"goose/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":8761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"87793026","text":"from unittest import TestCase\nfrom mock import Mock, patch\n\nimport sys\nimport tempfile\nimport os\nimport json\nimport requests\nfrom requests.exceptions import RequestException\nfrom ibm_analytics_engine import CloudFoundryAPI, CloudFoundryException\n\n\nclass TestCloudFoundryAPI(TestCase):\n def test_invalid_api_key_file(self):\n try:\n error_class = IOError\n except BaseException:\n error_class = FileNotFoundError\n\n with self.assertRaises(error_class):\n cf = CloudFoundryAPI(api_key_filename='does_not_exist')\n\n def mocked_requests_get(*args, **kwargs):\n if args[0] == 'https://api.ng.bluemix.net/v2/info':\n return MockResponse({\"authorization_endpoint\": \"https://login.ng.bluemix.net/UAALoginServerWAR\"}, 200)\n\n @patch('requests.get', side_effect=mocked_requests_get)\n def test_api_key_file(self, mock_get):\n # delete=True means the file will be deleted on close\n tmp = tempfile.NamedTemporaryFile(delete=True)\n try:\n data = json.dumps({\n \"name\": \"iae-key\",\n \"description\": \"\",\n \"createdAt\": \"2017-11-14T12:30+0000\",\n \"apiKey\": \"\"\n }).encode('utf-8')\n tmp.write(data)\n tmp.flush()\n cf = CloudFoundryAPI(api_key_filename=tmp.name)\n finally:\n tmp.close() # deletes the file\n\nclass MockResponse:\n def __init__(self, json_data, status_code, raise_for_status_flag=False, text_data=''):\n self.json_data = json_data\n self.text = text_data\n self.status_code = status_code\n self.raise_for_status_flag = raise_for_status_flag\n def raise_for_status(self):\n if self.raise_for_status_flag:\n self.text = 'some error occurred'\n raise requests.exceptions.HTTPError()\n else:\n return\n def json(self):\n return self.json_data\n\nclass TestCloudFoundryAPI_Request(TestCase):\n\n def mocked_requests_get(*args, **kwargs):\n if args[0] == 'https://api.ng.bluemix.net/v2/info':\n return MockResponse({\"authorization_endpoint\": \"https://login.ng.bluemix.net/UAALoginServerWAR\"}, 200)\n else:\n return MockResponse(None, None, True, 'text_data')\n\n @patch('requests.get', side_effect=mocked_requests_get)\n def test_request_method(self, mock_get):\n\n cf = CloudFoundryAPI(api_key='abcdef')\n with self.assertRaises(CloudFoundryException):\n cf._request('url', 'get', 'some_data', 'description', create_auth_headers=False)\n\nclass TestCloudFoundryAPI_Auth(TestCase):\n\n def mocked_requests_get(*args, **kwargs):\n if args[0] == 'https://api.ng.bluemix.net/v2/info':\n return MockResponse({\"authorization_endpoint\": \"https://login.ng.bluemix.net/UAALoginServerWAR\"}, 200)\n raise RuntimeError(\"Unhandle GET request: \" + args[0]) \n\n def mocked_requests_post(*args, **kwargs):\n if args[0] == 'https://login.ng.bluemix.net/UAALoginServerWAR/oauth/token':\n return MockResponse(None, None, True)\n raise RuntimeError(\"Unhandle GET request: \" + args[0]) \n\n @patch('requests.get', side_effect=mocked_requests_get)\n @patch('requests.post', side_effect=mocked_requests_post)\n def test_auth(self, mock_get, mock_post):\n\n cf = CloudFoundryAPI(api_key='abcdef')\n with self.assertRaises(RequestException):\n cf.auth()\n\nclass TestCloudFoundryAPI_Oidc(TestCase):\n\n def mocked_requests_get(*args, **kwargs):\n if args[0] == 'https://api.ng.bluemix.net/v2/info':\n return MockResponse({\"authorization_endpoint\": \"https://login.ng.bluemix.net/UAALoginServerWAR\"}, 200)\n raise RuntimeError(\"Unhandle GET request: \" + args[0]) \n\n def mocked_requests_post(*args, **kwargs):\n if args[0] == 'https://login.ng.bluemix.net/UAALoginServerWAR/oauth/token':\n return MockResponse({'access_token': 'aaaaa', 'token_type': 'bearer', 'refresh_token': 'aaaaa', 'expires_in': 1209599}, 200)\n if args[0] == 'https://iam.bluemix.net/identity/token':\n return MockResponse(None, None, True)\n\n raise RuntimeError(\"Unhandle GET request: \" + args[0]) \n\n @patch('requests.get', side_effect=mocked_requests_get)\n @patch('requests.post', side_effect=mocked_requests_post)\n def test_auth(self, mock_get, mock_post):\n\n cf = CloudFoundryAPI(api_key='abcdef')\n with self.assertRaises(RequestException):\n cf.oidc_token()\n","sub_path":"tests/library/cf/client_test.py","file_name":"client_test.py","file_ext":"py","file_size_in_byte":4527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"16805274","text":"#--Imports------------------------------------------------------------------\nimport tkinter as tk\nimport re\nimport random\n#---------------------------------------------------------------------------\n\n#--Initialisations----------------------------------------------------------\nfirst_input = True\n\nfields = 'Verilog Code Location (with filename)', 'Verilog Module Name', 'Destination Folder', 'Clock Delay', 'Time Delay', 'No of Test Cases'\n\ninputfileloc = ''\nmodulename = ''\ndestfolder = ''\n\ninputs = []\ninputs_sizes = []\ninputs_withsizes = []\n\noutputs = []\noutputs_sizes = []\noutputs_withsizes = []\n\ntimedelay = 5\nclockdelay = 5\nnooftestcases = 5\n\nalltestcases = False\n\ntestbenchcode_format = ['`include \"^vtb_modulename^.v\"', 'module ^vtb_modulename^_tb;', '^vtb_inputs^', '^vtb_outputs^', \n\t'initial begin\\n\\t$dumpfile(\"^vtb_modulename^_tb.vcd\");\\n\\t$dumpvars(0, ^vtb_modulename^_tb);\\n\\t^vtb_monitor^\\nend', \n\t'^vtb_modulename^ ^vtb_modulename^_(^vtb_inputsparams^, ^vtb_outputsparams^);', \n\t'^vtb_clkname^\\n', \n\t'initial begin\\n^vtb_inputinit^\\n^vtb_inputchange^\\nend', \n\t'endmodule']\n\nformat_values = [['^vtb_modulename^', ''], ['^vtb_inputs^', ''], ['^vtb_inputsparams^', ''], ['^vtb_outputs^', ''], ['^vtb_outputsparams^', ''], ['^vtb_monitor^', ''], ['^vtb_inputinit^', ''], ['^vtb_inputchange^', ''], \n\t\t\t\t['^vtb_clockdelay^', ''], ['^vtb_clkname^', '']]\n\nclock_inp_names = ['clk', 'clock']\n\n#---------------------------------------------------------------------------\n\n#--Functions----------------------------------------------------------------\n#--1--\ndef makeform(root, fields):\n\tentries = []\n\tfor field in fields:\n\t\trow = tk.Frame(root)\n\t\tlab = tk.Label(row, width=15, text=field, anchor='w')\n\t\tent = tk.Entry(row)\n\t\trow.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)\n\t\tlab.pack(side=tk.LEFT)\n\t\tent.pack(side=tk.RIGHT, expand=tk.YES, fill=tk.X)\n\t\tentries.append((field, ent))\n\treturn entries\n\n#--2--\ndef fetch_inputs(entries):\n\tglobal first_input\n\tinput_json = {}\n\n\tfor entry in entries:\n\t\tfield = entry[0]\n\t\ttext = entry[1].get()\n\t\tif field == \"EnterArrayTypeDataFieldHere\":\n\t\t\ttext = text.split(\",\")\n\t\tinput_json[field] = text\n\tprint(input_json)\n\n\tfirst_input = False\n\n\tglobal inputfileloc\n\tglobal modulename\n\tglobal destfolder\n\tglobal timedelay\n\tglobal clockdelay\n\tglobal nooftestcases\n\tglobal alltestcases\n\n\tif input_json[\"Verilog Code Location (with filename)\"] != '':\n\t\tinputfileloc = input_json[\"Verilog Code Location (with filename)\"]\n\tif input_json[\"Verilog Module Name\"] != '':\n\t\tmodulename = input_json[\"Verilog Module Name\"]\n\tif input_json[\"Destination Folder\"] != '':\n\t\tdestfolder = input_json[\"Destination Folder\"]\n\tif input_json[\"Time Delay\"] != '':\n\t\ttimedelay = int(input_json[\"Time Delay\"])\n\tif input_json[\"Clock Delay\"] != '':\n\t\tclockdelay = int(input_json[\"Clock Delay\"])\n\tif input_json[\"No of Test Cases\"] != '':\n\t\tnooftestcases = int(input_json[\"No of Test Cases\"])\n\telif input_json[\"No of Test Cases\"] == '':\n\t\talltestcases = True\n\n\tInputOutputVerilogParser(filepath=inputfileloc, destfolder=destfolder)\n\n\n#--3--\n\n#--4--\ndef FileContents(filepath):\n\tf = open(filepath, \"r\")\n\treturn f.read()\n\ndef VectorSize(name):\n\tname = name.strip()\n\n\tif re.search('^\\[', name):\n\t\tlval = re.findall('^\\[(.*):', name)[0]\n\t\trval = re.findall('^\\[.*:(.*)\\]', name)[0]\n\t\treturn (abs(int(rval) - int(lval)) + 1)\n\treturn 1\n\ndef ArraySize(name):\n\tname = name.strip()\n\n\tif re.search('^\\[', name):\n\t\tname = re.findall('^\\[.*:.*\\](.*)', name)[0]\n\t\treturn ArraySize(name)\n\t\t# if re.search('\\[', name):\n\t\t# \tname = re.findall('^.+\\[.*:.*\\]', name)[0]\n\t\t# \treturn VectorSize(name)\n\t\t# return 1\n\n\telif re.search('\\[', name):\n\t\tname = re.findall('^.+(\\[.*:.*\\])', name)[0]\n\t\treturn VectorSize(name)\n\treturn 1\n\ndef RemoveVectorArray(name):\n\tname = name.strip()\n\n\tif re.search('^\\[.*:.*\\].*', name):\n\t\tname = re.findall('^\\[.*:.*\\](.*)', name)[0]\n\t\treturn RemoveVectorArray(name)\n\n\telif re.search('\\[', name):\n\t\tname = re.findall('^(.+)(\\[.*:.*\\])', name)[0]\n\t\treturn name.strip()\n\treturn name.strip()\n\n#--5--\ndef InputOutputVerilogParser(filepath, destfolder):\n\tglobal inputs\n\tglobal inputs_withsizes\n\tglobal outputs\n\tglobal outputs_withsizes\n\tglobal inputs_sizes\n\tglobal outputs_sizes\n\tglobal modulename\n\n\tcontents = FileContents(filepath)\n\tcontents = contents.split(\"\\n\")\n\t# print (\"Contents: \", contents)\n\tfor line in contents:\n\t\tprint (\"Line(wos): \", line)\n\t\tline = line.strip()\t\n\t\tprint (\"Line(ws): \", line)\t\t\t\t# C:\\LinuxTerminalDocuments\\COE17B010\\VLSI\\PracticeCourse\\FlipFlops\\Counter\\Sync\\Combined\\UpDownSync.v\n\n\t\tif re.search('module\\s+', line):\n\t\t\tmodulename = re.findall('module\\s+(.*)\\(', line)[0].strip()\n\n\t\tif re.search('input\\s+', line):\n\t\t\tval = re.findall('input\\s+(.*);', line)[0].strip()\n\t\t\tif re.search('^\\[', val) == None:\n\t\t\t\tprint (\"Input: \", val, \" -- \", val.split(\",\"))\n\t\t\t\tinps = val.split(\",\")\n\t\t\t\tinpssize = []\n\t\t\t\ti=0\n\t\t\t\tfor o in inps:\n\t\t\t\t\tinps[i] = o.strip()\n\n\t\t\t\t\tinpssize.append([VectorSize(inps[i]), ArraySize(inps[i])])\n\n\t\t\t\t\ti+=1\n\n\t\t\t\tinputs_withsizes.extend(inps)\n\t\t\t\tinputs_sizes.extend(inpssize)\n\t\t\telse:\n\t\t\t\tvectorprefix = re.findall('^(\\[.*:.*\\]).*', val)[0]\n\t\t\t\tval = re.findall('^\\[.*:.*\\](.*)', val)[0]\n\n\t\t\t\tprint (\"Input: \", val, \" -- \", val.split(\",\"))\n\t\t\t\tinps = val.split(\",\")\n\t\t\t\tinpssize = []\n\t\t\t\ti=0\n\t\t\t\tfor o in inps:\n\t\t\t\t\tinps[i] = vectorprefix + o.strip()\n\n\t\t\t\t\tinpssize.append([VectorSize(inps[i]), ArraySize(inps[i])])\n\n\t\t\t\t\ti+=1\n\n\t\t\t\tinputs_withsizes.extend(inps)\n\t\t\t\tinputs_sizes.extend(inpssize)\n\n\n\t\tif re.search('output\\s+', line):\n\t\t\tval = re.findall('output\\s+(.*);', line)[0].strip()\n\n\t\t\tif re.search('^\\[', val) == None:\n\t\t\t\tprint (\"Output: \", val, \" -- \", val.split(\",\"))\n\t\t\t\touts = val.split(\",\")\n\t\t\t\toutssize = []\n\t\t\t\ti=0\n\t\t\t\tfor o in outs:\n\t\t\t\t\touts[i] = o.strip()\n\n\t\t\t\t\toutssize.append([VectorSize(outs[i]), ArraySize(outs[i])])\n\n\t\t\t\t\ti+=1\n\t\t\t\t\n\t\t\t\toutputs_withsizes.extend(outs)\n\t\t\t\toutputs_sizes.extend(outssize)\n\n\t\t\telse:\n\t\t\t\tvectorprefix = re.findall('^(\\[.*:.*\\]).*', val)[0]\n\t\t\t\tval = re.findall('^\\[.*:.*\\](.*)', val)[0]\n\n\t\t\t\tprint (\"Output: \", val, \" -- \", val.split(\",\"))\n\t\t\t\touts = val.split(\",\")\n\t\t\t\toutssize = []\n\t\t\t\ti=0\n\t\t\t\tfor o in outs:\n\t\t\t\t\touts[i] = vectorprefix + o.strip()\n\n\t\t\t\t\toutssize.append([VectorSize(outs[i]), ArraySize(outs[i])])\n\n\t\t\t\t\ti+=1\n\t\t\t\t\n\t\t\t\toutputs_withsizes.extend(outs)\n\t\t\t\toutputs_sizes.extend(outssize)\n\n\tfor inp in inputs_withsizes:\n\t\tinputs.append(RemoveVectorArray(inp))\n\n\tfor out in outputs_withsizes:\n\t\toutputs.append(RemoveVectorArray(out))\n\n\tprint (\"Inputs with sizes: \", inputs_withsizes)\n\tprint (\"Inputsize: \", inputs_sizes)\n\tprint (\"Outputs with sizes: \", outputs_withsizes)\n\tprint (\"Outputsize: \", outputs_sizes)\n\n\tprint(\"Inputs: \", inputs)\n\tprint(\"Outputs: \", outputs)\n\n\tAssignFormatValues()\n\n\tCreateOutputFile()\n\n#--6--\ndef AssignFormatValues():\n\tglobal format_values\n\tglobal inputs\n\tglobal inputs_withsizes\n\tglobal outputs\n\tglobal outputs_withsizes\n\tglobal inputs_sizes\n\tglobal outputs_sizes\n\tglobal modulename\n\tglobal timedelay\n\tglobal clockdelay\n\tglobal nooftestcases\n\tglobal alltestcases\n\n\tfor f in format_values:\n\t\tif f[0] == '^vtb_modulename^':\n\n\t\t\tf[1] = modulename.strip()\n\n\t\tif f[0] == '^vtb_inputs^':\n\t\t\ts = ''\n\t\t\tfor i in inputs_withsizes:\n\t\t\t\ts = s + 'reg'\n\t\t\t\ts = s + ' '+ i\n\t\t\t\ts = s + ';\\n'\n\n\t\t\tf[1] = s\n\n\t\tif f[0] == '^vtb_outputs^':\n\t\t\ts = ''\n\t\t\tfor i in outputs_withsizes:\n\t\t\t\ts = s + 'wire'\n\t\t\t\ts = s + ' '+ i\n\t\t\t\ts = s + ';\\n'\n\n\t\t\tf[1] = s\n\n\t\tif f[0] == '^vtb_inputsparams^':\n\t\t\ts = ''\n\t\t\tfor i in inputs:\n\t\t\t\ts = s + ', .'+ i + '(' + i + ')'\n\n\t\t\tf[1] = re.findall('^, (.*)', s)[0]\n\n\t\tif f[0] == '^vtb_outputsparams^':\n\t\t\ts = ''\n\t\t\tfor i in outputs:\n\t\t\t\ts = s + ', .'+ i + '(' + i + ')'\n\n\t\t\tf[1] = re.findall('^, (.*)', s)[0]\n\n\t\tif f[0] == '^vtb_monitor^':\n\t\t\ts = '$monitor($time, \": '\n\t\t\tfor i in inputs:\n\t\t\t\ts = s + ', ' + i + ': %b'\n\t\t\tfor i in outputs:\n\t\t\t\ts = s + ', ' + i + ': %b'\n\n\t\t\ts = s + '\"'\n\n\t\t\tfor i in inputs:\n\t\t\t\ts = s + ', ' + i\n\t\t\tfor i in outputs:\n\t\t\t\ts = s + ', ' + i\n\t\t\ts = s + ');'\n\n\t\t\tf[1] = s\n\n\t\tif f[0] == '^vtb_inputinit^':\n\t\t\ts = ''\n\t\t\ti=0\n\t\t\tfor ip in inputs:\n\t\t\t\tsvec = inputs_sizes[i][0]\n\t\t\t\tsarr = inputs_sizes[i][1]\n\t\t\t\tif sarr > 1:\n\t\t\t\t\tfor j in range(sarr):\n\t\t\t\t\t\ts = s + ip + '[' + str(j) + '] = ' + str(svec) + \"'b\"\n\t\t\t\t\t\tfor k in range(svec):\n\t\t\t\t\t\t\ts = s + '0'\n\t\t\t\t\t\ts = s + '; '\n\t\t\t\t\ts = s + '\\n'\n\t\t\t\telse:\n\t\t\t\t\ts = s + ip + ' = ' + str(svec) + \"'b\"\n\t\t\t\t\tfor k in range(svec):\n\t\t\t\t\t\ts = s + '0'\n\t\t\t\t\ts = s + '; '\n\t\t\t\t\ts = s + '\\n'\n\n\t\t\tf[1] = s\n\n\t\tif f[0] == '^vtb_inputchange^':\n\t\t\tif alltestcases:\n\t\t\t\tf[1] = AllTestCases(timedelay, inputs, inputs_sizes)\n\t\t\telse:\n\t\t\t\tf[1] = LimitedTestCases(nooftestcases, timedelay, inputs, inputs_sizes)\n\n\t\tif f[0] == '^vtb_clockdelay^':\n\n\t\t\tf[1] = str(clockdelay)\n\n\t\tif f[0] == '^vtb_clkname^':\n\t\t\tclkname = ''\n\t\t\tfor i in clock_inp_names:\n\t\t\t\tif i in inputs:\n\t\t\t\t\tclkname = i\n\t\t\tif clkname != '':\n\t\t\t\tf[1] = 'always #' + str(clockdelay) + '\\n\\t' + clkname + ' = ! ' + clkname + ';'\n\t\t\telse:\n\t\t\t\tf[1] = ''\n\n\n\tprint(\"FORMAT: \", format_values)\n\n#--7--\ndef LimitedTestCases(nooftestcases, timedelay, inputs, inputs_sizes):\n\ts = ''\n\tfor i in range(nooftestcases):\n\t\ts = s + '#' + str(timedelay) + ' '\n\t\trandom.randint(1,2)\n\t\ti=0\n\t\tfor ip in inputs:\n\t\t\tsvec = inputs_sizes[i][0]\n\t\t\tsarr = inputs_sizes[i][1]\n\t\t\tif sarr > 1:\n\t\t\t\tfor j in range(sarr):\n\t\t\t\t\ts = s + ip + '[' + str(j) + '] = ' + str(svec) + \"'b\"\n\t\t\t\t\tfor k in range(svec):\n\t\t\t\t\t\ts = s + str(random.randint(0,1))\n\t\t\t\t\ts = s + '; '\n\t\t\t\t#s = s + '\\n'\n\t\t\telse:\n\t\t\t\ts = s + ip + ' = ' + str(svec) + \"'b\"\n\t\t\t\tfor k in range(svec):\n\t\t\t\t\ts = s + str(random.randint(0,1))\n\t\t\t\ts = s + '; '\n\t\t\t\t#s = s + '\\n'\n\t\ts = s + '\\n'\n\treturn s\n\ndef AllTestCases(timedelay, inputs, inputs_sizes):\n\ts = ''\n\ttotal_size = 0\n\tfor ip in inputs_sizes:\n\t\ttotal_size = total_size + (ip[0]*ip[1])\n\n\tnoofcombinations = 2 ** total_size\n\n\ttotinp = [0]*total_size\n\n\tfor i in range(noofcombinations):\n\t\ts = s + '#' + str(timedelay) + ' '\n\t\ttotinp = GenNextInput(totinp)\n\n\t\ttotinpindex = 0\n\t\tindex=0\n\t\tfor ip in inputs:\n\t\t\tsvec = inputs_sizes[index][0]\n\t\t\tsarr = inputs_sizes[index][1]\n\t\t\tif sarr > 1:\n\t\t\t\tfor j in range(sarr):\n\t\t\t\t\ts = s + ip + '[' + str(j) + '] = ' + str(svec) + \"'b\"\n\t\t\t\t\tfor k in range(svec):\n\t\t\t\t\t\ts = s + str(totinp[totinpindex])\n\t\t\t\t\t\ttotinpindex+=1\n\t\t\t\t\ts = s + '; '\n\t\t\t\t#s = s + '\\n'\n\t\t\telse:\n\t\t\t\ts = s + ip + ' = ' + str(svec) + \"'b\"\n\t\t\t\tfor k in range(svec):\n\t\t\t\t\ts = s + str(totinp[totinpindex])\n\t\t\t\t\ttotinpindex+=1\n\t\t\t\ts = s + '; '\n\t\t\t\t#s = s + '\\n'\n\n\t\ts = s + '\\n'\n\n\treturn s\n\ndef GenNextInput(totinp):\n\tnewtotinp = totinp\n\ti = 0\n\tfor t in totinp:\n\t\tif t == 1:\n\t\t\tnewtotinp[i] = 0\n\t\telif t == 0:\n\t\t\tnewtotinp[i] = 1\n\t\t\tbreak\n\t\ti+=1\n\treturn newtotinp\n\n\n\n#--8--\ndef CreateOutputFile():\n\tglobal testbenchcode_format\n\tglobal format_values\n\n\tglobal destfolder\n\n\tcontents = ''\n\tfor c in testbenchcode_format:\n\n\t\tfor fv in format_values:\n\t\t\tc = c.replace(fv[0], fv[1])\n\t\tcontents = contents + c\n\t\tcontents = contents + '\\n'\n\tprint(\"OutputFileContents: \", contents)\n\n\tf = open(destfolder + '\\\\' + modulename + '_tb.v', 'w+')\n\tf.write(contents)\n\n\n#---------------------------------------------------------------------------\n\n#--Main Code----------------------------------------------------------------\n\nroot = tk.Tk()\nents = makeform(root, fields)\nroot.bind('', (lambda event, e=ents: fetch_inputs(e))) \nb1 = tk.Button(root, text='Done',\n\tcommand=(lambda e=ents: fetch_inputs(e)))\nb1.pack(side=tk.LEFT, padx=5, pady=5)\nb2 = tk.Button(root, text='Quit', command=root.quit)\nb2.pack(side=tk.LEFT, padx=5, pady=5)\nroot.mainloop()","sub_path":"TestBenchGen/Old/MainInputFrame_WithReGeX_AllPossInputs.py","file_name":"MainInputFrame_WithReGeX_AllPossInputs.py","file_ext":"py","file_size_in_byte":11506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"389154328","text":"from carsim import CarSim\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnum_steps=1000\n\nts = np.zeros(num_steps)\nvs = np.zeros(num_steps)\n\nc = CarSim()\n\nfor t in range(num_steps):\n if t>=500:\n c.speed(20.0)\n #c.torque(18.0)\n c.step()\n ts[t]=c.time\n vs[t]=c.get_speed()\n\nc.quit()\n\nplt.plot(ts,vs)\nplt.show()\n","sub_path":"bullet/spd_step.py","file_name":"spd_step.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"508778058","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport subprocess\n\n\ndef ssh_preamble(address, key_path):\n \"\"\" Common options to SSH into a conversion host. \"\"\"\n return [\n 'ssh',\n '-i', key_path,\n '-o', 'BatchMode=yes',\n '-o', 'StrictHostKeyChecking=no',\n '-o', 'ConnectTimeout=10',\n 'cloud-user@' + address\n ]\n\n\ndef dst_ssh(address, key_path, command):\n \"\"\" Get text output from running one SSH command on a conversion host. \"\"\"\n args = ssh_preamble(address, key_path)\n args.extend(command)\n return subprocess.check_output(args).decode('utf-8').strip()\n","sub_path":"os_migrate/plugins/module_utils/workload_common.py","file_name":"workload_common.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"153254818","text":"class Solution:\n def convert(self, s: str, numRows: int) -> str:\n if numRows ==1 :\n return s\n results = [\"\" for i in range(numRows)]\n block_size = numRows-2 +numRows\n for i in range(len(s)):\n in_block =i%block_size\n loc_row = in_block\n if in_block >= numRows:\n loc_row = numRows - (in_block - numRows +1)-1\n results[loc_row]+=s[i]\n return \"\".join(results)\n","sub_path":"6-zigzag-conversion/zigzag_conversion.py","file_name":"zigzag_conversion.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"85924113","text":"# Best time to buy and sell stock\n\n# You are given an integer array prices where prices[i] is the price of a given stock on the ith day.\n\n# On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.\n\n# Find and return the maximum profit you can achieve.\nfrom typing import List\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n # inputs [7,1,5,3,6,4]\n profit = 0\n j = 0\n for i in range(1,len(prices)):\n if prices[j] > prices[i]:\n j+=1\n elif prices[j] == prices[i]:\n j+=1\n else:\n profit = profit + (prices[i] - prices[j])\n return profit\n","sub_path":"Arrays/maxProfitStocks.py","file_name":"maxProfitStocks.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"400292534","text":"import numpy as np\nimport open3d as o3d\nimport os, copy, cv2, time\nimport CoordGenerator\nfrom tqdm import tqdm\n\nfrom reg_icp import *\n\n\ndef draw_registration_result(source, target, transformation):\n source_temp = copy.deepcopy(source)\n target_temp = copy.deepcopy(target)\n source_temp.paint_uniform_color([0, 0.651, 0.929])\n target_temp.paint_uniform_color([1, 0.706, 0])\n source_temp.transform(transformation)\n o3d.visualization.draw_geometries([source_temp, target_temp])\n\n\ndef vis(pcl, fid, pcd_fusion, transformation=None):\n\n #######################################\n # load depth and convert to pointcloud.\n #######################################\n depth = cv2.imread('{}/{}'.format(test_folder, depth_mask).format( fid*fid_step ), -1) / 1000.0\n if b_enable_dynamic_mask:\n diff = cv2.imread('{}/{}'.format(dynamic_folder, dynamic_mask).format( fid*fid_step ), -1)\n depth[diff==255]=0.\n\n pose_gt = np.loadtxt('{}/{}'.format(test_folder, pose_gt_mask).format( fid*fid_step ))\n pose = np.loadtxt('{}/{}'.format(est_folder, pose_est_mask).format(fid))\n pose = np.dot( rand_trans, pose )\n\n cg = CoordGenerator.CoordGenerator(intrinsics, image_width, image_height)\n coord, _ = cg.depth_pose_2coord(depth, pose)\n points = coord.reshape(-1, 3)\n pcd = o3d.geometry.PointCloud(o3d.utility.Vector3dVector(points))\n sampled_pcd = pcd.voxel_down_sample(voxel_size=pts_voxel_size)\n # normals for the frame.\n sampled_pcd.estimate_normals(search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=rad_for_norm_est, max_nn=30))\n sampled_pcd.orient_normals_towards_camera_location(pose[0:3,3])\n sampled_pcd.normalize_normals()\n # normals for the scene.\n pcl.orient_normals_towards_camera_location(pose[0:3,3])\n pcl.normalize_normals()\n\n source, target = sampled_pcd, pcl\n Rt_init = np.identity(4)\n\n origin_terr, origin_rerr = camera_pose_error( pose, pose_gt ) # pose before ICP.\n #if origin_terr < 0.20: return\n #if origin_terr > 0.10: return\n # print('frame', fid*fid_step)\n # print('error before ICP {:.2f}m {:.2f}deg'.format(origin_terr, origin_rerr))\n # draw_registration_result(source, target, Rt_init)\n\n\n #####################\n # point-to-plane ICP.\n #####################\n reg_p2l = o3d.pipelines.registration.registration_icp(\n source, target, ICP_threshold, Rt_init,\n o3d.pipelines.registration.TransformationEstimationPointToPlane())\n transformation = reg_p2l.transformation\n\n # terr, rerr = camera_pose_error( np.dot(transformation, pose), pose_gt ) # pose after ICP.\n # print('error after ICP {:.2f}m {:.2f}deg'.format(terr, rerr))\n # draw_registration_result(source, target, transformation)\n\n # fusion.\n source_temp = copy.deepcopy(source)\n source_temp.transform(transformation)\n pcd_fusion = pcd_fusion + source_temp\n pcd_fusion = pcd_fusion.voxel_down_sample(voxel_size=pts_voxel_size)\n pcd_fusion.paint_uniform_color([0, 0.651, 0.929])\n \n #o3d.visualization.draw_geometries([pcd_fusion])\n\n\n return pcd_fusion\n\n\n\n\nif __name__ == '__main__':\n\n sampled_pcl = o3d.io.read_point_cloud('data/_scene{:02d}_pts-{}_sp{}_vx{}.pcd'.format(scene_id, mesh_mode, n_scene_pts, pts_voxel_size))\n pcd_fusion = o3d.geometry.PointCloud()\n\n # for fid in range(0, 999999):\n # pose_path = '{}/{}'.format(est_folder, pose_est_mask).format(fid)\n # if not os.path.exists(pose_path): break \n # vis(sampled_pcl, fid, np.identity(4))\n\n\n succ_list = np.loadtxt('data/_scene{:02d}_succ_list.txt'.format(scene_id))\n fail_list = np.loadtxt('data/_scene{:02d}_fail_list.txt'.format(scene_id))\n # succ_terr_list = np.loadtxt('data/_scene{:02d}_succ_terr_list.txt'.format(scene_id))\n # fail_terr_list = np.loadtxt('data/_scene{:02d}_fail_terr_list.txt'.format(scene_id))\n\n for sid in tqdm(range(len(succ_list))):\n fid = int(succ_list[sid]/fid_step)\n pcd_fusion = vis(sampled_pcl, fid, pcd_fusion)\n\n o3d.io.write_point_cloud('data/_scene{:02d}_pts-fusion_sp{}_vx{}.pcd'.format(scene_id, n_scene_pts, pts_voxel_size), pcd_fusion)\n\n\n # for sid in range(len(fail_list)):\n # fid = int(fail_list[sid]/fid_step)\n # vis(sampled_pcl, fid)\n\n","sub_path":"Registration/stat.py","file_name":"stat.py","file_ext":"py","file_size_in_byte":4261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"292916372","text":"from char_function import character_creation\nfrom lob import lobby\nimport battle\nimport Enemies\nimport time\nimport random\nfrom playerstatsmod import playerprofile, statdisplay, helptext,itemcreation,inventory\nfrom Dungeon_map import dungeon_generation\n\nstart_time = time.time()\nplayerprofile\ngameflag = False\n\nwhile(gameflag != True):\n xInput = lobby()\n if xInput.lower() == \"quit\":\n print(\"You played for \" + str(round(time.time() - start_time)) + \" Seconds\")\n break\n elif xInput.lower() == \"stats\":\n statdisplay()\n elif xInput.lower() == 'help':\n helptext()\n elif xInput.lower() == 'fight':\n battle.combat()\n elif xInput.lower() == 'dungeon':\n dungeon_generation()\n elif xInput.lower() == 'debugitem':\n itemcreation()\n elif xInput.lower() == 'inventory':\n print(inventory)\n\n\n\n\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"540791346","text":"from pylab import figure, close, show, plot\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom matplotlib import dates\nimport datetime\n\na = np.array([\n [1293605162197, 0, 0],\n [1293605477994, 63, 0],\n [1293605478057, 0, 0],\n [1293605478072, 2735, 1249],\n [1293606162213, 0, 0],\n [1293606162229, 0, 0]])\n\nd = a[:,0]\ny1 = a[:,1]\ny2 = a[:,2]\n\n# convert epoch to matplotlib float format\ns = d/1000\nms = d-1000*s # not needed?\ndts = map(datetime.datetime.fromtimestamp, s)\nfds = dates.date2num(dts) # converted\n\n# matplotlib date format object\nhfmt = dates.DateFormatter('%m/%d %H:%M')\n\nfig = figure(1, )\nax = fig.add_subplot(111)\nax.vlines(fds, y2, y1)\n\nax.xaxis.set_major_locator(dates.MinuteLocator())\nax.xaxis.set_major_formatter(hfmt)\nax.set_ylim(bottom = 0)\n#ax.tick_params(axis='x', rotation=90)\n#-------- rotamos los xticks:\nxlabels = ax.get_xticklabels()\nfor label in xlabels:\n label.set_rotation(30)\n#plt.xticks(rotation='vertical')\n#plt.subplots_adjust(bottom=.3)\n#plt.show()\n\nshow(); close()\n","sub_path":"dates/gg.py","file_name":"gg.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"409156456","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# author: bigfoolliu\n\n\n\"\"\"\nelasticsearch模块使用\n\"\"\"\n\nfrom elasticsearch import Elasticsearch\n\nhttp_auth = {}\nes = Elasticsearch([{'host': '127.0.0.1', 'port': 9200}], timeout=3600, http_auth=http_auth)\n\n# print(Elasticsearch.__doc__)\nprint(es)\n\n\ndef query_all():\n \"\"\"\n 全部查询\n \"\"\"\n query = {\n 'query': {\n 'match_all': {}\n }\n }\n result = es.search(index='test-index', body=query)\n for row in result['hits']['hits']:\n print(row)\n\n\ndef demo_query():\n query_all()\n\n\nif __name__ == \"__main__\":\n demo_query()\n","sub_path":"language/python/modules/Database/elasticsearch/elasticsearch_module.py","file_name":"elasticsearch_module.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"42383963","text":"class Solution(object):\n def firstMissingPositive(self, A):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\" \n # Pass 1, move every value to the position of its value\n n = len(A)\n for index in xrange(n):\n element = A[index]\n while True:\n if element <= 0 or element > n or element == A[element - 1]:\n break\n A[element - 1], element = element, A[element - 1]\n \n # Pass 2, find first location where the index doesn't match the value\n for index in xrange(n):\n if A[index] != index + 1:\n return index + 1\n return n + 1\n","sub_path":"First-Missing-Positive.py","file_name":"First-Missing-Positive.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"116477923","text":"import cv2\nimport numpy as np\nimport os \ndef distance(v1, v2):\n # Eucledian \n return np.sqrt(((v1-v2)**2).sum())\n\ndef knn(train, test, k=5):\n dist = []\n \n for i in range(train.shape[0]):\n # Get the vector and label\n ix = train[i, :-1]\n iy = train[i, -1]\n # Compute the distance from test point\n d = distance(test, ix)\n dist.append([d, iy])\n # Sort based on distance and get top k\n dk = sorted(dist, key=lambda x: x[0])[:k]\n # Retrieve only the labels\n labels = np.array(dk)[:, -1]\n \n # Get frequencies of each label\n output = np.unique(labels, return_counts=True)\n # Find max frequency and corresponding label\n index = np.argmax(output[1])\n return output[0][index]\ncap = cv2.VideoCapture(0)\ndataset_path = './data/'\n\nface_data =[]\nlabels=[]\n\nclass_id = 0\nnames = {}\nfor fx in os.listdir(dataset_path):\n if fx.endswith('.npy'):\n #Create a mapping btw class_id and name\n names[class_id] = fx[:-4]\n print(\"Loaded \"+fx)\n data_item = np.load(dataset_path+fx)\n face_data.append(data_item)\n\n #Create Labels for the class\n target = class_id*np.ones((data_item.shape[0],))\n class_id += 1\n labels.append(target)\n\nface_dataset = np.concatenate(face_data,axis=0)\nface_labels = np.concatenate(labels,axis=0).reshape((-1,1))\n\nprint(face_dataset.shape)\nprint(face_labels.shape)\n\ntrainset = np.concatenate((face_dataset,face_labels),axis=1)\nprint(trainset.shape)\n\nwhile True:\n ret,frame = cap.read()\n if ret == False:\n continue\n\n from google.cloud import vision\n client = vision.ImageAnnotatorClient()\n cv2.imwrite(\"/home/chirag/attendance/frame.jpg\", frame) \n #from PIL import Image, ImageDraw\n path=\"/home/chirag/attendance/frame.jpg\"\n with io.open(path,'rb') as image_file:\n content =image_file.read()\n image = vision.types.Image(content=content)\n #image.source.image_uri = uri\n #print(type(image))\n response = client.face_detection(image=image)\n faces = response.face_annotations\n # Names of likelihood from google.cloud.vision.enums\n likelihood_name = ('UNKNOWN', 'VERY_UNLIKELY', 'UNLIKELY', 'POSSIBLE','LIKELY', 'VERY_LIKELY')\n for face in faces:\n #print('anger: {}'.format(likelihood_name[face.anger_likelihood]))\n #print('joy: {}'.format(likelihood_name[face.joy_likelihood]))\n #print('surprise: {}'.format(likelihood_name[face.surprise_likelihood]))\n #vertices = (['({},{})'.format(vertex.x, vertex.y)\n #for vertex in face.bounding_poly.vertices]:\n #print(type(vertex))\n b =[]\n\n for vertex in face.bounding_poly.vertices:\n b.append(vertex)\n x_i=int(b[0].x)\n x_f=int(b[2].x)\n y_i=int(b[0].y)\n y_f=int(b[2].y)\n \n \n face_section = frame[y_i:y_f,x_i:x_f]\n face_section = cv2.resize(face_section,(100,100))\n out = knn(trainset,face_section.flatten())\n pred_name = names[int(out)]\n cv2.putText(frame,pred_name,(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2,cv2.LINE_AA)\n cv2.rectangle(frame,(x_i,y_i),(x_f,y_f),(0,255,255),2)\n\n cv2.imshow(\"Faces\",frame)\n\n key = cv2.waitKey(1) & 0xFF\n if key==ord('q'):\n break\n \ncap.release()\ncv2.destroyAllWindows()","sub_path":"recognize_knn.py","file_name":"recognize_knn.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"97119855","text":"'''\nsome code has been borrowed from https://hotblackrobotics.github.io/en/blog/2018/01/29/seq-goals-py/\n'''\n\nimport rospy\nimport actionlib\nimport math\nimport json\nimport paramiko\nimport os\nimport time\nimport getpass\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\nfrom geometry_msgs.msg import Pose, Point, Quaternion\nfrom tf.transformations import quaternion_from_euler\nfrom nav_msgs.msg import Odometry\nfrom tf import TransformListener\n\n\ndef active_cb():\n global goal_start_time\n \n goal_start_time = rospy.get_time()\n rospy.loginfo(\"Goal pose is now being processed by the Action Server...\")\n\n\ndef feedback_cb(feedback):\n pass\n\n\ndef done_cb(status, result):\n global goal_duration, goal_start_time, goal_running\n\n if status == 2:\n rospy.loginfo(\"Goal pose received a cancel request after it started executing, completed execution!\")\n if status == 3:\n rospy.loginfo(\"Goal pose reached\")\n goal_duration += rospy.get_time() - goal_start_time\n goal_running = False\n if status == 4:\n rospy.loginfo(\"Goal pose was aborted by the Action Server\")\n rospy.signal_shutdown(\"Goal pose aborted, shutting down!\")\n goal_running = False\n shutdown()\n if status == 5:\n rospy.loginfo(\"Goal pose has been rejected by the Action Server\")\n rospy.signal_shutdown(\"Goal pose rejected, shutting down!\")\n goal_running = False\n shutdown()\n if status == 8:\n rospy.loginfo(\"Goal pose received a cancel request before it started executing, successfully cancelled!\")\n goal_running = False\n\n\ndef set_goal(pose, client):\n global goal_running\n\n goal_running = True\n goal_pose = MoveBaseGoal()\n goal_pose.target_pose.pose.position = Point(x=pose[0], y=pose[1])\n goal_pose.target_pose.pose.orientation = Quaternion(*(quaternion_from_euler(0, 0, pose[2]*math.pi/180, axes='sxyz')))\n goal_pose.target_pose.header.frame_id = \"map\"\n goal_pose.target_pose.header.stamp = rospy.Time.now()\n rospy.loginfo(\"Sending goal pose to Action Server\")\n client.send_goal(goal_pose, done_cb=done_cb, active_cb=active_cb, feedback_cb=feedback_cb)\n\n\ndef start_client(client):\n rospy.init_node('move_base_testbench')\n \n rospy.loginfo(\"Waiting for move_base action server...\")\n wait = client.wait_for_server(rospy.Duration(5.0))\n\n if not wait:\n rospy.logerr(\"Action server not available!\")\n rospy.signal_shutdown(\"Action server not available!\")\n\n rospy.loginfo(\"Connected to move base server\")\n\n\ndef cancel_goal():\n client.cancel_all_goals()\n\n\ndef start_test(zero_offset):\n global client, goal_duration, goal_start_time, goal_running, pos, listener\n\n #goal_seq = [(2.993, -1.157, 90.0), (0.0, 0.0, 0.0)]\n goal_seq = [(2.993, 3.02, 270.0), (2.993, 0.0, 180.0), (0.0, 0.0, 0.0)]\n\n #Read in json file from previous tests\n fp = open(\"src/data.json\", \"r+\")\n data = json.load(fp)\n fp.close()\n\n #Ask for name of test\n #If blank name given, use last test name\n\n name = raw_input(\"What is the name of the current test? \")\n\n if name == \"\":\n name = data[\"last test\"]\n else:\n data[name] = []\n data[\"last test\"] = name\n\n print(\"Starting test sequence\")\n\n test_num = len(data[name])\n data[name].append({})\n test = data[name][test_num]\n\n load_checked = False\n\n for goal in goal_seq:\n print(\"Moving to position\")\n set_goal(goal, client)\n time.sleep(1)\n\n while True:\n if not goal_running:\n break\n else:\n if not load_checked:\n test[\"cpu load\"] = get_cpu_load()\n load_checked = True\n \n pos, rot = listener.lookupTransform('/map', '/base_link', listener.getLatestCommonTime('/map', '/base_link'))\n test['reported distance'] = math.sqrt(pos[0]**2 + pos[1]**2) \n test[\"time taken\"] = goal_duration\n\n #Ask for measured distance the robot moved\n test[\"real distance\"] = abs(float(zero_offset) - float(raw_input(\"What was the actual distance the robot moved? \")))\n \n #Test finished, serialise to json\n fp = open(\"src/data.json\", \"w\")\n json.dump(data, fp, indent=2)\n fp.close()\n\n\ndef get_cpu_load():\n global ssh\n\n stdin, stdout, stderr = ssh.exec_command('mpstat -P ALL 16 1')\n tot_load = []\n count = 1\n\n for line in stdout:\n if count < 14:\n count += 1\n continue\n elif count < 18:\n load = line.split()[-1]\n load = 100.0 - float(load)\n #load = load * (3.0 / 32.0)\n #load = load * (0.5 / 10.0)\n tot_load.append(load)\n else:\n load = line.split()[-1]\n load = 100.0 - float(load)\n #load = load * (10.0 / 32.0)\n #load = load * (4.0 / 10.0)\n tot_load.append(load)\n\n count += 1\n\n return tot_load\n\n\ndef shutdown():\n\tglobal client, ssh\n\t\n\tprint('Shutting down ROS')\n\tdel client\n\t#os.system('source ~/catkin_ws/devel/setup.bash; rosnode kill move_base_testbench')\n\tssh.exec_command('source ~/catkin_ws/devel/setup.bash; rosnode kill -a')\n\ttime.sleep(2)\n\n\tssh.close()\n\texit()\n\n\ngoal_duration = 0.0\ngoal_start_time = 0.0\ngoal_running = False\npos = Point(0.0, 0.0, 0.0)\nrob_ip = '10.80.29.159'\n\nos.environ['ROS_MASTER_URI'] = 'http://' + rob_ip + ':11311'\n\nssh = paramiko.SSHClient()\nssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\npw = getpass.getpass('Password for rock64: ')\nssh.connect(rob_ip, username='rock64', password=pw)\nprint('Connection to robot successful')\n\nzero_offset = raw_input(\"Static measured distance: \")\nprint('Launching ROS on robot')\ntransport = ssh.get_transport()\nchannel = transport.open_session()\nchannel.exec_command('source ~/catkin_ws/devel/setup.bash; roslaunch uow_nav.launch')\ntime.sleep(15)\n\nprint('Starting local client')\nclient = actionlib.SimpleActionClient('move_base', MoveBaseAction)\ntime.sleep(2)\n\nstart_client(client)\nlistener = TransformListener()\nrate = rospy.Rate(0.5)\n\nstart_test(zero_offset)\n\nshutdown()\n","sub_path":"src/control_lib.py","file_name":"control_lib.py","file_ext":"py","file_size_in_byte":6089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"35999488","text":"from rascal.calibrator import Calibrator\r\nfrom itertools import combinations\r\nimport pytest\r\nimport logging\r\n\r\nlogging.basicConfig(level=logging.DEBUG)\r\nlogger = logging.getLogger()\r\n\r\n\r\ndef test_no_elements():\r\n logger.info(\"Testing no elements\")\r\n cal = Calibrator()\r\n assert len(cal.atlas) > 0\r\n assert len(cal.atlas_elements) > 0\r\n\r\ndef test_empty_elements():\r\n logger.info(\"Testing load empty element list\")\r\n with pytest.raises(ValueError):\r\n cal = Calibrator(elements=[])\r\n\r\ndef test_load_single_line():\r\n element_list = [\"Hg\", \"Ar\", \"Xe\", \"CuNeAr\", \"Kr\"]\r\n\r\n for element in element_list:\r\n logger.info(\"Testing load single element: {}\".format(element))\r\n cal = Calibrator(elements=element)\r\n assert len(cal.atlas) > 0\r\n assert len(cal.atlas_elements) > 0\r\n\r\ndef test_load_mutliple_lines():\r\n\r\n element_list = [\"Hg\", \"Ar\", \"Xe\", \"CuNeAr\", \"Kr\"]\r\n\r\n for i in range(1, len(element_list)+1):\r\n for elements in combinations(element_list, i):\r\n logger.info(\"Testing load elements: {}\".format(elements))\r\n cal = Calibrator(elements=elements)\r\n assert len(cal.atlas) > 0\r\n assert len(cal.atlas_elements) > 0","sub_path":"test/test_arclines.py","file_name":"test_arclines.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"21020167","text":"\"\"\"\n[user, attr_x, item]\nuse cls to represent the attributes\n\"\"\"\nimport torch\nfrom torch import log, unsqueeze\nimport torch.nn as nn\nfrom torch.nn.modules.transformer import TransformerEncoder, TransformerEncoderLayer\nimport torch.nn.utils.rnn as rnn_utils\nimport torch.nn.functional as F\n\nclass _ATTR_NETWORK(nn.Module):\n def __init__(self, vocab_obj, args, device):\n super(_ATTR_NETWORK, self).__init__()\n\n self.m_device = device\n \n self.m_vocab_size = vocab_obj.vocab_size\n self.m_user_num = vocab_obj.user_num\n self.m_item_num = vocab_obj.item_num\n\n self.m_attr_embed_size = args.attr_emb_size\n self.m_user_embed_size = args.user_emb_size\n self.m_item_embed_size = args.item_emb_size\n\n self.m_attn_head_num = args.attn_head_num\n self.m_attn_layer_num = args.attn_layer_num\n\n self.m_attn_linear_size = args.attn_linear_size\n\n # self.m_attr_embedding = nn.Embedding(self.m_vocab_size, self.m_attr_embed_size)\n self.m_user_embedding = nn.Embedding(self.m_user_num, self.m_user_embed_size)\n self.m_item_embedding = nn.Embedding(self.m_item_num, self.m_item_embed_size)\n self.m_attr_embedding_user = nn.Embedding(self.m_vocab_size, self.m_user_embed_size)\n self.m_attr_embedding_item = nn.Embedding(self.m_vocab_size, self.m_user_embed_size)\n\n encoder_layers = TransformerEncoderLayer(self.m_attr_embed_size, self.m_attn_head_num, self.m_attn_linear_size)\n self.m_attn = TransformerEncoder(encoder_layers, self.m_attn_layer_num)\n\n self.m_gamma = args.gamma\n\n ### cls: self.m_vocab_size+1\n ### 0: pad_id\n\n self.m_attr_embedding_x = nn.Embedding(self.m_vocab_size+1, self.m_attr_embed_size)\n \n seg_num = 2\n self.m_seg_embedding = nn.Embedding(seg_num, self.m_attr_embed_size)\n\n max_seq_len = args.max_seq_length\n self.m_pop_embedding = nn.Embedding(max_seq_len+2, self.m_attr_embed_size)\n \n self.f_init_weight()\n\n self = self.to(self.m_device)\n\n def f_init_weight(self):\n initrange = 0.1\n \n torch.nn.init.uniform_(self.m_attr_embedding_x.weight, -initrange, initrange)\n\n torch.nn.init.uniform_(self.m_attr_embedding_item.weight, -initrange, initrange)\n torch.nn.init.uniform_(self.m_attr_embedding_user.weight, -initrange, initrange)\n torch.nn.init.uniform_(self.m_user_embedding.weight, -initrange, initrange)\n torch.nn.init.uniform_(self.m_item_embedding.weight, -initrange, initrange)\n\n def f_generate_mask(self, length):\n max_len = length.max().item()\n mask = torch.arange(0, max_len).expand(len(length), max_len).to(length.device)\n mask = mask < length.unsqueeze(1)\n\n mask = ~mask\n\n return mask\n\n def forward(self, attr, attr_inds, attr_tf, attr_pops, attr_lens, attr_lens_user, attr_lens_item, user_ids, item_ids, pos_targets, pos_lens, neg_targets, neg_lens):\n \n ### attr: cls+attr_user+attr_item\n ### attr_inds: 0+0+1\n ### attr_pops: 0+1,2,3+1,2,3\n\n attr_embed = self.m_attr_embedding_x(attr)\n segment_embed = self.m_seg_embedding(attr_inds)\n pop_embed = self.m_pop_embedding(attr_pops)\n\n attr_mask = self.f_generate_mask(attr_lens)\n\n input = attr_embed+segment_embed+pop_embed\n\n ### attr_attn: batch_size*attr_lens*embed_size\n attr_attn = input.transpose(0, 1)\n attr_attn = self.m_attn(attr_attn, src_key_padding_mask=attr_mask)\n attr_attn = attr_attn.transpose(0, 1)\n\n attr_x = attr_attn[:, 0, :]\n\n user_embed = self.m_user_embedding(user_ids)\n item_embed = self.m_item_embedding(item_ids)\n\n # output = torch.cat([user_embed, attr_x, item_embed], dim=-1)\n \n neg_embed_user = self.m_attr_embedding_user(neg_targets)\n neg_embed_item = self.m_attr_embedding_item(neg_targets)\n neg_embed_x = self.m_attr_embedding_x(neg_targets)\n\n ### user_item_output: batch_size*ouput_size\n ### neg_logits: batch_size*neg_num\n neg_logits_user = torch.matmul(neg_embed_user, user_embed.unsqueeze(-1))\n neg_logits_user = neg_logits_user.squeeze(-1)\n\n neg_logits_item = torch.matmul(neg_embed_item, item_embed.unsqueeze(-1))\n neg_logits_item = neg_logits_item.squeeze(-1)\n\n neg_logits_x = torch.matmul(neg_embed_x, attr_x.unsqueeze(-1))\n neg_logits_x = neg_logits_x.squeeze(-1)\n\n neg_mask = self.f_generate_mask(neg_lens)\n neg_mask = ~neg_mask\n\n ### targets: batch_size*pos_num\n ### pos_embed: batch_size*pos_num*embed_size\n # pos_embed = self.m_attr_embedding(pos_targets)\n\n pos_embed_user = self.m_attr_embedding_user(pos_targets)\n pos_embed_item = self.m_attr_embedding_item(pos_targets)\n pos_embed_x = self.m_attr_embedding_x(pos_targets)\n\n ### user_item_output: batch_size*ouput_size\n ### neg_logits: batch_size*neg_num\n pos_logits_user = torch.matmul(pos_embed_user, user_embed.unsqueeze(-1))\n pos_logits_user = pos_logits_user.squeeze(-1)\n\n pos_logits_item = torch.matmul(pos_embed_item, item_embed.unsqueeze(-1))\n pos_logits_item = pos_logits_item.squeeze(-1)\n\n pos_logits_x = torch.matmul(pos_embed_x, attr_x.unsqueeze(-1))\n pos_logits_x = pos_logits_x.squeeze(-1)\n\n pos_mask = self.f_generate_mask(pos_lens)\n pos_mask = ~pos_mask\n\n pos_logits = pos_logits_user+pos_logits_item+pos_logits_x\n neg_logits = neg_logits_user+neg_logits_item+neg_logits_x\n\n logits = torch.cat([pos_logits, neg_logits], dim=-1)\n\n mask = torch.cat([pos_mask, neg_mask], dim=-1)\n\n new_targets = torch.cat([torch.ones_like(pos_targets), torch.zeros_like(neg_targets)], dim=1)\n\n new_targets = new_targets*mask\n\n return logits, mask, new_targets\n\n def f_eval_forward(self, attr, attr_inds, attr_tf, attr_pops, attr_lens, attr_lens_user, attr_lens_item, user_ids, item_ids):\n\n attr_embed = self.m_attr_embedding_x(attr)\n segment_embed = self.m_seg_embedding(attr_inds)\n pop_embed = self.m_pop_embedding(attr_pops)\n\n attr_mask = self.f_generate_mask(attr_lens)\n\n input = attr_embed+segment_embed+pop_embed\n\n ### attr_attn: batch_size*attr_lens*embed_size\n attr_attn = input.transpose(0, 1)\n attr_attn = self.m_attn(attr_attn, src_key_padding_mask=attr_mask)\n attr_attn = attr_attn.transpose(0, 1)\n\n attr_x = attr_attn[:, 0, :]\n\n user_embed = self.m_user_embedding(user_ids)\n item_embed = self.m_item_embedding(item_ids)\n\n logits_user = torch.matmul(user_embed, self.m_attr_embedding_user.weight.t())\n logits_item = torch.matmul(item_embed, self.m_attr_embedding_item.weight.t())\n logits_x = torch.matmul(attr_x, self.m_attr_embedding_x.weight.t())\n\n logits = logits_user + logits_item + logits_x[:, :-1]\n\n return logits","sub_path":"hier2attr/model_cls.py","file_name":"model_cls.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"226739316","text":"# Automatic testing for the implementation of Transposition Cipher\n\nimport random\nimport sys\nimport transposition\n\ndef main():\n\trandom.seed(42)\n\n\t# test 20 times\n\tfor i in range(20):\n\t\t# The message will have a random length:\n\t\tmessage = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' * random.randint(4, 40)\n\n\t\t# Convert the message string to a list to shuffle it.\n\t\tmessage = list(message)\n\t\trandom.shuffle(message)\n\t\tmessage = ''.join(message) # convert list to string\n\n\t\tprint('Test #%s: \"%s...\"' % (i+1, message[:50]))\n\n\t\t# Check all possible keys for each message.\n\t\tfor key in range(1, len(message)):\n\t\t\tencrypted = transposition.encrypt(message, key)\n\t\t\tdecrypted = transposition.decrypt(encrypted, key)\n\n\t\t\tif message != decrypted:\n\t\t\t\tprint('Mismatch with key %s and message %s.' % (key, message))\n\t\t\t\tprint(decrypted)\n\t\t\t\tsys.exit()\n\n\tprint('Transposition cipher test passed.')\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"transpositionTest.py","file_name":"transpositionTest.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"631259551","text":"from cing.Libs import peirceTest\nfrom unittest import TestCase\nfrom cing import verbosityError\nfrom cing import verbosityDebug\nimport cing\nimport unittest\n\nclass AllChecks(TestCase):\n \n def testPeirceTest1(self): \n values = [101.2, 90.0, 99.0, 102.0, 103.0, 100.2, 89.0, 98.1, 101.5, 102.0]\n vOld,_oOld = peirceTest.peirceTestOld( values )\n# print 'v=',vOld\n# print vOld.av, vOld.sd\n# print 'o=',_oOld\n# \n v,_o = peirceTest.peirceTest( values )\n# print 'v=',v\n# print v.av, v.sd\n# print 'o=',_o\n \n self.assertTrue( vOld == v )\n\n def testPeirceTest2(self):\n # A stable array just longer than the reference data used in the test.\n values = [] \n for i in range(0,1000):\n values.append(1) \n# nTdebug(\"n=\",len(values))\n for i in range(0,10):\n values[i] = 2 \n # Will only note first 9 outliers\n vOld,oOld = peirceTest.peirceTestOld( values )\n# print 'v=',vOld\n# print vOld.av, vOld.sd\n# print 'obj=',oOld\n# \n v,obj = peirceTest.peirceTest( values )\n# print 'v=',v\n# print v.av, v.sd\n# print 'obj=',obj\n \n self.assertFalse( vOld == v )\n self.assertFalse( oOld == obj )\n \n def testPeirceTest3(self):\n #Note the difference between array sizes 17 and 18. \n #No outliers identified at 18 but 7 outliers made the cutoff at size 17\n values = [] \n n = 200 # Default value 200. Tested up to 10,000 once before.\n m = 10 # Only tested with default value 10.\n for i in range(0,n):\n values.append(1) \n# nTdebug(\"n=\", len(values))\n for i in range(0,m):\n values[i] = 2\n \n while n > 3:\n values = values[:n] \n _v,obj = peirceTest.peirceTest( values )\n# print 'number of outliers at size: '+repr(n)+ ' =',len(obj)\n self.assertTrue(len(obj)<=m)\n n -= 1\n \n def testPeirceTest4(self):\n values = [] \n n = 2 # Default value 200. Tested up to 10,000 once before.\n for i in range(n):\n values.append(i) \n \n result = peirceTest.peirceTest( values )\n self.failUnless(result)\n v,obj = result\n# print 'number of outliers at size: '+repr(n)+ ' =',len(obj)\n self.assertTrue(len(v) == n)\n self.assertTrue(len(obj) == 0)\n \n def testPeirceTest5(self):\n values = [61.1080599488, 34.876110084, 63.0380528016, -37.3907919689, 55.7742201359, 158.950985878, 152.580838711, 159.962185469, \n 39.5242231825, 167.478815798, -45.1721895276, 150.966989049, 38.7181950131, 54.4126758063, 62.9191496902, -41.4928983793,\n 46.5057394648, -36.3803547969, -48.513237809, 61.4695459467]\n \n result = peirceTest.peirceTest( values )\n self.failUnless(result)\n v,obj = result\n# print 'number of outliers at size: '+repr(n)+ ' =',len(obj)\n self.assertTrue(len(v) == 10)\n self.assertTrue(len(obj) == 10)\n\n \nif __name__ == \"__main__\":\n cing.verbosity = verbosityError\n cing.verbosity = verbosityDebug\n unittest.main()\n","sub_path":"python/cing/Libs/test/test_PeirceTest.py","file_name":"test_PeirceTest.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"415231461","text":"import catboost\nimport pandas as pd\nimport os\nfrom catboost import CatBoostClassifier\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport pymorphy2\n\nif os.path.exists(os.path.join(os.path.abspath(os.curdir), 'models/model')):\n model = CatBoostClassifier()\n model.load_model('models/model')\n train_data = pd.read_excel('test.xlsx')\n comments = train_data['Comment']\n with open('models/model_file.txt', 'r') as file_model:\n dic_keys = file_model.read().split(',')\n data = np.zeros((len(comments), len(dic_keys) + 1))\n for i in range(0, len(comments)):\n for j in range(0, len(dic_keys)):\n if dic_keys[j] in comments[i]:\n data[i][j] = 1\n else:\n data[i][j] = 0\n data[i][-1] = len(comments[i])\n models_predict = model.predict(data=data)\n for i in range(len(models_predict)):\n print('{} : {}'.format(comments[i], models_predict[i]))\n\nelse:\n train_data = pd.read_excel('train.xlsx')\n comments = train_data['Comment']\n target = train_data['Toxic']\n normal_word = {}\n for i in comments:\n for word in i.split(' '):\n p = pymorphy2.MorphAnalyzer().parse(word=word)[0]\n if p.tag.POS not in ['NOUN', 'ADJF', 'ADJS', 'VERB', 'INFN', 'PRTF', 'PRTS', 'GRND', 'ADVB']:\n continue\n else:\n if p.normal_form in normal_word:\n normal_word[p.normal_form] += 1\n else:\n normal_word[p.normal_form] = 1\n dictionar = {}\n for key in normal_word.keys():\n if normal_word[key] > 5:\n dictionar[key] = normal_word.get(key)\n else:\n continue\n data = np.zeros((len(comments), len(dictionar) + 1))\n label = np.zeros((len(target)))\n dic_keys = list(dictionar.keys())\n for i in range(0, len(comments)):\n for j in range(0, len(dic_keys)):\n if dic_keys[j] in comments[i]:\n data[i][j] = 1\n else:\n data[i][j] = 0\n data[i][-1] = len(comments[i])\n label[i] = target[i]\n\n model = CatBoostClassifier()\n x_train, y_train, x_test, y_test = train_test_split(data, label, test_size=0.005)\n x_train.shape\n x_test.shape\n model.fit(data, label)\n print(\"Модель обучена, идет запись на носитель\")\n np_correct = (y_test == model.predict(x_test)).sum()\n\n model.save_model('models/model',\n format=\"cbm\",\n export_parameters=None,\n pool=None)\n with open('models/model_file.txt', 'w') as file_model:\n file_model.write(','.join(dic_keys))\n","sub_path":"Neuron_catboost.py","file_name":"Neuron_catboost.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"50063294","text":"#!/usr/bin/python\nimport json, dicttoxml, sys\n\n# pass the filename as an argument when calling this script\nif len(sys.argv) < 2:\n\tsys.exit('Usage: json-to-xml.py file.json')\nfilename_in = sys.argv[1]\nfilename_list = [filename_in.split('.')[0], 'xml']\nfilename_out = \".\".join(filename_list)\n\n# read the json file filename in\ninput = open(filename_in)\ndata = json.load(input)\ninput.close()\n\n# convert to xml\nxml = dicttoxml.dicttoxml(data)\n\n# write the xml file\nwith open(filename_out, \"wb+\") as outfile:\n\toutfile.write(xml)\n","sub_path":"Python/json-to-xml.py","file_name":"json-to-xml.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"598985681","text":"# \n\n\n#get_ipython().magic('matplotlib notebook')\n#get_ipython().magic('matplotlib inline')\n\n#import os\nimport time\n#import datetime as dt\nimport numpy as np\n#from numpy import newaxis\nimport matplotlib.pyplot as plt\nimport pandas as pd\n#import pandas_datareader\n#import stock_data_preprocessing_x\n\n\n# \n# [2]:\n\n###############################################################################\n#load Google stock data\n#start = dt.datetime(1995,1,1)\n#end = dt.date.today()\n#data = pandas_datareader.data.DataReader('GOOG','yahoo',start,end)\ndata = pd.read_csv('googl.csv')\n#data = data[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']]\n#data = data.set_index(['Date'])\ndata.head()\ndata.shape\n\ndata.plot(y=['Close', 'Adj Close'])\ndata.plot(y=['Volume'])\nplt.show()\n# # Normalise and Prepozess the data like a boss^12\n\n# \n# [3]:\n###############################################################################\n##normalise data\n#data_n = stock_data_preprocessing.normalise_stock_data(data)\n#data_n.head()\n#data_n.shape\n#\n#data_n = data_n[['Adj Volume', 'Adj Close']]\n# # 1,2,3 Plot Line!\n\n#pd.DataFrame(data['Adj Close'].cumsum()).plot()\n\n# calculate markup of adj close, this will be the predict target y\n# markup = (today price - last day price) / last day price * 100\n# the first day markup=0\naryMarkup = np.zeros(shape=(len(data),1))\naryMarkup.shape\ndata.shape\n\npreRow = None\nfor i, row in data.iterrows():\n# print(i,end='\\r')\n if( preRow is None ):\n preRow = row\n continue\n# print(i)\n# aryMarkup[i] = 1\n# print(row['Adj Close'])\n# print(preRow['Adj Close'])\n aryMarkup[i] = (row['Adj Close'] - preRow['Adj Close']) / preRow['Adj Close']\n preRow = row\n\ndata['markup'] = aryMarkup*100\n#data['markup'].plot(figsize=(15,6))\n\nmax_volume = data['Volume'].max()\ndata['Adj Volume'] = data['Volume'] / max_volume * 10\n\n# [4]:\ndata_n = pd.DataFrame(data[['Adj Volume', 'markup']])\ndata_n.shape\n\ndata_n['markup'].plot()\nplt.title('markup')\nplt.show()\n\ndata_n['Adj Volume'].plot()\nplt.title('Adj Volume')\nplt.show()\n\n#stock_data_preprocessing.stock_plot((data_n,))\n#stock_data_preprocessing.stock_plot(data_n)\n\n# \n###############################################################################\n\n# make training and test data set\n#\n# x_train.shape = (samples, seq_steps, input_features)\n# y_train.shape = (samples,)\n#\n# x_test.shape = (samples, seq_steps, input_features)\n# y_test.shape = (samples,)\n\n# [5]:\n\n\n# training data\nprediction_time = 1 # predict the markup of the prediction_time day\ntestdatasize = 300\nseq_steps = 20\ntestdatacut = testdatasize + seq_steps + 1\n\nx_train = data_n[1 : -testdatacut].as_matrix()\ny_train = data_n[1+prediction_time : -testdatacut+prediction_time]['markup'].as_matrix()\n#y_train = data_n[prediction_time:-testdatacut ]['Adj Close'].as_matrix()\n#y_train = data_n[prediction_time:-testdatacut ]['Normalised Close'].as_matrix()\nx_train.shape\ny_train.shape\n\n# test data\nx_test = data_n[-testdatacut : -prediction_time].as_matrix()\ny_test = data_n[-testdatacut+prediction_time :]['markup'].as_matrix()\n#y_test = data_n[prediction_time-testdatacut: ]['Adj Close'].as_matrix()\n#y_test = data_n[prediction_time-testdatacut: ]['Normalised Close'].as_matrix()\nx_test.shape\ny_test.shape\n\n# # unroll it\n\n# [6]:\n\n\ndef unroll(data,sequence_length=24):\n result = []\n for index in range(len(data) - sequence_length + 1):\n result.append(data[index: index + sequence_length])\n return np.asarray(result)\n\n\nx_train = unroll(x_train,seq_steps)\nx_test = unroll(x_test,seq_steps)\ny_train = y_train[-x_train.shape[0]:]\ny_test = y_test[-x_test.shape[0]:]\n#y_train = y_train[-x_train.shape[0]:]\n#y_test = y_test[-x_test.shape[0]:]\n\n\nprint(\"x_train\", x_train.shape)\nprint(\"y_train\", y_train.shape)\nprint(\"x_test\", x_test.shape)\nprint(\"y_test\", y_test.shape)\n\n# \n###############################################################################\n# (with Python 3.5.3, Keras 2.0.4 and Tensorflow 1.2)\n\n# [7]:\n\nfrom keras.layers.core import Dense, Activation, Dropout\nfrom keras.layers.recurrent import LSTM\nfrom keras.models import Sequential\n\n\n# [ ]:\n\n\n#Step 2 Build Model\nmodel = Sequential()\n\nmodel.add(LSTM(\n input_dim=x_train.shape[-1],\n output_dim=128,\n return_sequences=True))\n#model.add(Dropout(0.15))\n\nmodel.add(LSTM(\n 128,\n return_sequences=False))\n#model.add(Dropout(0.2))\n\nmodel.add(Dense(20))\nmodel.add(Dense(output_dim=1))\n#model.add(Activation('linear'))\n\nstart = time.time()\nmodel.compile(loss='mse', optimizer='rmsprop')\nprint('compilation time : {}'.format(time.time() - start))\n\n\n# \n# [ ]:\n###############################################################################\n#Step 3 Train the model\nhistory = model.fit(\n x_train,\n y_train,\n batch_size=256,\n nb_epoch=25,\n validation_split=0.1)\n\n# list all data in history\nprint(history.history.keys())\n\n\n# summarize history for loss\nplt.figure()\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'test'], loc='upper left')\nplt.show()\n\n## summarize history for accuracy\n#plt.figure()\n#plt.plot(history.history['acc'])\n#plt.plot(history.history['val_acc'])\n#plt.title('model accuracy')\n#plt.ylabel('accuracy')\n#plt.xlabel('epoch')\n#plt.legend(['train', 'test'], loc='upper left')\n\n# \n# [ ]:\n###############################################################################\n# predict on test data\np = model.predict(x_test)\n\n# plot the predicted markup value and the actural markup value\nplt.figure(figsize=(12,5))\nplt.plot(p,color='red', label='prediction')\nplt.plot(y_test,color='blue', label='y_test')\nplt.legend(loc='upper left')\nplt.grid(True)\nplt.show()\n\n# transform markup back into close price\npred_test_close = np.zeros(shape=(len(x_test)+seq_steps))\npred_test_close[0:seq_steps] = data['Adj Close'][-testdatacut : -testdatacut + seq_steps]\npred_test_close.shape\n\nfor i in range(len(x_test)):\n pred_test_close[seq_steps+i] = pred_test_close[seq_steps+i-1] * (1 + p[i] / 100)\n\n# plot predict price and actural price, calculate the log value\npred_test_close_log = np.log(pred_test_close)\ndata_close_log = np.log(data['Adj Close'].values)\n\nplt.figure()\nplt.plot(pred_test_close_log,color='red', label='prediction')\nplt.plot(data_close_log[-len(pred_test_close_log):],color='blue', label='y_test')\nplt.legend(loc='upper left')\nplt.show()\n\n# \n###############################################################################\n# predict on the training data\np_train = model.predict(x_train)\n\n# plot the predicted markup value and the actural markup value\n# hard to see\nplt.figure(figsize=(40,5))\nplt.plot(y_train,color='blue', label='y_train')\nplt.plot(p_train,color='red', label='prediction')\nplt.title('markup prediction')\nplt.legend(loc='upper left')\nplt.show()\n\nlen(p_train)\n\n\n# transform markup back into close price\npred_close = np.zeros(shape=(len(x_train)+seq_steps+1))\npred_close[0:seq_steps+1] = data['Adj Close'][0:seq_steps+1]\npred_close.shape\n\nfor i in range(len(x_train)):\n pred_close[seq_steps+1+i] = pred_close[seq_steps+i] * (1 + p_train[i] / 100)\n\n## plot predict price and actural price\n#plt.figure(figsize=(52,5))\n#plt.plot(pred_close[0:1000],color='red', label='prediction')\n#plt.plot(data['Adj Close'][0:1000],color='blue', label='y_train')\n\n# plot predict price and actural price, calculate the log value\npred_close_log = np.log(pred_close)\ndata_close_log = np.log(data['Adj Close'].values)\n\nplt.figure(figsize=(40,5))\nplt.plot(pred_close_log[0:1000],color='red', label='prediction')\nplt.plot(data_close_log[0:1000],color='blue', label='y_train')\nplt.title('price(log) prediction')\nplt.legend(loc='upper left')\nplt.show()\n\n## plot the predicted markup value\n#plt.figure(figsize=(52,5))\n#plt.plot(p_train[0:1000],color='red', label='prediction')\n#plt.grid(True)\n#plt.show()\n\n##Step 4 - Plot the predictions!\n#predictions = lstm.predict_sequences_multiple(model, x_test, 50, 50)\n##predictions = predict_sequences_multiple(model, x_test, 50, 50)\n#len(predictions)\n#len(predictions[0])\n#lstm.plot_results_multiple(predictions, y_test, 50)\n\n","sub_path":"stockdemo_x.py","file_name":"stockdemo_x.py","file_ext":"py","file_size_in_byte":8206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"581784003","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\ndef do_grab__(st=10848, ed=10869):\n for page in range(st, ed):\n res = requests.get(f'https://www.555duo.net/a/html/{page}.html')\n soup = BeautifulSoup(res.text)\n down_soup = soup.find_all('a', class_='down')\n if down_soup and len(down_soup)>6:\n href = down_soup[6].get('href')\n print(href)\n\n\ndo_grab__(4900, 4930)\n","sub_path":"papapa/spider_5duo.py","file_name":"spider_5duo.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"326033539","text":"import torch\nfrom torch.functional import F\nfrom torch.autograd import Variable\nimport matplotlib.pyplot as plt\n\n\n# y = a * x^2 + b\nx = torch.unsqueeze(torch.linspace(-1,1,100),dim = 1)\n\ny = x.pow(2)+0.2*torch.rand(x.size())\n#\n# plt.scatter(x.data.numpy(),y.data.numpy())\n# plt.show()\n\n# build a nn\n\n# x, y = Variable(x), Variable(y)\nclass Net(torch.nn.Module):\n def __init__(self,n_features,n_hidden,n_output):\n super(Net,self).__init__()\n self.hidden = torch.nn.Linear(n_features,n_hidden)\n self.predict = torch.nn.Linear(n_hidden,n_output)\n def forward(self, x):\n x = F.relu(self.hidden(x))\n x = self.predict(x)\n return x\n\nnet = Net(n_features=1,n_hidden=10,n_output=1) # 回归问题,只需要输出一个值就可以\n\nprint (net) # 打印搭建的神经网络结构\n\n# train the net\n\noptimizer = torch.optim.SGD(net.parameters(),lr = 0.2)\nloss_func = torch.nn.MSELoss() # 回归预测一般使用均方误差\n\n\nplt.ion() # 画图\n# plt.show()\nfor t in range(200):\n prediction = net(x) # 每次输入一个数,在网络内部 1-10-1\n loss = loss_func(prediction,y)\n\n# optimizer.zero_grad()\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if t % 5 == 0:\n # plot and show learning process\n plt.cla()\n plt.scatter(x.data.numpy(), y.data.numpy())\n plt.plot(x.data.numpy(), prediction.data.numpy(), 'r-', lw=5)\n plt.text(0.5, 0, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})\n plt.pause(0.1)\nplt.ioff()\nplt.show()","sub_path":"learn_9_regression.py","file_name":"learn_9_regression.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"377219211","text":"#-*- coding: UTF-8 -*-\nimport json\nfrom five import grok\nfrom Acquisition import aq_parent\nfrom datetime import datetime\nfrom DateTime import DateTime\n\nfrom emc.kb.contents.feed import Ifeed\nfrom emc.kb.contents.answer import Ianswer\nfrom emc.kb.contents.question import Iquestion\nfrom emc.kb.contents.feedsfolder import Ifeedsfolder\nfrom emc.kb.interfaces import IFollowing,IFollowing\nfrom emc.kb.interfaces import ICreatedMentionwoFolderEvent\nfrom emc.memberArea.interfaces import IMemberAreaCreatedEvent\n\nfrom Products.CMFCore.utils import getToolByName\nfrom plone.dexterity.utils import createContentInContainer\nfrom Products.PluggableAuthService.interfaces.authservice import IPropertiedUser\n\nfrom zope import event\nfrom zope import component\nfrom zope.intid import IntIds\nfrom zope.component import getUtility\nfrom zope.intid.interfaces import IIntIds\nfrom zc.relation.interfaces import ICatalog\nfrom zope.lifecycleevent import ObjectModifiedEvent\nfrom zope.lifecycleevent.interfaces import IObjectAddedEvent\nfrom z3c.relationfield import RelationValue,RelationCatalog\n\n \n@grok.subscribe(Ianswer, IObjectAddedEvent)\ndef feedquestionanswer(obj,event):\n \"\"\"关注问题有新答案\"\"\"\n catalog = getToolByName(obj, 'portal_catalog')\n questionobject = aq_parent(obj)\n questionlist = IFollowing(questionobject).followed\n if len(questionlist) == 0:\n return\n \n for question in questionlist:\n brain = catalog({'object_provides': Ifeedsfolder.__identifier__,\n 'Creator': question,\n 'sort_on': 'sortable_title'})\n if not brain:\n break\n folder = brain[0].getObject()\n if not folder:\n break\n \n id = questionobject.getId()\n feed = catalog({'object_provides': Ifeed.__identifier__,\n 'id': id,\n 'path': dict(query='/'.join(folder.getPhysicalPath()),\n depth=1), \n 'sort_on': 'sortable_title'})\n \"\"\"如果存在当前记录,重置修改时间,否则新建\"\"\"\n if len(feed) > 0:\n feed[0].getObject().type = 3\n feed[0].getObject().setModificationDate(DateTime())\n else:\n item = createContentInContainer(folder,\"emc.kb.feed\",checkConstraints=False,id=id)\n item.type = 3\n \n@grok.subscribe(Ianswer, IObjectAddedEvent)\ndef feedtopicanswer(obj,event):\n \"\"\"关注话题中问题有答案\"\"\"\n questionobject = aq_parent(obj)\n intids = getUtility(IIntIds) \n intid = intids.getId(questionobject)\n catalog = component.getUtility(ICatalog) \n qlist = sorted(catalog.findRelations({'from_id': intid}))\n if len(qlist) == 0: return\n for q in qlist:\n topicobject = q.to_object\n topiclist = IFollowing(topicobject).followed\n \"\"\"计算关联回答的topic分数\"\"\"\n topicobject.topicscore = topicobject.topicscore + 0.3\n topicobject.reindexObject()\n \n catalog = getToolByName(obj, 'portal_catalog')\n for topic in topiclist:\n brain = catalog({'object_provides': Ifeedsfolder.__identifier__,\n 'Creator': topic,\n 'sort_on': 'sortable_title'})\n if not brain:\n break\n folder = brain[0].getObject()\n if not folder:\n break\n \n id = questionobject.getId()\n feed = catalog({'object_provides': Ifeed.__identifier__,\n 'id': id,\n 'path': dict(query='/'.join(folder.getPhysicalPath()),\n depth=1), \n 'sort_on': 'sortable_title'})\n \"\"\"如果存在当前记录,重置修改时间,否则新建\"\"\"\n if len(feed) > 0:\n feed[0].getObject().type = 2\n feed[0].getObject().setModificationDate(DateTime())\n else:\n item = createContentInContainer(folder,\"emc.kb.feed\",checkConstraints=False,id=id)\n item.type = 2\n \n@grok.subscribe(Iquestion, IObjectAddedEvent)\ndef feedtopciquestion(obj,event):\n \"\"\"关注话题有问题\"\"\"\n intids = getUtility(IIntIds)\n intid = intids.getId(obj)\n catalog = component.getUtility(ICatalog) \n qtlist = sorted(catalog.findRelations({'from_id': intid}))\n if len(qtlist) == 0: return \n \n for q in qtlist:\n topiclist = IFollowing(q.to_object).followed\n catalog = getToolByName(obj, 'portal_catalog')\n for topic in topiclist:\n brain = catalog({'object_provides': Ifeedsfolder.__identifier__,\n 'Creator': topic,\n 'sort_on': 'sortable_title'})\n if not brain:\n break\n folder = brain[0].getObject()\n if not folder:\n break\n \n id = obj.getId()\n feed = catalog({'object_provides': Ifeed.__identifier__,\n 'id': id,\n 'path': dict(query='/'.join(folder.getPhysicalPath()),\n depth=1), \n 'sort_on': 'sortable_title'})\n \"\"\"如果存在当前记录,重置修改时间,否则新建\"\"\"\n if len(feed) > 0:\n feed[0].getObject().type = 1\n feed[0].getObject().setModificationDate(DateTime())\n else:\n item = createContentInContainer(folder,\"emc.kb.feed\",checkConstraints=False,id=id)\n item.type = 1","sub_path":"emc/kb/subscribers/feed.py","file_name":"feed.py","file_ext":"py","file_size_in_byte":5531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"161328203","text":"'''\n需要生成一个 mask: 111111...1000001...1111, 从 i 到 j 位为 0,剩下为 1\n100000 - 100 = 011100\n参考 https://www.jianshu.com/p/e8a1f04190cf\n'''\n\nclass Solution:\n \"\"\"\n @param n: An integer\n @param m: An integer\n @param i: A bit position\n @param j: A bit position\n @return: An integer\n \"\"\"\n def updateBits(self, n, m, i, j):\n # write your code here\n n = ((1 << 32) - 1) & n\n m = ((1 << 32) - 1) & m\n m = m << i\n mask = ~((1 << (j+1)) - (1 << i))\n return (n & mask) + m\n \n \n\nif __name__ == '__main__':\n solution = Solution()\n #print(solution.updateBits(1024, 21, 2, 6))\n print(solution.updateBits(1, -1, 0, 31))","sub_path":"Lintcode-ladder/MathBitManipulation/updateBits.py","file_name":"updateBits.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"113424911","text":"class Solution(object):\n def findMinArrowShots(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n if not points:\n return 0\n \n points.sort(key = lambda x: x[1])\n \n arrow, first_end = 1, points[0][1]\n \n for start, end in points:\n if start > first_end:\n arrow +=1\n first_end = end\n \n return arrow","sub_path":"Week3/MinimumNumberofArrowstoBurstBalloons.py","file_name":"MinimumNumberofArrowstoBurstBalloons.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"313816440","text":"\"\"\"\nЗадание_6.\tВ одномерном массиве найти сумму элементов,\nнаходящихся между минимальным и максимальным элементами.\nСами минимальный и максимальный элементы в сумму не включать.\n\nПодсказки:\n1) берем первый минимальный и максимальный\n2) не забудьте, что сначала может быть минимальный, потом максимальный\nа может - наоборот. во всех этих случаях нужна корректная работа\n\nПример:\nВведите количество элементов в массиве: 10\nМассив: [88, 58, 50, 77, 49, 6, 42, 67, 14, 79]\nСумма элементов между минимальным (6) и максимальным (88) элементами: 234\n\"\"\"\n\nfrom random import random\n\nwhile True:\n try:\n # число элементов в массиве\n N = int(input('\\nВведите количество элементов в массиве: '))\n NUMS_LST = [0] * N\n for i in range(N):\n # заполняем массив числами [0,99]\n NUMS_LST[i] = int(random() * 100)\n print(f'Исходный массив:\\n{NUMS_LST}')\n\n INDEX_MIN_NUMS = NUMS_LST.index(min(NUMS_LST))\n INDEX_MAX_NUMS = NUMS_LST.index(max(NUMS_LST))\n print('\\nСписок <<индекс:начение>>')\n for i, v in enumerate(NUMS_LST, 0):\n print(f'{i}:{v}', end=' ')\n\n print(f'\\n\\nИндекс минимального элемента: {INDEX_MIN_NUMS}')\n print(f'Индекс максимального элемента: {INDEX_MAX_NUMS}')\n TOTAL_NUMS = 0\n if INDEX_MAX_NUMS < INDEX_MIN_NUMS:\n for i in range(INDEX_MAX_NUMS + 1, INDEX_MIN_NUMS):\n TOTAL_NUMS = TOTAL_NUMS + NUMS_LST[i]\n else:\n for i in range(INDEX_MIN_NUMS + 1, INDEX_MAX_NUMS):\n TOTAL_NUMS = TOTAL_NUMS + NUMS_LST[i]\n print(\n f'Сумма элементов между минимальным \\'{NUMS_LST[INDEX_MIN_NUMS]}\\'',\n end=' ')\n print(\n f'и максимальным \\'{NUMS_LST[INDEX_MAX_NUMS]}\\' элементами: {TOTAL_NUMS}')\n break\n except ValueError:\n print('Некорректно введённые данные!')\n","sub_path":"Урок 3.Практическое задание/task_6.py","file_name":"task_6.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"73681589","text":"import os\n月份表 = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']\n\n输入内容 = input('请输入月份数字:')\ntry:\n 月份 = int(输入内容)\nexcept:\n print(\"输入错误!\")\n os._exit(-1)\n\nif 月份 > 12:\n print(\"数字太大!\")\nelif 月份 < 1:\n print(\"数字太小!\")\nelse:\n print(\"月份简写为:{}\".format(月份表[月份 - 1]))","sub_path":"第05周/2_month_number_to_short.py","file_name":"2_month_number_to_short.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"444150453","text":"from selenium import webdriver\r\nimport time\r\nimport os\r\nimport psutil # For memory usage\r\nimport re\r\nimport pandas as pd # For dataframe output\r\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\r\n# For not explicitly wait for elements to load\r\nfrom selenium.webdriver.support.ui import WebDriverWait \r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.common.by import By\r\ncapabilities = DesiredCapabilities.FIREFOX \r\nlimit = True # Setting the limit to 100 pages\r\n\r\n# Custom path to geckodriver\r\ngecko_path = 'C:\\\\uw\\\\DSBA 2\\\\Web Scraping\\\\bonus\\\\geckodriver.exe'\r\n\r\nurl = 'https://arxiv.org' # Starting webpage\r\n\r\noptions = webdriver.firefox.options.Options()\r\noptions.headless = False\r\n\r\ndriver = webdriver.Firefox(options = options, executable_path = gecko_path)\r\nwait = WebDriverWait(driver, 30) # Maximum wait time\r\n# Actual program:\r\nstart = time.time()\r\ndriver.get(url)\r\n# Clicking the \"Advanced Search\" button when it appears\r\nwait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div/header/div[2]/div[2]/form/div/div[1]/p/a[2]'))) \r\ndriver.execute_script(\"window.stop();\")\r\nbutton = driver.find_element_by_xpath('/html/body/div/header/div[2]/div[2]/form/div/div[1]/p/a[2]')\r\nbutton.click()\r\n\r\n# Clicking the checkbox for \"Computer Science\" when it appears\r\nwait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/div[2]/div[1]/div/form/section[2]/fieldset[1]/div[2]/div[1]/div[1]/div/div/input'))) \r\nbutton = driver.find_element_by_xpath('/html/body/main/div[2]/div[2]/div[1]/div/form/section[2]/fieldset[1]/div[2]/div[1]/div[1]/div/div/input')\r\nbutton.click()\r\n\r\n# Clickig the \"Search\" button when it appears\r\nbutton = driver.find_element_by_xpath('/html/body/main/div[2]/div[2]/div[1]/div/form/section[3]/button')\r\nbutton.click()\r\nwait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/nav[1]/a[2]'))) \r\n\r\n\r\n# Initializing the empty list for informations of papers\r\nTitle_list = []\r\nCategory_list = []\r\nA_list = []\r\nDate_list = []\r\nPDF_list = []\r\n\r\n# Function to scrape required info for each paper\r\ndef scrape(driver):\r\n\t# We wait for the last title to be load, instead of explicitly waiting for the whole page to load\r\n\t# This is beneficial since it's more efficient\r\n\twait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/ol/li[50]/p[1]'))) \r\n\t# To scrape the title using regex\r\n\ttitle = re.findall(r'([\\s\\S]*?)<\\/p>', driver.page_source)\r\n\tfor t in title:\r\n\t\tTitle_list.append(t.strip())\r\n\r\n\t# We wait for the last category to be visible\r\n\twait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/ol/li[50]/div/div/span[1]')))\r\n\t# To scrape the category\r\n\tcategory = driver.find_elements_by_class_name(\"tags.is-inline-block\")\r\n\tfor c in category:\r\n\t\tif 'cs.' in c.text: # To make sure that it gets the CS tags if the paper is an interdisciplinary\r\n\t\t\tCategory_list.append(re.findall('cs.[A-Z][A-Z]',c.text)[0][-2:])\r\n\t\telse:\r\n\t\t\tprint(\"None\")\r\n\t\r\n\t# Again we wait for the author of the last paper to be load\r\n\twait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/ol/li[50]/p[2]')))\r\n\t# To scrape the authors by using the class name\r\n\tAuthors = driver.find_elements_by_class_name(\"authors\")\r\n\tfor a in Authors:\r\n\t\tA_list.append(a.text[9:]) # To remove \"Authors: \" from the beginning of the string\r\n\r\n\t# Waiting for the date of the last paper to be load\r\n\twait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/ol/li[50]/p[4]'))) \r\n\t# To scrape the submitted date by using regex \r\n\tdate = re.findall(r'Submitted<\\/span> ([\\s\\S]*?)[^;]+<\\/p>', driver.page_source)\r\n\tfor d in date:\r\n\t\tDate_list.append(d[:-1])\r\n\r\n\t# Waiting for the pdf link of the last paper to be load\r\n\twait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/ol/li[50]/div/p/span/a[1]')))\r\n\t# To scrape the PDF url by using regex\r\n\tPDF = re.findall(r'https:\\/\\/arxiv.org\\/pdf\\/[^\"]+', driver.page_source)\r\n\tfor p in PDF:\r\n\t\tPDF_list.append(p)\r\n\t\r\n\t# To click the \"Next\" button after achieving the required data in each page\r\n\twait.until(EC.presence_of_element_located((By.XPATH, '/html/body/main/div[2]/nav[1]/a[2]'))) \r\n\tdriver.find_element_by_xpath('/html/body/main/div[2]/nav[1]/a[2]').click()\r\n\r\n\r\nif limit:\r\n\tfor i in range(2): # For 100 papers, since in each page we have 50 results\r\n\t\tscrape(driver)\r\n# Assuming around 800 papers to scrape when the limit is set to fasle. In total there are more \r\n# than 327360 pages in recent CS papers\r\nelse:\r\n\tfor i in range(16): # For 800 papers, since in each page we have 50 results\r\n\t\tscrape(driver)\r\nend = time.time()\r\nprint(\"Elapsed time during scraping in seconds:\",round(end - start,2)) \r\nprint(\"Memory usage in MB:\",round(psutil.Process(os.getpid()).memory_info().rss / 1024 ** 2,2))\r\n\r\n# Saving to dataframe and output as CSV file\r\nt = pd.Series(Title_list, name = 'Title')\r\nc = pd.Series(Category_list, name = 'Category')\r\na = pd.Series(A_list, name = 'Authors')\r\nd = pd.Series(Date_list, name = 'Date')\r\np = pd.Series(PDF_list, name = 'PDF')\r\ndf = pd.concat([t,c,a,d,p], axis=1)\r\ndf.to_csv('papers.csv', index=False)\r\n\r\ndriver.quit()\r\n","sub_path":"selenium/arxiv_(Selenium).py","file_name":"arxiv_(Selenium).py","file_ext":"py","file_size_in_byte":5299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"413080052","text":"from django.contrib.auth import login, authenticate\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.forms.models import inlineformset_factory\nfrom django.shortcuts import render, redirect\n\nfrom .forms import ProfileForm, SignUpForm\nfrom .models import UserProfile\n\n\n@login_required\ndef dashboard(request):\n try:\n usuario = UserProfile.objects.get(user=request.user)\n except UserProfile.DoesNotExist:\n usuario = None\n return render(request, 'dashboard.html', {'usuario': usuario, })\n\n\n@login_required\ndef profile(request):\n try:\n usuario = UserProfile.objects.get(user=request.user)\n except UserProfile.DoesNotExist:\n usuario = None\n\n return render(request, 'profile.html', {'usuario': usuario})\n\n\n@login_required\ndef profile_update(request):\n try:\n usuario = UserProfile.objects.get(user=request.user)\n except UserProfile.DoesNotExist:\n usuario = None\n\n ProfileInlineFormset = inlineformset_factory(User, UserProfile, fields=('avatar',))\n formset = ProfileInlineFormset(instance=request.user)\n\n if request.method == 'POST':\n form = ProfileForm(data=request.POST, instance=request.user)\n formset = ProfileInlineFormset(request.POST, request.FILES, instance=request.user)\n\n if form.is_valid():\n perfil = form.save(commit=False)\n formset = ProfileInlineFormset(request.POST, request.FILES, instance=perfil)\n\n if formset.is_valid():\n perfil.save()\n formset.save()\n # return HttpResponseRedirect('/accounts/profile/')\n return redirect('dashboard')\n\n else:\n form = ProfileForm(instance=request.user)\n formset = ProfileInlineFormset(instance=request.user)\n\n return render(request, 'profile_update.html', {'form': form,\n 'formset': formset,\n 'usuario': usuario, })\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignUpForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n raw_password = form.cleaned_data.get('password1')\n user = authenticate(username=username, password=raw_password)\n login(request, user)\n return redirect('dashboard')\n else:\n form = SignUpForm()\n return render(request, 'registration/signup.html', {'form': form})\n","sub_path":"core/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"6263808","text":"import numpy as np\nimport tensorflow as tf\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\n\nclass CommNetLever:\n \n def __init__(self, sess, N, J, embedding_size = 128, lr = 1e-3, training_mode = 'supervised', alpha = 0.03):\n \n '''\n - N: total number of agents\n - J: number of levers (and agents randomly selected at each step)\n - embedding_size: dimension of the hidden layers \n - lr: learning rate \n - training_mode: 'supervised' or 'reinforce'\n - alpha: paramater used by reinforce training mode to balance reward and baseline loss\n \n '''\n \n self.N = N\n self.J = J\n self.embedding_size = embedding_size\n \n self.build_controler()\n \n self.training_mode = training_mode\n \n if training_mode == 'supervised':\n self.build_supervised()\n with tf.variable_scope('Supervised_optimizer'):\n self.train_op = tf.train.AdamOptimizer(lr).minimize(self.supervised_loss)\n \n elif training_mode == 'reinforce':\n self.alpha = 0.03\n self.build_reinforce()\n with tf.variable_scope('Reinforce_optimizer'):\n self.train_op = tf.train.RMSPropOptimizer(lr).minimize(self.reinforce_loss)\n \n else:\n raise(ValueError(\"Unknown training mode: %s\" % training_mode)) \n \n self.sess = sess\n self.sess.run(tf.global_variables_initializer())\n \n def encode(self, inputs):\n \n with tf.variable_scope('Encoder'):\n \n self.identity_embeddings = tf.get_variable(\"identity_embeddings\",\n [self.N, self.embedding_size])\n \n self.embedded_identities = tf.nn.embedding_lookup(self.identity_embeddings, inputs)\n \n \n return tf.unstack(self.embedded_identities, axis = 1)\n \n def build_f(self, name, h, c, h0 = None):\n \n with tf.variable_scope(name, reuse = tf.AUTO_REUSE):\n \n if h0 is not None and c is not None:\n \n b1 = tf.get_variable('b1', shape = (1, self.embedding_size))\n W1 = tf.get_variable('W1', shape = (3 * self.embedding_size,\n self.embedding_size))\n \n W2 = tf.get_variable('W2', shape = (self.embedding_size,\n self.embedding_size))\n \n concat = tf.concat([h, c, h0], axis = 1)\n \n elif h0 is not None and c is None: \n b1 = tf.get_variable('b1', shape = (1, self.embedding_size))\n \n W1 = tf.get_variable('W1', shape = (2 * self.embedding_size,\n self.embedding_size))\n \n W2 = tf.get_variable('W2', shape = (self.embedding_size,\n self.embedding_size))\n \n concat = tf.concat([h, h0], axis = 1)\n \n elif c is not None and h0 is None:\n \n b1 = tf.get_variable('b1', shape = (1, self.embedding_size))\n \n W1 = tf.get_variable('W1', shape = (2 * self.embedding_size,\n self.embedding_size))\n \n W2 = tf.get_variable('W2', shape = (self.embedding_size,\n self.embedding_size))\n \n concat = tf.concat([h, c], axis = 1)\n \n else:\n \n b1 = tf.get_variable('b1', shape = (1, self.embedding_size))\n \n W1 = tf.get_variable('W1', shape = (self.embedding_size,\n self.embedding_size))\n \n W2 = tf.get_variable('W2', shape = (self.embedding_size,\n self.embedding_size))\n \n concat = h\n \n \n b2 = tf.get_variable('b2', shape = (1, self.embedding_size))\n \n dense1 =tf.nn.relu(tf.einsum(\"ij,jk->ik\", concat, W1) + b1)\n dense2 = tf.nn.relu(tf.einsum(\"ij,jk->ik\", dense1, W2) + b2)\n \n return dense2\n \n def decode(self, h):\n \n with tf.variable_scope('Decoder', reuse = tf.AUTO_REUSE):\n \n W = tf.get_variable('W', shape = (self.embedding_size,\n self.J))\n \n b = tf.get_variable('b', shape = (1, self.J))\n \n policy_logit = tf.einsum(\"ij,jk->ik\", h, W) + b\n \n return policy_logit\n \n \n def communicate(self, h_seq):\n \n # mean of hidden layers \n return tf.add_n(h_seq) / (self.J - 1)\n \n def sample_actions(self, log_proba):\n \n action = tf.multinomial(log_proba, num_samples = 1)\n \n return action\n \n \n def build_controler(self):\n \n self.inputs = tf.placeholder(tf.int32, shape = (None, self.J))\n \n h0_seq = self.encode(self.inputs)\n c0_seq = [self.communicate([h0_seq[j] for j in range(self.J) if j != i]) for i in range(self.J)]\n \n h1_seq = [self.build_f(\"Comm_step_1\", h0_seq[j], c0_seq[j], None) for j in range(self.J)]\n c1_seq = [self.communicate([h1_seq[j] for j in range(self.J) if j != i]) for i in range(self.J)]\n \n self.h2_seq = [self.build_f(\"Comm_step_2\", h1_seq[j], c1_seq[j], h0_seq[j]) for j in range(self.J)]\n \n # can be used to check values of hidden states \n self.hidden_layers = {'h0_seq': h0_seq, 'c0_seq': c0_seq, 'h1_seq': h1_seq, 'c1_seq':c1_seq, 'h2_seq': self.h2_seq}\n \n \n self.policy_logit_seq = [self.decode(h2) for h2 in self.h2_seq]\n self.log_proba_seq = [tf.nn.log_softmax(policy_logit, axis = 1) for policy_logit in self.policy_logit_seq]\n self.action_seq = [self.sample_actions(log_proba) for log_proba in self.log_proba_seq]\n self.one_hot_action_seq = [tf.one_hot(action, depth = self.J) for action in self.action_seq]\n \n \n \n def build_supervised(self):\n \n assert self.training_mode == 'supervised', 'Wrong training mode'\n \n self.targets = tf.placeholder(tf.int32, shape = (None, self.J))\n unstacked_targets = tf.unstack(self.targets, axis = 1)\n \n supervised_loss_seq = [tf.nn.sparse_softmax_cross_entropy_with_logits(labels=unstacked_targets[j],\n logits=self.policy_logit_seq[j])\n for j in range(self.J)]\n \n self.supervised_loss = tf.reduce_mean(supervised_loss_seq)\n \n \n def supervised_train(self, X, y, val_X, val_y, env, batch_size = 32, epochs = 1):\n \n \n assert self.training_mode == 'supervised', 'Wrong training mode'\n \n n = X.shape[0]\n \n val_n = val_X.shape[0]\n \n data_inds = np.array(range(n))\n for ep in range(1, epochs + 1):\n # shuffle data for each epoch\n np.random.shuffle(data_inds)\n \n supervised_loss_sum = 0\n reward_sum = 0\n for i in tqdm(range(0, n, batch_size), \"Epoch: %d\" % ep):\n \n # select batch data\n inds_batch = data_inds[i:i+batch_size]\n X_batch = X[inds_batch]\n y_batch = y[inds_batch]\n \n # train on batch\n _, supervised_loss, one_hot_action_seq = self.sess.run([self.train_op, self.supervised_loss, self.one_hot_action_seq], feed_dict={self.inputs: X_batch, self.targets: y_batch})\n \n # keep track of the loss and reward\n supervised_loss_sum += supervised_loss * batch_size\n reward_sum += env.get_reward(one_hot_action_seq)\n \n print(\"loss = %f\" % (supervised_loss_sum / n))\n print(\"reward = %f\" % (reward_sum / n))\n print()\n \n # eval loss and reward on validation set\n val_supervised_loss, val_one_hot_action_seq = self.sess.run([self.supervised_loss, self.one_hot_action_seq], feed_dict={self.inputs: val_X, self.targets: val_y})\n print('val loss = %f' % (val_supervised_loss))\n print('val reward = %f' % (env.get_reward(val_one_hot_action_seq) / val_n))\n \n def build_baseline(self, h):\n \n '''state specific baseline for reinforce training mode is given by a simple FC layer\n connected to the last hidden layer of the controler\n '''\n \n assert self.training_mode == 'reinforce', 'Wrong training mode'\n \n with tf.variable_scope('Baseline', reuse = tf.AUTO_REUSE):\n \n W = tf.get_variable('W', shape = (self.embedding_size,\n 1))\n \n b = tf.get_variable('b', shape = (1,))\n \n \n baseline = tf.einsum(\"ij,jk->ik\", h, W) + b\n \n return baseline\n \n\n def build_reinforce(self):\n \n assert self.training_mode == 'reinforce', 'Wrong training mode'\n \n # only used for scattering \n self.indices = tf.placeholder(tf.int32, shape = (None, 2))\n self.shape = tf.placeholder(tf.int32, shape =(2,))\n \n # baseline tensors\n self.baselines = tf.concat([self.build_baseline(h2) for h2 in self.h2_seq], axis = 1)\n self.scattered_baselines = tf.scatter_nd(self.indices, tf.reshape(self.baselines, [-1]), shape = self.shape)\n \n # reward values\n self.repeated_reward_values = tf.placeholder(tf.float32, shape = (None,))\n self.scattered_reward_values = tf.scatter_nd(self.indices, self.repeated_reward_values, shape = self.shape)\n self.scattered_reward_values_cumsum = tf.cumsum(self.scattered_reward_values, axis = 0, reverse = True)\n \n # baseline values\n self.baseline_values = tf.placeholder(tf.float32, shape = (None, self.J))\n self.scattered_baseline_values = tf.scatter_nd(self.indices, tf.reshape(self.baseline_values, [-1]), shape = self.shape)\n \n # actions that have been taken\n self.action_taken = tf.placeholder(tf.int32, shape = (None, self.J))\n unstacked_action_taken = tf.unstack(self.action_taken, axis = 1)\n \n # neg log proba of taken actions\n self.neg_log_p = tf.transpose(tf.concat([[tf.nn.sparse_softmax_cross_entropy_with_logits(labels=unstacked_action_taken[j],\n logits=self.policy_logit_seq[j])] for j in range(self.J)], axis = 0))\n self.scattered_neg_log_p = tf.scatter_nd(self.indices, tf.reshape(self.neg_log_p, [-1]), shape = self.shape)\n \n #surrogate loss (- dtheta)\n self.reinforce_loss = tf.reduce_sum(tf.multiply(self.scattered_neg_log_p, self.scattered_reward_values_cumsum - self.scattered_baseline_values))\n self.reinforce_loss += self.alpha * tf.reduce_sum(tf.square(self.scattered_reward_values_cumsum - self.scattered_baselines))\n self.reinforce_loss /= self.J\n \n \n def take_action(self, state):\n \n assert self.training_mode == 'reinforce', 'Wrong training mode'\n \n action_seq, baselines= self.sess.run([self.action_seq, self.baselines], {self.inputs: [state]})\n \n return [a[0,0] for a in action_seq], baselines\n \n def reinforce_train(self, env, n_episodes, T):\n \n assert self.training_mode == 'reinforce', 'Wrong training mode'\n \n history = {'reward' : [], 'loss': []} \n \n for _ in tqdm(range(n_episodes), \"REINFORCE\"):\n \n \n state_seq, action_seq, reward_seq, baseline_seq = self.policy_rollout(T, env)\n episode_len = reward_seq.shape[0]\n \n history['reward'].append(np.mean(reward_seq))\n \n repeated_t = np.repeat(np.arange(episode_len), self.J)\n \n indices = np.vstack([repeated_t, state_seq.ravel()]) .T\n \n feed_dict = {}\n feed_dict[self.inputs] = state_seq\n feed_dict[self.indices] = indices\n feed_dict[self.shape] = [episode_len, self.N]\n feed_dict[self.repeated_reward_values] = np.repeat(reward_seq, self.J)\n feed_dict[self.baseline_values] = baseline_seq\n feed_dict[self.action_taken] = action_seq\n \n _, loss = self.sess.run([self.train_op, self.reinforce_loss], feed_dict = feed_dict)\n \n history['loss'].append(loss)\n \n \n return history\n\n\n def policy_rollout(self, T, env):\n \n '''\n Simulate one episode of length T at most\n '''\n \n state_seq = []\n action_seq = []\n reward_seq = []\n baseline_seq = []\n \n \n state, terminal_state = env.reset()\n \n t = 0\n \n while not terminal_state and t < T:\n t +=1\n \n state_seq.append(state)\n action, baseline = self.take_action(state)\n \n state, reward, terminal_state = env.step(state, action)\n \n \n action_seq.append(action)\n reward_seq.append(reward)\n baseline_seq.append(baseline)\n \n return np.array(state_seq), np.array(action_seq), np.array(reward_seq), np.squeeze(np.array(baseline_seq))\n","sub_path":"commnet/commnetlever.py","file_name":"commnetlever.py","file_ext":"py","file_size_in_byte":14075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"483937062","text":"from models import Msg\nfrom django.views.generic import list_detail\nfrom forms import MsgPostForm\nfrom django.http import HttpResponseRedirect\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import get_object_or_404\nfrom django.core.context_processors import csrf\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.utils import simplejson\n\nITEMS_PER_PAGE = 5\n\ndef msg_list_page(request, page):\n #return list_detail.object_list(\n # request,\n #queryset=Msg.objects.order_by('-id'),\n #page=2,\n #paginate_by=ITEMS_PER_PAGE,\n #template_name='msg_list_page.html',\n # template_object_name='msg'\n #)\n page_number = 1;\n \n if request.method == \"POST\":\n page_number = int(request.POST['page']);\n return HttpResponseRedirect('/msg/'+str(page_number)); \n \n def previous_page_number():\n if paginator.num_pages == 0:\n return 0\n elif page_number ==1:\n return 1\n else:\n return page_obj.previous_page_number()\n \n def next_page_number():\n if paginator.num_pages == 0:\n return 0\n elif page_number == paginator.num_pages:\n return paginator.num_pages\n else:\n return page_obj.next_page_number()\n \n def get_msg_list():\n if msg_list:\n return page_obj.object_list\n else:\n return None\n msg_list = Msg.objects.all()\n paginator = Paginator(msg_list,ITEMS_PER_PAGE)\n if page:\n page_number = int(page);\n #else:\n #page_number = 1\n page_obj = paginator.page(page_number)\n c = RequestContext(request, {\n 'msg_list': get_msg_list,\n 'paginator': paginator,\n 'page_obj': page_obj,\n 'is_paginated': page_obj.has_other_pages(),\n 'results_per_page': paginator.per_page,\n 'has_next': page_obj.has_next(),\n 'has_previous': page_obj.has_previous(),\n 'page': page_obj.number,\n 'next': next_page_number(),\n 'previous': previous_page_number(),\n 'first_on_page': page_obj.start_index(),\n 'last_on_page': page_obj.end_index(),\n 'pages': paginator.num_pages,\n 'hits': paginator.count,\n 'page_range': paginator.page_range,\n })\n \n return render_to_response('msg_list_page.html', c)\n\n\n@login_required\ndef msg_post_page(request):\n if request.method == 'POST':\n form = MsgPostForm(request.POST)\n if form.is_valid():\n message = Msg.objects.create(title=form.cleaned_data['title'],content=form.cleaned_data['content'],user=request.user,ip=request.META['REMOTE_ADDR'])\n message.save() \n return HttpResponseRedirect('/msg/') \n else:\n form = MsgPostForm()\n return render_to_response('msg_post_page.html',{'form':form}, context_instance=RequestContext(request))\n \ndef user_msg_list_page(request,username,page):\n user = get_object_or_404(User, username=username)\n #return list_detail.object_list(\n #request,\n #queryset=user.msg_set.order_by('-id'),\n #paginate_by=ITEMS_PER_PAGE,\n #page=2,\n #template_name='user_msg_list_page.html',\n #template_object_name='msg',\n #extra_context={'username':username}\n #)\n\n page_number = 1;\n if page:\n page_number = int(page);\n \n if request.method == \"POST\":\n page_number = int(request.POST['page']);\n return HttpResponseRedirect('/user/'+username+'/'+str(page_number)); \n \n def previous_page_number():\n if paginator.num_pages == 0:\n return 0\n elif page_number ==1:\n return 1\n else:\n return page_obj.previous_page_number()\n \n def next_page_number():\n if paginator.num_pages == 0:\n return 0\n elif page_number == paginator.num_pages:\n return paginator.num_pages\n else:\n return page_obj.next_page_number()\n \n def get_user_msg_list():\n if user_msg_list:\n return page_obj.object_list\n else:\n return None\n \n user_msg_list = user.msg_set.order_by('-id')\n paginator = Paginator(user_msg_list,ITEMS_PER_PAGE) \n \n page_obj = paginator.page(page_number)\n c = RequestContext(request, {\n 'msg_list': get_user_msg_list,\n 'paginator': paginator,\n 'page_obj': page_obj,\n 'is_paginated': page_obj.has_other_pages(),\n 'results_per_page': paginator.per_page,\n 'has_next': page_obj.has_next(),\n 'has_previous': page_obj.has_previous(),\n 'page': page_obj.number,\n 'next': next_page_number(),\n 'previous': previous_page_number(),\n 'first_on_page': page_obj.start_index(),\n 'last_on_page': page_obj.end_index(),\n 'pages': paginator.num_pages,\n 'hits': paginator.count,\n 'page_range': paginator.page_range,\n 'username':username,\n 'user':user\n })\n \n return render_to_response('user_msg_list_page.html', c)\n\ndef user_work_list_page(request, username, page):\n user = get_object_or_404(User, username=username)\n c = RequestContext(request, {\n 'username':username,\n 'user':user\n })\n return render_to_response('user_work_list_page.html',context_instance=RequestContext(request))\n\ndef msg_detail_page(request, message_id): \n msg = get_object_or_404(Msg, id=message_id)\n msg.clickcount += 1\n msg.save()\n return list_detail.object_detail(\n request,\n queryset=Msg.objects.all(),\n object_id = message_id,\n template_name='msg_detail_page.html',\n template_object_name='msg',\n )\n\n@csrf_exempt\ndef autosave(request):\n #response = HttpResponse()\n #response['Content-Type']=\"text/javascript\" \n #title = str(request.POST.get('title'))\n #file = open(\"D:/Workspace/Designer/media/autosave/tmp.txt\",\"w\")\n #file.write(title)\n #file.close()\n #response.write(\"Saved successfully!\")\n #return response;\n info=\" \"\n result = {}\n try:\n if request.method == 'POST':\n req = simplejson.loads(request.raw_post_data)\n if req['action']==\"save\":\n title = req['title']\n file = open(\"D:/Workspace/Designer/media/autosave/tmp.txt\",\"w\")\n file.write(title)\n file.close()\n result['result'] = \"save successfully!\"\n elif req['action']==\"restore\":\n file = open(\"D:/Workspace/Designer/media/autosave/tmp.txt\",\"r\")\n title = file.readline()\n result['result'] = title\n else:\n result['result'] = \"none\"\n except:\n import sys\n info = \"%s || %s\" % (sys.exc_info()[0], sys.exc_info()[1])\n\n result['message']=info\n json=simplejson.dumps(result)\n return HttpResponse(json)\n \n\ndef restore(request):\n result = {}\n file = open(\"D:/Workspace/Designer/media/autosave/tmp.txt\",\"r\")\n title = file.readline()\n result['result'] = title\n json=simplejson.dumps(result)\n return HttpResponse(json)\n \ndef msg_delete(request, id):\n msg=get_object_or_404(Msg,pk=int(id)) \n msg.delete()\n return HttpResponseRedirect('/msg/')","sub_path":"Designer/message/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"404724417","text":"\"\"\"A - Anti-Adjacency\nhttps://atcoder.jp/contests/yahoo-procon2019-qual/tasks/yahoo_procon2019_qual_a\nN K\n\n>>> main(3, 2)\nYES\n>>> main(5, 5)\nNO\n>>> main(31, 10)\nYES\n>>> main(10, 90)\nNO\n\"\"\"\n\n\ndef main(N, K):\n if K * 2 - 1 <= N:\n print(\"YES\")\n else:\n print(\"NO\")\n\n\nif __name__ == \"__main__\":\n N, K = map(int, input().split(\" \"))\n\n main(N, K)\n","sub_path":"others/yahoo-procon2019-qual/yahoo_procon2019_qual_a.py","file_name":"yahoo_procon2019_qual_a.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"646172481","text":"import os\nimport scipy.io\nimport numpy as np\nfrom pathlib import Path\nfrom car import Car\n\n\nclass Data:\n\n\tdef __init__(self):\n\t\tself.__save_train_folder = 'data\\\\train_data'\n\t\tself.__save_test_folder = 'data\\\\test_data'\n\t\tself.__mat_file = 'data\\\\cars_annos.mat'\n\t\tself.__data_label = 'annotations'\n\t\tself.__classes_label = 'class_names'\n\n\t\tself.__max_count = 16185\n\t\tself.__image_count = 3000\n\n\tdef getData(self):\n\t\trelocated = self.checkIfRelocated()\n\t\tif relocated:\n\t\t\treturn self.filterData()\n\t\telse:\n\t\t\treturn self.readFromMatFile()\n\n\n\tdef checkIfRelocated(self):\n\t\treturn Path(self.__save_train_folder).exists() and Path(self.__save_test_folder).exists()\n\n\tdef filterData(self):\n\t\tcars = self.readFromMatFile()\n\t\tfor car in cars:\n\t\t\tcar_relocated = car.checkIfRelocated()\n\t\t\tif car_relocated:\n\t\t\t\tcar.setPath(car.relocationPath())\n\t\treturn cars\n\n\n\tdef readFromMatFile(self):\n\t\tidk = scipy.io.loadmat(self.__mat_file)\n\t\tall_cars = []\n\t\tcars = idk[self.__data_label].tolist()[0]\n\t\tclasses = idk[self.__classes_label].tolist()[0]\n\n\t\ti = 0\n\t\tfor line in cars:\n\t\t\tif i == self.__image_count:\n\t\t\t\tbreak\n\t\t\tpath = \"data/\" + line[0][0]\n\t\t\tx1 = line[1][0][0]\n\t\t\ty1 = line[2][0][0]\n\t\t\tx2 = line[3][0][0]\n\t\t\ty2 = line[4][0][0]\n\t\t\tlabel = line[5][0][0] - 1\n\t\t\tclass_name = classes[label][0]\n\t\t\ttest = False\n\t\t\tif line[6][0][0] == 1:\n\t\t\t\ttest = True\n\n\t\t\tcar = Car(path,x1,y1,x2,y2,label,class_name,test)\n\t\t\tall_cars.append(car)\n\t\t\ti+=1\n\n\t\treturn all_cars\n\n\tdef getRawData(self):\n\t\treturn self.__cars\n\n\n\tdef relocate(self):\n\t\ti = 0\n\t\tfor car in self.__cars:\n\t\t\tcar.relocate()\n\t\t\ti+=1\n\t\t\tprint(\"Images relocated: \",i,\" out of \",self.__image_count)\n\n\tdef getKerasDataset(self):\n\t\tcars_train = []\n\t\tlabels_train = []\n\n\t\tcars_test = []\n\t\tlabels_test = []\n\n\t\ti = 0\n\t\tfor car in self.getData():\n\t\t\tif not car.isTest():\n\t\t\t\tcars_train.append(car.asArray())\n\t\t\t\tlabels_train.append(car.getLabel())\n\t\t\telse:\n\t\t\t\tcars_test.append(car.asArray())\n\t\t\t\tlabels_test.append(car.getLabel())\n\t\t\ti+=1\n\t\t\tprint(\"Images loaded: \",i,\" out of \",self.__image_count)\n\n\t\ttrain = (np.array(cars_train),np.array(labels_train))\n\t\ttest = (np.array(cars_test),np.array(labels_test))\n\n\t\treturn train,test\n\n\n\tdef getTensorflowDataset(self):\n\t\tdef linefy(array):\n\t\t\tline = []\n\t\t\tfor row in array:\n\t\t\t\tfor val in row:\n\t\t\t\t\tline.append(val/255)\n\t\t\treturn line\n\t\tdef oneHot(class_count, label):\n\t\t\tidk = [0 for i in range(class_count)]\n\t\t\tidk[label] = 0\n\t\t\treturn idk\n\n\t\ttrain = []\n\t\ttrain_labels = []\n\t\ttest = []\n\t\ttest_labels = []\n\n\t\ti = 0\n\t\tfor car in self.getData():\n\t\t\tif not car.isTest():\n\t\t\t\ttrain.append(linefy(car.asArray()))\n\t\t\t\ttrain_labels.append(oneHot(196,car.getLabel()))\n\t\t\telse:\n\t\t\t\ttest.append(linefy(car.asArray()))\n\t\t\t\ttest_labels.append(oneHot(196,car.getLabel()))\n\t\t\ti+=1\n\t\t\tprint(\"Images loaded: \",i,\" out of \",self.__image_count)\n\n\t\ttrain = np.array(train)\n\t\ttrain_labels = np.array(train_labels)\n\t\ttest = np.array(test)\n\t\ttest_labels = np.array(test_labels)\n\n\t\treturn (train, train_labels,test,test_labels)\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"91573344","text":"from sklearn import svm, tree\nfrom sklearn.cross_validation import KFold\nfrom sklearn import cross_validation\nfrom sklearn.metrics import confusion_matrix\nimport time\nfrom simplefunctions import avarage_score\n\ndef runsvcn(data,target):\n folds= [4,7,10]\n kernels = ['linear', 'rbf', 'sigmoid']\n print(\"------------ SVM ------------\")\n\n for fold in folds:\n kf = KFold(len(target), n_folds=fold)\n print('fold = %d ' % fold)\n for kernel in kernels:\n kf = KFold(len(target), n_folds=fold)\n svc = svm.SVC(C=1, kernel=kernel)\n\n print(avarage_score([svc.fit(data[train], target[train]).score(data[test], target[test]) for train, test in kf]))\n print(avarage_score(cross_validation.cross_val_score(svc, data, target, cv=kf, n_jobs=-1)))\n\n\ndef runsvc(kernel, data,target,nfolds):\n kf = KFold(len(target), n_folds=nfolds)\n svc = svm.SVC(C=1, kernel=kernel)\n start = time.time()\n ret = (cross_validation.cross_val_score(svc, data, target, cv=kf, n_jobs=-1, ))\n end = time.time()\n\n return ret, (end - start)\n","sub_path":"classifiers/svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"96127332","text":"import random\r\n#diamond = \"d\"\r\n#spade = \"s\"\r\n#heart=\"h\"\r\n#club=\"c\"\r\n\"\"\"\r\nThings I need to implement:\r\n Card ranking to check which hand would win and give the pot to the coresponding player\r\n If every player has folded then the player left wins and give the pot to the coresponding player\r\n Fix a method for all in\r\n Make it that after everyone has bet and you already payed x amount by raising that when you check it doesn't make you pay more\r\n Add an option to either just play one game/round or go until people run out of money\r\n ***Train an Ai dataset by making them play against each other***\r\n ***Make Visual representation and be able to play agaisnt the best Ai***\r\n\r\n\"\"\"\r\nclass Player():\r\n def __init__(self, amount, name):\r\n self.amount = amount\r\n self.name = name\r\n\r\n\r\nplayers = [Player(10000,\"Bob\"), Player(10000,\"Tom\"), Player(10000,\"Tim\")]\r\n\r\n\r\nclass TexasHoldem():\r\n def __init__(self, players):\r\n self.folded_players = []\r\n self.amount_of_players = 0\r\n self.pot = 0\r\n self.curbet = 0\r\n self.turns = 0\r\n self.dealer = None\r\n self.small_blind = None\r\n self.big_blind = None\r\n self.last_turn = None\r\n self.players = {}\r\n self.amounts = {}\r\n self.player_cards = {}\r\n self.blinds = {}\r\n self.cardslist = ['2d', '2s', '2h', '2c', '3d', '3s', '3h', '3c', '4d', '4s', '4h', '4c', '5d', '5s', '5h', '5c', '6d', '6s', '6h', '6c', '7d', '7s', '7h', '7c', '8d', '8s', '8h', '8c', '9d', '9s', '9h', '9c', '10d', '10s', '10h', '10c', 'Jd', 'Js', 'Jh', 'Jc', 'Qd', 'Qs', 'Qh', 'Qc', 'Kd', 'Ks', 'Kh', 'Kc', 'Ad', 'As', 'Ah', 'Ac']\r\n self.newdeck = self.shuffle(self.cardslist)\r\n self.cards = []\r\n self.deck = False\r\n self.game = True\r\n self.first_turn = True\r\n for i in players:\r\n self.amount_of_players += 1\r\n self.players[\"Player{0}\".format(self.amount_of_players)] = i.name\r\n self.amounts[\"Player{0}\".format(self.amount_of_players)] = i.amount\r\n \r\n \r\n if self.first_turn == True:\r\n for key in self.players:\r\n self.deal(key)\r\n if self.amount_of_players == 2:\r\n self.dealer = self.players['Player1']\r\n self.small_blind = self.players['Player1']\r\n self.big_blind = self.players['Player2']\r\n else:\r\n self.small_blind = self.players['Player1']\r\n self.big_blind = self.players['Player2']\r\n \r\n \r\n \r\n \r\n \r\n \r\n def shuffle(self, cards):\r\n random.shuffle(cards)\r\n return cards\r\n \r\n def deal(self, whom):\r\n cards = []\r\n for i in self.newdeck:\r\n cards.append(i)\r\n self.newdeck.remove(i)\r\n break\r\n for i in self.newdeck:\r\n cards.append(i)\r\n self.newdeck.remove(i)\r\n break\r\n self.player_cards[whom] = cards \r\n \r\n def turn(self, whoseturn):\r\n for i in self.folded_players:\r\n if whoseturn == i:\r\n print(\"You Folded\")\r\n return\r\n \r\n \r\n if (self.turns % 4) == 3:\r\n self.curbet = 0\r\n if len(self.cards) == 5:\r\n self.game = False\r\n \r\n if len(self.cards) == 4:\r\n j = 0\r\n for i in self.newdeck:\r\n if j == 1:\r\n break\r\n self.cards.append(i)\r\n self.newdeck.remove(i)\r\n j+= 1\r\n self.turns = 0\r\n\r\n if len(self.cards) == 3:\r\n j = 0\r\n for i in self.newdeck:\r\n if j == 1:\r\n break\r\n self.cards.append(i)\r\n self.newdeck.remove(i)\r\n j+= 1\r\n self.turns = 0\r\n\r\n if len(self.cards) == 0:\r\n j = 0\r\n for i in self.newdeck:\r\n if j == 3:\r\n break\r\n self.cards.append(i)\r\n self.newdeck.remove(i)\r\n j+= 1\r\n self.turns = 0\r\n \r\n \r\n \r\n \r\n#switch order or break after each\r\n\r\n\r\n\r\n \r\n self.print_screen(whoseturn)\r\n if self.first_turn == True:\r\n if self.players[whoseturn] == self.small_blind:\r\n self.bet(whoseturn, 100)\r\n #self.curbet == 100\r\n self.first_turn = True\r\n elif self.players[whoseturn] == self.big_blind:\r\n self.bet(whoseturn, 200)\r\n self.first_turn = False\r\n self.curbet += 200\r\n else:\r\n action = input(\"What Do You Want To Do?(check, raise, fold)\")\r\n if action.lower() == 'check':\r\n if self.curbet < self.amounts[whoseturn]:\r\n self.bet(whoseturn, self.curbet)\r\n self.turns += 1\r\n\r\n else:\r\n print(\"You only have:\" , self.amounts[whoseturn])\r\n\r\n if action.lower() == 'raise':\r\n x = input(\"Enter An Amount You Want To Raise:\")\r\n if (self.curbet + int(x)) < self.amounts[whoseturn]:\r\n self.bet(whoseturn, self.curbet + int(x))\r\n self.curbet += int(x)\r\n self.turns = 0\r\n else:\r\n print(\"You only have:\" , self.amounts[whoseturn])\r\n\r\n if action.lower() == 'fold':\r\n self.folded_players.append(whoseturn)\r\n self.turns += 1\r\n\r\n print(self.turns)\r\n self.check()\r\n self.last_turn == whoseturn\r\n \r\n \r\n def check(self):\r\n #Ace High; 2 pair; Three pair; straight; Flush; Full House; Four of a kind; Straight Flush; Royal Flush\r\n if self.folded_players == self.amount_of_players - 1:\r\n for i in self.players:\r\n if i != self.folded_players:\r\n self.amounts[i] += self.pot\r\n self.pot = 0\r\n\r\n\r\n def final(self):\r\n #for i in player\r\n pass\r\n\r\n\r\n def print_screen(self, whoseturn):\r\n print(\"\\n\",\"CARDS:\",self.cards)\r\n print(\"\\n\")\r\n print(whoseturn, \"\\n\",\"Pot:\",self.pot)\r\n print(\"\\n\")\r\n print(self.player_cards[whoseturn])\r\n print(\"\\n\")\r\n \r\n \r\n \r\n def bet(self, whom, amount):\r\n self.amounts[whom] -= amount\r\n self.pot += amount\r\n \r\n \r\n \r\n def main(self):\r\n #print(self.amount_of_players, self.players, self.amounts)\r\n while self.game == True: \r\n for key in self.players:\r\n self.turn(key) \r\n \r\n #print(self.amounts)\r\n \r\n #print(self.player_cards)\r\n \r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n TexasHoldem(players).main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"604185023","text":"import numpy as np\n\nclass SupportVectorMachine:\n def __init__(self, num_features:int,reg:float):\n self.W = np.random.normal(0,1,(num_features,1))\n self.b = np.random.normal(0,1,1) \n self.reg = reg\n def predict(self, X:np.array):\n raw_score = X@self.W + self.b\n raw_score[raw_score < 0] = -1\n raw_score[raw_score >= 0] = 1\n return raw_score\n\n def evaluate(self, X: np.array, Y: np.array):\n raw_score = X@self.W + self.b\n modulo_case = Y * raw_score\n each_loss = np.zeros(Y.shape)\n each_loss[modulo_case <1 ] = 1 - modulo_case\n\n raw_score[raw_score < 0] = -1\n raw_score[raw_score >= 0] = 1\n loss = self.reg * np.sum(self.W *self.W) + np.sum(each_loss)\n\n accuracy = np.sum(raw_score == Y)/Y.shape[0]\n\n\n return raw_score, loss\n \n \n def train(self, X_train: np.array, Y_train: np.array, X_validate: np.array, Y_validate : np.array, epochs: int = 2000,lr:int = 0.01):\n train_losses, validate_losses = [], []\n for i in range(epochs):\n raw_score = X_train @ self.W + self.b\n modulo_case = Y_train * raw_score\n each_loss = np.zeros(Y_train.shape)\n each_loss[modulo_case <1 ] = 1 - modulo_case\n\n raw_score[raw_score < 0] = -1\n raw_score[raw_score >= 0] = 1\n loss = self.reg * np.sum(self.W *self.W) + np.sum(each_loss)\n train_losses.append(loss)\n validate_scores, validate_loss = evaluate(X_validate, Y_validate)\n validate_losses.append(validate_loss)\n W -= (2*self.reg)*W\n y_train_cpy = np.copy(Y_train)\n y_train_cpy[each_loss == 0] = 0\n X_train_new = np.copy(X_train)\n X_train_new = X_train_new*y_train_cpy\n W += lr*(np.sum(X_train_new,axis = 0) - (2*self.reg)*W)\n\n if i %100 == 0:\n print(f'Losses at step {i}: Train loss: {train_losses[-1]}, Validate Loss : {validate_losses[-1]}')\n \n\n return train_losses, validate_losses\n \n \n pass\n \nclass MultiClassSVM:\n def __init__(self, num_classes:int, num_features:int, reg:float = 2.5e-4, delta: float = 1.0):\n self.W = np.random.normal(0 ,1, (num_features, num_classes))\n self.reg = reg\n self.d = delta\n\n \n def predict(self, X:np.array):\n raw_score = X@self.W\n max_col = np.argmax(raw_score, axis = 1)\n return max_col\n\n def evaluate (self, X: np.array, Y: np.array):\n num_data = X.shape[0]\n num_classes = self.W.shape[1]\n raw_score = X@self.W\n correct_answer_score = np.copy(raw_score[np.arange(num_data), Y])\n max_col = np.argmax(raw_score, axis = 1)\n accuracy = np.sum((max_col == Y))/num_data\n\n loss = raw_score - correct_answer_score[:, np.newaxis] + self.d\n loss[loss< 0 ] = 0 \n loss[np.arange(num_data), Y] = 0\n loss_array = np.copy(loss)\n loss = np.sum(loss)/num_data + self.reg*np.linalg.norm(self.W)**2\n\n return max_col, accuracy, loss, loss_array\n \n def fit(self, X: np.array, Y: np.array, lr :float = 0.001, epochs: int = 1000, batch_size: int = 1024, verbose : bool = True):\n num_data = X.shape[0]\n num_classes = self.W.shape[1]\n train_losses = []\n test_losses = []\n\n\n #-----------Gradient Descent-----------------------\n for i in range(epochs):\n train_loss = 0\n count = 0\n Y_pred_train, acc_train, train_loss,la = self.evaluate(X, Y)\n train_losses.append(train_loss)\n for j in range(0,num_data, batch_size):\n count+= 1\n X_train_svm = X[j:min(j+batch_size,num_data)]\n Y_train_svm = Y[j:min(j+batch_size, num_data)]\n num_samples = X_train_svm.shape[0]\n \n #-------------LR Step------------------------------\n tl, dW = self.svm_vec(X,Y)\n self.W -= lr*dW\n\n #------------Print Loss-----------------------------\n\n if verbose == True:\n print(f\"Epoch {i}: Train loss = {train_loss} , Train accuracy = {acc_train}\")\n if i >2:\n if train_losses[-1] - train_losses[-2] > 1:\n break \n Y_pred_train, acc_train, train_loss,la = self.evaluate(X, Y)\n train_losses.append(train_loss)\n print(f\"Epoch {epochs}: Train loss = {train_loss} , Train accuracy = {acc_train}\")\n return train_losses, self.W\n\n def svm_vec(self, X, y):\n loss = 0.0\n dW = np.zeros(self.W.shape) # initialize the gradient as zero\n num_data = X.shape[0]\n num_classes = self.W.shape[1]\n raw_score = X @ self.W\n correct_answer_score = np.copy(raw_score[np.arange(num_data), y])\n max_col = np.argmax(raw_score, axis = 1)\n accuracy = np.sum((max_col == y))/num_data\n\n loss = raw_score - correct_answer_score[:, np.newaxis] + 1\n loss[loss< 0 ] = 0 \n loss[np.arange(num_data), y] = 0\n loss_array = np.copy(loss)\n loss = np.sum(loss)/num_data + self.reg*np.linalg.norm(self.W)**2\n\n loss_arr = loss_array\n num_xi = np.sum(loss_arr > 0, axis = 1)\n loss_arr[loss_arr > 0] =1 \n val_xi = num_xi[:,np.newaxis] * X\n zeros_arr = np.zeros((num_data,num_classes))\n zeros_arr[np.arange(num_data),y] = 1\n dW = - val_xi.T @ zeros_arr\n dW += X.T @ loss_arr\n dW/= num_data\n dW += 2*self.reg*self.W\n\n return loss, dW\n \n def predict_single(self, x):\n x = x[np.newaxis]\n return self.predict(x)\n\n\n\n ","sub_path":"SVM/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"491847911","text":"\"\"\"\nProject user queries\n\"\"\"\n\nfrom typing import Optional\n\nfrom typeguard import typechecked\n\nfrom ...helpers import Compatible, deprecate, format_result, fragment_builder\nfrom .queries import gql_project_users, GQL_PROJECT_USERS_COUNT\nfrom ...types import ProjectUser\n\n\nclass QueriesProjectUser:\n \"\"\"\n Set of ProjectUser queries\n \"\"\"\n # pylint: disable=too-many-arguments,too-many-locals\n\n def __init__(self, auth):\n \"\"\"\n Initializes the subclass\n\n Parameters\n ----------\n - auth : KiliAuth object\n \"\"\"\n self.auth = auth\n\n # pylint: disable=dangerous-default-value,invalid-name\n @Compatible(['v1', 'v2'])\n @typechecked\n def project_users(self,\n email: Optional[str] = None,\n id: Optional[str] = None, # pylint: disable=redefined-builtin\n organization_id: Optional[str] = None,\n project_id: Optional[str] = None,\n fields: list = ['activated', 'id', 'role',\n 'starred', 'user.email', 'user.id', 'user.name'],\n first: int = 100,\n skip: int = 0):\n # pylint: disable=line-too-long\n \"\"\"\n Return projects and their users (possibly with their KPIs) respecting a set of criteria\n\n Parameters\n ----------\n - email : str, optional (default = None)\n - organization_id : str, optional (default = None)\n - project_id : str, optional (default = None)\n - fields : list, optional (default = ['activated', 'id', 'role', 'starred',\n 'user.email', 'user.id', 'user.name'])\n All the fields to request among the possible fields for the projectUsers.\n See [the documentation](https://cloud.kili-technology.com/docs/python-graphql-api/graphql-api/#projectuser) for all possible fields.\n - first : int, optional (default = 100)\n Maximum number of users to return. Can only be between 0 and 100.\n - skip : int, optional (default = 0)\n Number of project users to skip\n\n Returns\n -------\n - a result object which contains the query if it was successful, or an error message else.\n\n Examples\n -------\n >>> # Retrieve consensus marks of all users in project\n >>> kili.project_users(project_id=project_id, fields=['consensusMark', 'user.email'])\n \"\"\"\n variables = {\n 'first': first,\n 'skip': skip,\n 'where': {\n 'id': id,\n 'project': {\n 'id': project_id,\n },\n 'user': {\n 'email': email,\n 'organization': {\n 'id': organization_id,\n }\n },\n }\n }\n _gql_project_users = gql_project_users(\n fragment_builder(fields, ProjectUser))\n result = self.auth.client.execute(_gql_project_users, variables)\n return format_result('data', result)\n\n # pylint: disable=invalid-name\n @typechecked\n def count_project_users(\n self,\n email: Optional[str] = None,\n id: Optional[str] = None, # pylint: disable=redefined-builtin\n organization_id: Optional[str] = None,\n project_id: Optional[str] = None):\n \"\"\"\n Counts the number of projects and their users respecting a set of criteria\n\n Parameters\n ----------\n - email : str, optional (default = None)\n - organization_id : str, optional (default = None)\n - project_id : str, optional (default = None)\n\n Returns\n -------\n - a positive integer corresponding to the number of results of the query\n if it was successful, or an error message else.\n \"\"\"\n variables = {\n 'where': {\n 'id': id,\n 'project': {\n 'id': project_id,\n },\n 'user': {\n 'email': email,\n 'organization': {\n 'id': organization_id,\n }\n },\n }\n }\n result = self.auth.client.execute(GQL_PROJECT_USERS_COUNT, variables)\n count = format_result('data', result)\n return count\n","sub_path":"kili/queries/project_user/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"592427909","text":"import os\n\nimport time\nfrom keras.layers import LSTM\n\n# Window size or the sequence length\nN_STEPS = 5\n# Lookup step, 1 is the next day\nLOOKUP_STEP = 1\n\n# test ratio size, 0.2 is 20%\nTEST_SIZE = 0.2\n# features to use\nFEATURE_COLUMNS = [\"adjclose\", \"volume\", \"open\", \"high\", \"low\"]\n# date now\ndate_now = time.strftime(\"%Y-%m-%d\")\n\n### model parameters\nN_LAYERS = 5\n# LSTM cell\nCELL = LSTM\n# LSTM neurons\nUNITS = 1024\n# 40% dropout\nDROPOUT = 0.50\n\n### training parameters\n# mean squared error loss\nLOSS = \"mse\"\nOPTIMIZER = \"adam\"\nACTIVATION = 'relu'\nBATCH_SIZE = 32\nEPOCHS = 7\n\n# Stock market ticker symbol (Yahoo)\nTICKER = \"SPY\"\nticker_data_filename = os.path.join(\"data\", f\"{TICKER}_{date_now}.csv\")\n# model name to save\nmodel_name = f\"{date_now}_{TICKER}-{LOSS}-{CELL.__name__}-seq-{N_STEPS}-step-{LOOKUP_STEP}-layers-{N_LAYERS}-units-{UNITS}\"\n","sub_path":"src/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"455905330","text":"from PIL import Image\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\nimport matplotlib.patheffects as patheffects\r\nimport os\r\nfrom os.path import exists, join, basename, splitext\r\nimport json\r\nimport numpy as np\r\nfrom sklearn.metrics import confusion_matrix, classification_report\r\n\r\ndef display(predictions, img_path, coco_path, legend=True, title=True, score_thresh=None):\r\n '''\r\n Function allowing the visualisation of the results\r\n of MMDetection's tool predictions, and the associated\r\n ground-truth. \r\n\r\n Parameters\r\n ----------\r\n predictions : list\r\n Result of mmdet.apis.inference_detector(model, image).\r\n img_path : str\r\n Path to the image.\r\n coco_path : str\r\n Path to the COCO-style annotation file in JSON format.\r\n legend : bool, optional\r\n Set to False to remove the legend (default: True)\r\n title : bool, optional\r\n Set to False to remove title (default: True).\r\n Title is : \"Image : \".\r\n score_tresh : float, optional\r\n Threshold to apply to scores of predictions (default: None).\r\n \r\n Returns\r\n -------\r\n matplotlib.pyplot\r\n\r\n Author\r\n ------\r\n Alexandre Delplanque\r\n '''\r\n\r\n # Ground-truth\r\n with open(coco_path,'r') as json_file:\r\n coco_dic = json.load(json_file)\r\n\r\n labels_dic = coco_dic['categories']\r\n images_dic = coco_dic['images']\r\n ann_dic = coco_dic['annotations']\r\n\r\n cls_names = []\r\n for cls in labels_dic:\r\n cls_names.append(cls['name'])\r\n\r\n for im in images_dic:\r\n if im['file_name']==basename(img_path):\r\n id_img = im['id']\r\n\r\n gt_boxes = []\r\n gt_labels = []\r\n for ann in ann_dic:\r\n if ann['image_id']==id_img:\r\n gt_boxes.append(ann['bbox'])\r\n gt_labels.append(ann['category_id'])\r\n\r\n # Predictions\r\n boxes = []\r\n labels = []\r\n scores = []\r\n for n_class in range(len(cls_names)):\r\n for n_box in range(len(predictions[n_class])):\r\n box = list(predictions[n_class][n_box][:4])\r\n score = predictions[n_class][n_box][4]\r\n boxes.append(box)\r\n labels.append(n_class+1)\r\n scores.append(score)\r\n\r\n predictions = {\r\n 'boxes': boxes,\r\n 'labels': labels,\r\n 'scores': scores\r\n }\r\n\r\n # Threshold des scores\r\n if score_thresh is not None:\r\n\r\n boxes = []\r\n labels = []\r\n scores = []\r\n i = 0\r\n for score in predictions['scores']:\r\n\r\n if score > score_thresh:\r\n\r\n boxes.append(predictions['boxes'][i])\r\n labels.append(predictions['labels'][i])\r\n scores.append(predictions['scores'][i])\r\n\r\n i +=1 \r\n\r\n predictions = {\r\n 'boxes': boxes,\r\n 'labels': labels,\r\n 'scores': scores\r\n }\r\n\r\n # Image\r\n image = Image.open(img_path)\r\n image_name = splitext(basename(img_path))[0]\r\n\r\n # Plot de l'image\r\n fig, ax = plt.subplots(1, figsize=(10,10))\r\n ax.axis('off')\r\n ax.imshow(image)\r\n\r\n # Fonctions\r\n def draw_outline(obj, linewidth):\r\n obj.set_path_effects([patheffects.Stroke(linewidth=linewidth,\r\n foreground='black'),\r\n patheffects.Normal()])\r\n\r\n def draw_text(ax, xy, txt, color, size=11):\r\n text = ax.text(*xy, txt,\r\n horizontalalignment='left',\r\n color=color,\r\n fontsize=size,\r\n weight='bold')\r\n draw_outline(text,1)\r\n\r\n def draw_rect(box, color, linestyle, txt=None):\r\n rect = patches.Rectangle(box[:2],(box[2]-box[0]),(box[3]-box[1]),\r\n linewidth=1.5, edgecolor=color, \r\n linestyle=linestyle,\r\n facecolor='none')\r\n rect = ax.add_patch(rect)\r\n if txt is not None:\r\n draw_text(ax, (box[0],box[1]-2), txt, color)\r\n\r\n # Couleurs\r\n labels_color = ['b','r','c','m','orange','lime','aquamarine','peru','silver']\r\n\r\n # Ajout des boxes de la gt\r\n i = 0\r\n for box in gt_boxes:\r\n label = gt_labels[i]\r\n color = labels_color[label-1]\r\n boxe = [box[0],box[1],box[0]+box[2],box[1]+box[3]]\r\n draw_rect(boxe, color, '-')\r\n i += 1\r\n\r\n # Ajout des boxes prédites\r\n i = 0\r\n color_names = []\r\n for box in predictions['boxes']:\r\n # Couleur bboxe et nom pour légende\r\n label = int(predictions['labels'][i])\r\n color = labels_color[label-1]\r\n name = labels_dic[label-1]['name']\r\n \r\n txt = '{:.2f}'.format(predictions['scores'][i])\r\n draw_rect(box, color, '--', txt)\r\n i += 1\r\n\r\n # Légende = boxes et couleur\r\n if legend == True:\r\n\r\n rect_solid = patches.Rectangle((0,0), 1, 1,linewidth=1,\r\n edgecolor='black',linestyle='-',\r\n facecolor='none')\r\n rect_dashed = patches.Rectangle((0,0), 1, 1,linewidth=1,\r\n edgecolor='black',linestyle='--',\r\n facecolor='none')\r\n extra = patches.Rectangle((0,0), 1, 1,linewidth=1,\r\n edgecolor='none',\r\n facecolor='none')\r\n\r\n rects = [] \r\n for o in range(len(cls_names)):\r\n rect = patches.Rectangle((0,0), 1, 1,linewidth=1,\r\n edgecolor=labels_color[o],\r\n facecolor='none')\r\n rects.append(rect)\r\n\r\n ax.legend([rect_solid, rect_dashed, extra]+rects, \r\n ['Ground-truth','Prediction', '-----------']+cls_names, \r\n bbox_to_anchor=(1.04,1), \r\n fontsize=13)\r\n\r\n # Titre = image\r\n if title == True:\r\n plt.title('Image : {}'.format(image_name), \r\n fontsize=20, weight='bold',pad=15.0)\r\n\r\ndef match(predictions, img_path, coco_path, IoU_tresh, score_thresh=None):\r\n '''\r\n Function used to match the ground-truth bounding boxes \r\n to predicted ones. The outputs are used to construct a\r\n confusion matrix.\r\n\r\n Parameters\r\n ----------\r\n predictions : list\r\n Result of mmdet.apis.inference_detector(model, image).\r\n img_path : str\r\n Path to the image.\r\n coco_path : str\r\n Path to the COCO-style annotation file in JSON format.\r\n IoU_tresh : float\r\n IoU treshold.\r\n score_tresh : float, optional\r\n Threshold to apply to scores of predictions (default: None).\r\n\r\n Returns\r\n -------\r\n 2D list\r\n Matching between gt and predicted bbox\r\n\r\n Author\r\n ------\r\n Alexandre Delplanque\r\n '''\r\n\r\n # Ground-truth\r\n with open(coco_path,'r') as json_file:\r\n coco_dic = json.load(json_file)\r\n\r\n labels_dic = coco_dic['categories']\r\n images_dic = coco_dic['images']\r\n ann_dic = coco_dic['annotations']\r\n\r\n cls_names = []\r\n for cls in labels_dic:\r\n cls_names.append(cls['name'])\r\n\r\n for im in images_dic:\r\n if im['file_name']==basename(img_path):\r\n id_img = im['id']\r\n\r\n gt_boxes = []\r\n gt_labels = []\r\n for ann in ann_dic:\r\n if ann['image_id']==id_img:\r\n box = ann['bbox']\r\n boxes = [box[0],box[1],box[0]+box[2],box[1]+box[3]]\r\n gt_boxes.append(boxes)\r\n gt_labels.append(ann['category_id'])\r\n \r\n gt = {\r\n 'boxes': gt_boxes,\r\n 'labels': gt_labels\r\n }\r\n \r\n # Predictions\r\n boxes = []\r\n labels = []\r\n scores = []\r\n for n_class in range(len(cls_names)):\r\n for n_box in range(len(predictions[n_class])):\r\n box = list(predictions[n_class][n_box][:4])\r\n score = predictions[n_class][n_box][4]\r\n boxes.append(box)\r\n labels.append(n_class+1)\r\n scores.append(score)\r\n\r\n preds = {\r\n 'boxes': boxes,\r\n 'labels': labels,\r\n 'scores': scores\r\n }\r\n\r\n # Threshold des scores\r\n if score_thresh is not None:\r\n\r\n boxes = []\r\n labels = []\r\n scores = []\r\n i = 0\r\n for score in preds['scores']:\r\n\r\n if score > score_thresh:\r\n\r\n boxes.append(preds['boxes'][i])\r\n labels.append(preds['labels'][i])\r\n scores.append(preds['scores'][i])\r\n\r\n i +=1 \r\n\r\n preds = {\r\n 'boxes': boxes,\r\n 'labels': labels,\r\n 'scores': scores\r\n }\r\n\r\n p_boxes = preds['boxes']\r\n\r\n # Calcul des IoU et rangement des résultats dans un tableau\r\n p_index = []\r\n res=[]\r\n i=0\r\n for gt_box in gt['boxes']:\r\n \r\n # Index de la gt box\r\n id_gt = i\r\n\r\n # Label de gt box\r\n gt_label = int(gt['labels'][i])\r\n\r\n # Initialisation du vecteur contenant les IoUs des predictions\r\n p_iou = []\r\n\r\n # S'il n'y a aucune bbox prédite => FN\r\n if len(p_boxes)==0:\r\n res.append([i, gt_label, int(0), int(0), int(0)])\r\n continue\r\n\r\n for p_box in p_boxes:\r\n \r\n # Détermination des coord. (x,y) de l'intersection\r\n xA = max(gt_box[0],p_box[0])\r\n yA = max(gt_box[1],p_box[1])\r\n xB = min(gt_box[2],p_box[2])\r\n yB = min(gt_box[3],p_box[3])\r\n\r\n # Aire de cette intersection\r\n area = max(0, xB - xA +1) * max(0, yB - yA +1)\r\n\r\n # Aires de la GT et de la pred\r\n area_gt = (gt_box[2] - gt_box[0] + 1) * (gt_box[3] - gt_box[1] + 1)\r\n area_p = (p_box[2] - p_box[0] + 1) * (p_box[3] - p_box[1] + 1)\r\n\r\n # Calcul de l'IoU\r\n IoU = area / float(area_gt + area_p - area)\r\n\r\n # Ajout au vecteur des IoU des preds\r\n p_iou.append(IoU)\r\n\r\n # Index de l'objet de correspondance. On prend l'IoU max \r\n # (correspondance maximale avec la GT).\r\n p_iou_max = float(max(p_iou))\r\n index = p_iou.index(p_iou_max)\r\n\r\n p_index.append(index)\r\n \r\n # Si l'IoU est trop faible, considéré comme background (FN)\r\n if p_iou_max < IoU_tresh:\r\n p_label = int(0)\r\n else:\r\n p_label = int(preds['labels'][index])\r\n\r\n res.append([id_gt, gt_label, index, p_label, p_iou_max])\r\n\r\n i += 1\r\n\r\n # Index de p_boxes sans correspondance avec la gt (FP) = p_not_used\r\n if len(p_boxes) > len(gt['boxes']):\r\n p_index_unique = np.unique(p_index)\r\n p_boxes_index = list(range(len(p_boxes)))\r\n\r\n # On retire les index rencontrés, il reste ceux sans correspondance\r\n p_not_used = [item for item in p_boxes_index if item not in p_index_unique]\r\n\r\n # Ajout à la variable res\r\n for k in range(len(p_not_used)):\r\n new_index = p_not_used[k]\r\n label = int(preds['labels'][new_index])\r\n res.append([i, int(0), new_index, label, int(0)])\r\n i += 1\r\n\r\n matching = np.array(res)\r\n matching = np.delete(matching, [0,2,4], 1)\r\n\r\n return matching \r\n\r\ndef matrix(match, class_names):\r\n '''\r\n Function used to create a confusion matrix, based\r\n on 2D matching numpy array betwen ground-truth and\r\n predictions.\r\n\r\n See sklearn.metrics.confusion_matrix\r\n\r\n Parameters\r\n ----------\r\n match : np.array\r\n 2D numpy array, with ground-truth labels in\r\n column 1 and predictions labels in column 2.\r\n class_names : list of str\r\n List of labels names, including 'Background' string\r\n in first position.\r\n Warning : Order need to be respected!\r\n \r\n Returns\r\n -------\r\n Dict\r\n Confusion matrix with labels name.\r\n \r\n Author\r\n ------\r\n Alexandre Delplanque\r\n '''\r\n\r\n truth = match[:,0]\r\n predicted = match[:,1]\r\n\r\n labels = list(set(np.concatenate((truth,predicted),axis=0)))\r\n labels = [int(lab) for lab in labels]\r\n\r\n matrix = confusion_matrix(truth, predicted, labels=labels)\r\n \r\n print(matrix)\r\n \r\n i = 0\r\n j = 0\r\n confusion_matrix = {}\r\n for name in class_names:\r\n dic = {name : {}}\r\n for name_bis in class_names:\r\n dic[name].update({name_bis : float(matrix[i][j])})\r\n confusion_matrix.update(dic)\r\n j += 1\r\n j = 0\r\n i += 1\r\n \r\n return confusion_matrix\r\n\r\ndef report(match, coco_path):\r\n '''\r\n Function used to create a report with calculation \r\n of precision, recall and F1-score for each class \r\n and the weighted average of each of these metrics.\r\n\r\n See sklearn.metrics.classification_report\r\n\r\n Parameters\r\n ----------\r\n match : np.array\r\n 2D numpy array, with ground-truth labels in\r\n column 1 and predictions labels in column 2.\r\n coco_path : str\r\n Path to the COCO-style annotation file in JSON \r\n format.\r\n Warning: Labels in match need to match id in\r\n annotation file (cf. 'categories' dict)!\r\n\r\n Returns\r\n -------\r\n print\r\n dict\r\n\r\n Author\r\n ------\r\n Alexandre Delplanque\r\n '''\r\n\r\n with open(coco_path,'r') as json_file:\r\n coco_dic = json.load(json_file)\r\n\r\n truth = match[:,0]\r\n predicted = match[:,1]\r\n\r\n labels = list(set(np.concatenate((truth,predicted),axis=0)))\r\n labels = [int(lab) for lab in labels]\r\n\r\n categories = coco_dic['categories']\r\n\r\n i = 0\r\n classes = ['Background']\r\n for lab in labels[1:]:\r\n if categories[i]['id']==lab:\r\n classes.append(categories[i]['name'])\r\n\r\n i += 1\r\n\r\n print(classification_report(truth, predicted, labels=labels, target_names=classes, digits=2))\r\n \r\n out = classification_report(truth, predicted, \r\n labels=labels, \r\n target_names=classes, \r\n digits=2, \r\n output_dict=True)\r\n return out\r\n","sub_path":"Post-processing/mmdet_utils.py","file_name":"mmdet_utils.py","file_ext":"py","file_size_in_byte":14134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"521574849","text":"from PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom source import source\nfrom analyze import analyze\nimport math\nimport time\nfrom threadings import Tnuls\nimport threading \n\nclass Window(QMainWindow):\n def __init__(self):\n super(Window, self).__init__()\n self.initUI()\n self.ename=\"\"\n self.aly=analyze()\n self.classlist=[]\n self.count=0\n self.datasum=0\n self.scalelist=[]\n self.doing=0\n self.bestlist=[]\n self.catch_time=0\n self.second=0\n self.isdeep_ay=False\n self.all_result={}\n self.all_rscale={}\n self.zu_name=[]\n self.zu_namel=[]\n self.ze_Ewage={}\n self.deep_state=0\n self.colors=[Qt.red, QColor(100, 10, 50, 255), Qt.green, Qt.yellow,Qt.gray,QColor(100, 100, 0, 255),QColor(100, 10, 20, 255),QColor(0, 100, 40, 255) ,QColor(0, 30, 140, 255) , Qt.yellow, Qt.green, Qt.black, Qt.blue, Qt.red]\n def initUI(self): \n self.setGeometry(35, 35, 1300, 670)\n def paintEvent(self,event):\n pt=QPainter(self)\n pt.begin(self)\n side=min(self.width(),self.height())\n #获取当前时间\n currentTime=QTime().currentTime()\n currentsecond=currentTime.second()\n w=(5*side)/13\n x=475/871*source.ui.groupBox_show.width()\n y=65/631*source.ui.groupBox_show.height()\n ax=102/871*source.ui.groupBox_show.width()\n ay=40/631*source.ui.groupBox_show.height()\n # if len(self.bestlist)>0:\n self.drawRect(pt,self.width(), self.height(), QColor(10, 40, 50, 255))#------------\n \n if not self.isdeep_ay:\n self.show_bestlist(pt,self.bestlist, x-200, y+100, w-40, w+300)\n for i in range(4):#len(self.classlist)\n #self.drawclock(pt, x, y, w, w, i)\n if i==0 and len(self.classlist)>0:\n self.drawclock(pt, x-20, y, w, w, 0)\n if i==1 and len(self.classlist)>1:\n self.drawclock(pt, x+w+ax, y, w, w, 1)\n if i==2 and len(self.classlist)>2:\n self.drawclock(pt, x-20, y+w+ay, w, w, 2)\n if i==3 and len(self.classlist)>3:\n self.drawclock(pt, x+w+ax, y+w+ay, w, w, 3)\n else:\n if self.deep_state==1:\n self.draw_pillar(pt,self.zu_name, self.all_rscale, self.zu_namel)\n if self.deep_state==2:\n self.draw_brline(pt,self.zu_name, self.all_result, self.zu_namel)\n pt.end()\n \n if source.isbigan:\n if self.second==59:\n self.second=0\n if self.second0:\n self.datasum=len(self.classlist)\n self.count=source.Erealdata[self.ename][0]\n if num 70:\n y2=y2-10\n if x2 < 30:\n x2=x2+20\n else:\n if x2< 30:\n x2=x2+20\n pen=QPen(color, lw, Qt.SolidLine)\n qp.setPen(pen)\n qp.drawLine(x1, y1, x2, y2)\n def draw_text(self, painter, font, text, x=0, y=0, color=Qt.white):\n painter.setPen(QPen(color,1.5))\n painter.setFont(font)\n painter.drawText(x, y, text)\n def drawRect(self, pt, w, h, color=QColor(50, 100, 200, 255), x=0, y=0):\n #pen1=QPen(QColor(225, 0, 225, 225))\n #rec=QRect(500, 500,500, 500)\n #pt.setPen(pen1)\n #pt.drawRect(rec)\n pt.setBrush(color)\n pt.drawRect(x, y, w, h)\n def show_bestlist(self, painter,bestlist, x=250, y=30, w=100, h=100):\n painter.setRenderHint(QPainter.Antialiasing)\n painter.setViewport(x,y,w,h)\n #设置QPainter的坐标系统,无论窗体大小如何变化,\n #窗体左上坐标为(0,0),右下坐标为(100,100),\n #因此窗体中心坐标为(50,50)\n painter.setWindow(0,0,60,200)\n font=QFont(\"Times\",5)\n i=0\n tw=0\n self.draw_text(painter, font,\"最佳组合:\",0 , tw-8)\n font=QFont(\"Times\",4)\n for text in bestlist:\n tw=tw+5*i\n self.draw_text(painter, font,text,0, tw)\n i=1+1\n def ui_settext(self, text, num, painter):\n font=QFont(\"Times\",6)\n self.draw_text(painter, font,text,0, 0)\n def ui_autolocation(self):\n source.ui.frame_ay.setGeometry(QRect(0, 0, self.width(), self.height()))\n source.ui.pushButton_bigin.setGeometry(QRect(self.width()/15,self.height()*11/67, self.width()*7/60, self.height()*51/670))\n source.ui.pushButton_show.setGeometry(QRect(self.width()/15, self.height()*22/67, self.width()*47/400, self.height()*51/670))\n source.ui.comboBox.setGeometry(QRect(self.width()/40, self.height()*17/67, self.width()*77/400,self.height()*47/670))\n source.ui.pushButton_back.setGeometry(QRect(self.width()*1180/1300, self.height()*20/670, self.width()*91/1300, self.height()*41/670))\n source.ui.groupBox_show.setGeometry(QRect(self.width()*3/13, self.height()*2/70, self.width()*890/1200, self.height()*645/670))\n source.ui.groupBox.setGeometry(QRect(self.width()/60, self.height()*29/67, self.width()*281/1300, self.height()*361/670))\n source.ui.textEdit_get.setGeometry(QRect(self.width()/60, self.height()*4/67, self.width()*241/1300, self.height()*301/670))\n source.ui.comboBox_2.setGeometry(QRect(self.width()/40, self.height()*6/67, self.width()*77/400, self.height()*41/670))\n source.ui.label.setGeometry(QRect(self.width()/40, self.height()*2/67, self.width()*61/1300, self.height()*31/670))\n source.ui.label_getstatus.setGeometry(QRect(self.width()*3/40, self.height()*2/67, self.width()/4, self.height()*31/670))\n def get_textpoint(self, hyangle, angle, length=60, state=1):\n cangle=hyangle+(angle-hyangle)/2\n angleR=self.location(cangle)\n cangle=angleR[1]/360*(2*3.14)\n point={\"x\":0, \"y\":0}\n x=math.cos(cangle)*length\n y=math.sin(cangle)*length\n if angleR[0]==90:\n point[\"x\"]=50+25\n point[\"y\"]=50\n if angleR[0]==180:\n point[\"x\"]=50\n point[\"y\"]=50+25\n if angleR[0]==270:\n point[\"x\"]=50-25\n point[\"y\"]=50\n if angleR[0]==360:\n point[\"x\"]=50\n point[\"y\"]=50-25\n if angleR[0]==1:\n point[\"y\"]=50-y\n point[\"x\"]=50+x\n if angleR[0]==2: \n point[\"x\"]=50+x\n point[\"y\"]=50+y\n if angleR[0]==3:\n point[\"y\"]=50+y\n if state==1:\n point[\"x\"]=35-x\n else:\n point[\"x\"]=50-x\n if angleR[0]==4:\n point[\"y\"]=50-y\n if state==1:\n point[\"x\"]=35-x\n else:\n point[\"x\"]=50-x\n return point\n def location(self, angle):\n angleR=[]\n if angle==40:\n angleR=[90, 0]\n if angle==310:\n angleR=[360, 0]\n if angle==130:\n angleR=[180, 0]\n if angle==220:\n angleR=[270, 0]\n if angle>-50 and angle<40:\n angleR=[1,40-angle]\n if angle>310 and angle<400:\n angleR=[1,400-angle]\n if angle>40 and angle<130:\n angleR=[2,angle-40]\n if angle>130 and angle<220:\n angleR=[3,220-angle]\n if angle>220 and angle <310:\n angleR=[4,angle-220]\n return angleR\n def getdata(self):\n ename=source.ui.comboBox.currentText ()\n if not ename==\"请选择要分析的工程师\":\n self.ename=ename\n classlist=self.aly.select_all(ename)\n if not classlist==\"error\" and len(classlist)>0:\n self.classlist=classlist\n self.bestlist=self.aly.getbest(classlist, ename)\n self.count=0\n self.datasum=0\n self.scalelist=[]\n #-----------------------------------------------------------------------------------------#\n def draw_pillar(self, painter, xy_name=[\"y\", \"x\"], result_list={}, namel=[] , x1=200, y1= 150, x2=200, y2=550, x3=1100, y3=550):\n x1=x1*self.width()/1300\n y1=y1*self.height()/670\n x2=x2*self.width()/1300\n y2=y2*self.height()/670\n x3=x3*self.width()/1300\n y3=y3*self.height()/670\n self.draw_Lines(painter,x1,y1 ,x2 , y2, Qt.black)\n self.draw_Lines(painter, x2, y2,x3 ,y3 , Qt.black)\n font=QFont(\"Times\",12)\n self.draw_text(painter, font,xy_name[0] , x1+5, y1)\n self.draw_text(painter, font, xy_name[1], x3, y3-5)\n xt=1100*self.width()/1300\n yt=90*self.height()/670\n w1=(x3-x2)/(len(namel)+2)\n w=w1*2/3\n xn=x2\n d=20\n i=0\n for name in namel:\n h=result_list[name]*float(y2-y1)*2\n xn=xn+w1\n yn=y2-h\n self.drawRect(painter, w, h,self.colors[i], xn, yn )\n strscal= str(\"%.2f\" % (result_list[name]*100))+\"%\"\n if name==self.ename:\n strscal=strscal+\"***\"\n self.draw_text(painter,font,strscal, xn, yn-20)\n i=i+1\n self.draw_text(painter, font, str(i), xn+10, yn+h+d)\n self.draw_text(painter, font, name, xt, yt)\n self.drawRect(painter, 40, 15, self.colors[i-1], xt-50, yt-15)\n yt=yt+30\n if name==self.ename:\n scale=str(\"%.2f\" % (result_list[name]*100)+\"%\")\n if not self.ename==\"\":\n rank=self.get_rank(result_list, self.ename, namel)\n text0=self.ename+source.deep_zuay[0]+scale+source.deep_zuay[1]+str(rank)+source.deep_zuay[2]\n self.draw_text(painter,font, text0, x1+100, y1-100)\n if rank<4:\n text1=source.deep_zuay1[0]\n if rank>3 and rank<7:\n text1=source.deep_zuay1[1]\n if rank>6 and rank<10:\n text1=source.deep_zuay1[2]\n self.draw_text(painter,font, text1, x1+80, y1-80)\n def get_rank(self, resultlist, name, namel):\n rank=1\n s0=resultlist[name]\n for n in namel:\n if resultlist[n]>s0:\n rank=rank+1\n return rank\n def draw_Lines(self, qp, x1, y1, x2, y2, color=Qt.black, lw=2):\n pen=QPen(color, lw, Qt.SolidLine)\n qp.setPen(pen)\n qp.drawLine(x1, y1, x2, y2)\n \n def draw_brline(self , painter, xy_name=[\"y\", \"x\"], result_list={}, namel=[] , x1=200, y1= 80, x2=200, y2=480, x3=1100, y3=480):\n x1=x1*self.width()/1300\n y1=y1*self.height()/670\n x2=x2*self.width()/1300\n y2=y2*self.height()/670\n x3=x3*self.width()/1300\n y3=y3*self.height()/670\n xt=1100*self.width()/1300\n yt=90*self.height()/670\n self.draw_Lines(painter,x1,y1 ,x2 , y2, Qt.black)\n self.draw_Lines(painter, x2, y2,x3 ,y3 , Qt.black)\n font=QFont(\"Times\",12)\n self.draw_text(painter, font,xy_name[0] , x1+5, y1)\n self.draw_text(painter, font, xy_name[1], x3, y3-5)\n #---\n w=(x3-x2)/(len(source.deep_years))\n xn=x2\n \n for year in source.deep_years:\n self.draw_text(painter,font, year,xn-5, y2+20)\n self.draw_Lines(painter, xn,y2-5, xn, y2 , Qt.black)\n xn=xn+w\n \n wg=(source.deep_wages[1])/10\n wage=int(wg)\n wh=(y2-y1-50)/10\n wyh=wh\n self.draw_text(painter,font, \"0\",x2-50, y2)\n for i in range(10):\n self.draw_text(painter,font, str(int(wage)),x2-50, y2-wyh)\n self.draw_Lines(painter, x1,y2-wyh, x1+5, y2-wyh , Qt.black)\n wage=wage+wg\n wyh=wyh+wh\n i=0\n add=50\n xb=x2-100\n for name in namel:\n xw0=x2\n xw1=x2\n yw0=0\n yw1=0\n result=result_list[name]\n self.draw_Lines(painter, xb-50,y2+50, xb-50, y2+185 , Qt.black)\n self.draw_Lines(painter, xb-30,y2+add+7, xb+40, y2+add+7 , self.colors[i])\n self.draw_Lines(painter, xb+60,y2+50, xb+60, y2+185 , Qt.black)\n lw=2\n if name==self.ename:\n lw=6\n for rwge in result:\n yw1=y2-rwge*(y2-y1-50)/source.deep_wages[1]\n if not xw0==xw1:\n self.draw_Lines(painter, xw0,yw0, xw1, yw1 , self.colors[i], lw)\n self.draw_Lines(painter, xw1+60,y2+50, xw1+60, y2+185 , Qt.black)\n self.draw_text(painter,font, str(rwge),xw1-10, y2+add+13)\n xw0=xw1\n xw1=xw1+w\n yw0=yw1\n self.draw_Lines(painter, x3,y2+50, x3, y2+185 , Qt.black)\n \n self.draw_Lines(painter, xb-50,y2+add, x3, y2+add , Qt.black)\n add=add+15\n \n #------------------------------------------------------------------------------------- \n self.draw_text(painter, font, name, xt, yt)\n self.drawRect(painter, 40, 10, self.colors[i], xt-50, yt-15)\n self.draw_Lines(painter, xt-50,yt, xt-10, yt , self.colors[i])\n yt=yt+30\n i=i+1\n self.draw_Lines(painter, xb-50,y2+add, x3, y2+add , Qt.black)\n #----------------------\n self.drawRect(painter, 40, 10, self.colors[0], xt-50, yt+50)\n self.draw_text(painter,font, \"平均工资\",xt, yt+50)\n self.draw_Lines(painter, xt-50,yt+80, xt-10, yt+80 , self.colors[0])\n self.draw_text(painter,font, \"工龄工资\",xt, yt+80)\n #self.draw_pillar(painter,self.zu_name, self.ze_Ewage, self.zu_namel, x1, y1, x2, y2, x3, y3)\n if len(self.ze_Ewage)>0:\n w1=(x3-x2)/(len(namel)+2)\n w=w1*2/3\n xn=x2\n d=40\n i=0\n for name in namel:\n h=self.ze_Ewage[name]*(y2-y1-50)/source.deep_wages[1]\n xn=xn+w1\n yn=y2-h\n self.drawRect(painter, w, h,self.colors[i], xn, yn )\n tw=str(self.ze_Ewage[name])\n i=i+1\n ti=str(i)\n if name==self.ename:\n tw=tw+\"***\"\n ti=ti+\"***\"\n self.draw_text(painter,font,tw , xn, yn-20)\n self.draw_text(painter, font, ti, xn+10, yn+h+d)\n #-----------------------------------------------------------------------------------------#\n def ui_clear(self):\n source.ui.pushButton_bigin.close()\n source.ui.pushButton_show.close()\n source.ui.comboBox.close()\n source.ui.groupBox_show.close()\n source.ui.groupBox.close()\n source.ui.textEdit_get.close()\n source.ui.comboBox_2.close()\n source.ui.label.close()\n source.ui.label_getstatus.close()\n def ui_reshow(self):\n source.ui.frame_ay.close()\n source.ui.pushButton_bigin.show()\n source.ui.pushButton_show.show()\n source.ui.comboBox.show()\n source.ui.groupBox_show.show()\n source.ui.groupBox.show()\n source.ui.textEdit_get.show()\n source.ui.comboBox_2.show()\n source.ui.label.show()\n source.ui.label_getstatus.show()\n self.isdeep_ay=False\n #-----------------------------------------------------------------------------------------#\n def deep_ay(self):\n self.ui_clear()\n source.ui.frame_ay.show()\n self.isdeep_ay=True\n if self.deep_state==0:\n self.hengxiang()\n def hengxiang(self):\n self.all_result=self.aly.get_alldata()\n for n in source.enginename:\n scale=self.aly.get_allscale(n)\n self.all_rscale[n]=scale\n self.zu_namel=source.enginename\n self.zu_name=[\"比例%\", \"工程师\"]\n self.deep_state=1\n def duibi_hx(self):\n self.deep_state=1\n self.zu_name=[\"比例%\", \"工程师\"]\n \n self.deep_state=1\n self.update()\n def duibi_zx(self):\n self.deep_state=2\n self.all_result=source.deep_engwages\n self.zu_name=[\"薪资\", \"工龄\"]\n self.ze_Ewage=self.aly.get_wages()\n self.update()\n def duibi_nl(self):\n self.deep_state=3\n self.update()\n def bigin_click(self):\n if not source.isbigan:\n self.second=0\n if source.ui.comboBox_2.currentText ()==\"58同城\":\n t=Tnuls(0)\n t.start()\n source.isbigan=True\n if source.ui.comboBox_2.currentText ()==\"中华英才网\":\n t=Tnuls(1)\n t.start()\n source.isbigan=True\n if source.ui.comboBox_2.currentText ()==\"智联招聘\":\n t=Tnuls(2)\n t.start()\n source.isbigan=True\n if source.ui.comboBox_2.currentText ()==\"猎聘猎头网\":\n t=Tnuls(3)\n t.start()\n source.isbigan=True\n if source.ui.comboBox_2.currentText ()==\"卓博人才网\":\n t=Tnuls(4)\n t.start()\n source.isbigan=True\n if source.ui.comboBox_2.currentText ()==\"前程无忧\":\n t=Tnuls(5)\n t.start()\n source.isbigan=True\n \n if source.isbigan:\n self.catch_time=0\n t1 = threading.Thread(target=self.threadcl) #创建第一个子线程,子线程的任务\n t1.setDaemon(True)\n t1.start()\n self.update()\n \n def show_click(self):\n self.getdata()\n self.setUpdatesEnabled(False);\n self.setUpdatesEnabled(True);\n self.repaint();\n if len(self.bestlist)>0:\n bestlist=self.bestlist\n antext=source.Eanalyze[source.ui.comboBox.currentText ()]\n analyze_text=self.set_ayetext(antext, self.ename, bestlist)\n \n source.ui.textEdit_get.setText(analyze_text)\n def set_ayetext(self, antext, name, bestlist):\n analyze_text=\"\"\n if name==\"1.嵌入式软件工程师\":\n analyze_text=antext[0]+bestlist[4]+antext[1]+bestlist[0]+antext[2]+bestlist[1]+antext[3]+bestlist[2]+antext[4]+bestlist[3]+antext[5]\n return analyze_text\n if name==\"2.JAVA软件工程师\":\n b=bestlist[3]\n bestlist[3]=bestlist[4]\n bestlist[4]=b\n for i in range(len(antext)):\n analyze_text=analyze_text+antext[i]\n if i800:\n time.sleep(0.3)\n '''\n while source.isbigan:\n time.sleep(1)\n if source.threadnum<1:\n source.isgetweb=True\n source.isbigan=False\n # database.close()#关闭数据库\n source.close_txt()\n source.copy_txt()\n \n","sub_path":"spider-engineer/ui_paint.py","file_name":"ui_paint.py","file_ext":"py","file_size_in_byte":24984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"67963655","text":"# -*- coding=utf-8 -*-\n# Author: zipxing@hotmail.com, zhouhao@tuyoogame.com\n# Created: 2015.3.28\n\nimport functools\nimport inspect\nimport time\nimport uuid\nfrom contextlib import contextmanager\nfrom functools import wraps\n\nimport stackless\n\nimport freetime.util.log as ftlog\nfrom freetime.aio.redis import doRedis\n\n\nclass FTLock(stackless.channel):\n def __init__(self, lockkey, relockKey=None):\n stackless.channel.__init__(self)\n self.lockkey = lockkey\n self._islock = False\n self._fttask = None\n self.relock = 0\n self.relockKey = relockKey\n\n def lock(self, relockKey=None):\n if self._islock == True:\n if self._fttask == stackless.getcurrent():\n self.relock += 1\n return\n if self.relockKey != None and self.relockKey == relockKey:\n self.relock += 1\n return\n self.receive()\n self._islock = True\n self._fttask = stackless.getcurrent()\n\n def unlock(self):\n if self.relock > 0:\n self.relock -= 1\n return 1\n self._fttask = None\n self._islock = False\n if self.balance < 0:\n self.send(0)\n return 1\n return 0\n\n\ndef locked(func):\n '''Decorator of object locker \n only used for object method\n \n e.g :\n \n class Room(object) : \n def __init__(self):\n self.locker = FTLock(self.__class__.__name__ + \"_%d\" % id(self))\n \n @locked\n def syncChooseTableAndSit(self, userId):\n pass\n '''\n\n @wraps(func)\n def syncfunc(*args, **argkw):\n objself = args[0]\n if not hasattr(objself, 'locker'):\n objself.locker = FTLock(objself.__class__.__name__ + \"_%d\" % id(objself))\n\n with lock(objself.locker):\n ftlog.debug(\"locked func:\", func.__name__)\n return func(*args, **argkw)\n\n return syncfunc\n\n\n@contextmanager\ndef lock(locker):\n '''e.g.\n with lock(room.locker) :\n ...\n '''\n ftlog.debug(\"locker %s isLocked:%s\" % (locker.lockkey, locker._islock))\n locker.lock()\n try:\n ftlog.debug(\"locker %s locked\" % (locker.lockkey))\n yield\n except:\n raise\n finally:\n ftlog.debug(\"locker %s unlock\" % (locker.lockkey))\n locker.unlock()\n\n\nclass FTRedLockException(Exception):\n pass\n\n\nclass FTRedLock:\n UNLOCK_LUA = '''if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n return redis.call(\"del\",KEYS[1])\n else\n return 0\n end\n '''\n UNLOCK_SHA = None\n\n def __init__(self, lockname, timeout=150.0):\n self.lockname = lockname\n self.timeout = timeout\n self._fttask = None\n self._random = ''\n self._islock = 0\n\n def lock(self):\n self._fttask = stackless.getcurrent()._fttask\n _start = time.time()\n self._random = str(uuid.uuid4())\n while True:\n if FTRedLock.UNLOCK_SHA == None:\n FTRedLock.UNLOCK_SHA = doRedis('locker', 'SCRIPT', 'load', FTRedLock.UNLOCK_LUA)\n ret = doRedis('locker', 'SET', self.lockname, self._random, 'NX', 'PX', int(self.timeout * 1000))\n if ret:\n self._islock = 1\n return True\n else:\n self._fttask.sleepNb(0.05)\n if time.time() - _start > self.timeout:\n raise FTRedLockException('lock timeout of ' + str(self.lockname))\n\n def unlock(self):\n if self._islock:\n doRedis('locker', 'EVALSHA', FTRedLock.UNLOCK_SHA, 1, self.lockname, self._random)\n self._islock = 0\n\n\ndef ftredlock(lock_name_head, lock_name_tails=[], timeout=150.0):\n '''Decorator of FTRedLock \n \n e.g : \n @ftredlock('table_data_lock', ['gameid', 'roomid', 'tableid'], 3.0)\n def syncChooseTableAndSit(self, gameid, roomid, tableid, userid):\n '''\n assert (isinstance(lock_name_head, (str, unicode)))\n assert (isinstance(lock_name_tails, (list, tuple)))\n assert (isinstance(timeout, (int, float)))\n\n def decorating_function(method):\n _timeout = timeout\n _lock_name_head = lock_name_head\n _lock_param_indexs = []\n\n paramkeys, _, __, ___ = inspect.getargspec(method)\n for lname in lock_name_tails:\n i = -1\n for x in xrange(len(paramkeys)):\n if lname == paramkeys[x]:\n i = x\n break\n if i >= 0:\n _lock_param_indexs.append(i)\n else:\n raise FTRedLockException('can not find the param name of :' + lname)\n\n @functools.wraps(method)\n def funwarp(*args, **argd):\n locker_name = _lock_name_head\n for i in _lock_param_indexs:\n locker_name = locker_name + ':' + str(args[i])\n locker = FTRedLock(locker_name, _timeout)\n try:\n locker.lock()\n return method(*args, **argd)\n finally:\n locker.unlock()\n\n return funwarp\n\n return decorating_function\n","sub_path":"source/freetime/freetime/core/lock.py","file_name":"lock.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"282814966","text":"from fsdk import FSDK\nimport os\nimport pickle\nimport ctypes\nfrom functions import numpy_to_image, image_to_byte_array\nimport asyncio\nimport cv2\nimport logging\nlogging.basicConfig(filename='fr.log', level=logging.DEBUG)\n\nfrom functions import ctype_from_bytes\n\n\ndef save_templates(db_path, templates):\n with open(os.path.join(db_path, 'templates.pkl'), 'wb') as handle:\n pickle.dump(templates, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef save_directory(db_path, templates):\n with open(os.path.join(db_path, 'templates.pkl'), 'wb') as handle:\n pickle.dump(set(templates.keys()), handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\ndef load_templates(db_path):\n return pickle.load(open(os.path.join(db_path, 'templates.pkl'), 'rb'))\n\n\ndef load_directory(db_path):\n return pickle.load(open(os.path.join(db_path, 'directory.pkl'), 'rb'))\n\n\ndef to_ctype(data):\n return data.ctypes.data_as(ctypes.POINTER(FSDK.FaceTemplate)).contents\n\n\ndef init(license_):\n try:\n FSDK.ActivateLibrary(open(license_).read())\n print(FSDK.GetLicenseInfo())\n except Exception as e:\n print(f'Lincense error: {e}')\n exit()\n\n FSDK.Initialize()\n\n\ndef compare_faces(img_1, img_2):\n return FSDK.MatchFaces(img_1, img_2)\n\n\ndef image_from_jpg(buffer):\n return FSDK.LoadImageFromJpegBuffer(buffer)\n\n\ndef get_face_template(img):\n return FSDK.GetFaceTemplate(img)\n\n\ndef get_faces(img):\n return img.DetectMultipleFaces()\n\n\ndef init_video(license_, **kwargs):\n init(license_)\n tracker = FSDK.Tracker() # creating a FSDK Tracker\n tracker.SetParameters(**kwargs)\n return tracker\n\n\nasync def find_from_video(img, templates, mode='all', threshold=0.90):\n faces = get_faces(img)\n for face in faces:\n tmp = FSDK.GetFaceTemplateInRegion(img, face)\n for name, features in templates.items():\n similarity = FSDK.MatchFaces(tmp, to_ctype(features))\n # print(similarity)\n if similarity > threshold:\n print(img, name, similarity)\n # if mode\n tmp.Free()\n img.Free()\n\n\ndef close():\n FSDK.Finalize()\n\n\ndef close_video(tracker):\n # tracker.SaveToFile(os.path.join(db_path, 'tracker_memory.dat'))\n tracker.Free()\n FSDK.Finalize()\n\n\ndef image_face_recognition(img, templates, cursor, threshold: float) -> dict:\n # Find template from image\n faces, current_templates = get_faces(img), [] # List of faces and list of templates\n for face in faces:\n # try:\n current_templates.append(FSDK.GetFaceTemplateInRegion(img, face)) # Find face template for each face\n # except Exception as e:\n # print(str(e))\n if not current_templates: # If no faces are found, return an error\n return dict(Message=False, Error='Any face was found')\n coincidences = dict() # Coincidences with more tha threshold% of similarity\n i = 0\n for item in templates:\n i += 1\n # id_hist, id_, curp, report, name, type_, template_db, date_ = item # HRF_RF_ID, HRF_TIPO_CIU, MRF_PATRON_F\n id_hist, id_, date_, template_db = item \n template_db = ctype_from_bytes(template_db.hex()) # Create an array from bytes and then convert into ctype\n # if id_ in coincidences:\n # continue\n for template in current_templates:\n similarity = compare_faces(template, template_db) # Comparing faces\n if similarity > threshold:\n if coincidences.get(id_, None) is None:\n coincidences[id_] = dict(\n PADRON_ID=id_, PF_FECHA_REGISTRO=date_.strftime(\"%m/%d/%Y, %H:%M:%S\"),\n FOTO_ID=id_hist\n )\n\n\n if not coincidences:\n return dict(Message=False, Error='No coincidence')\n\n else:\n return dict(\n Message=True, # Message of successful task\n Error=False,\n Coincidences=coincidences,\n )\n\n\nasync def video_face_recognition(img, templates, cursor, threshold: float) -> dict:\n response = image_face_recognition(img, templates, cursor, threshold)\n if not response['Message']:\n return dict()\n else:\n del response['Message'], response['Error']\n return response\n\n\nasync def process_frame(frame):\n img = numpy_to_image(frame) # Converting frame to image (numpy to Pillow image)\n img = image_to_byte_array(img) # Image to Jpeg buffer\n return img\n\n\nclass VideoFaceRecognition:\n \"\"\"docstring for LiveRecognition\"\"\"\n\n def __init__(self, templates=None, video=None):\n self.video = video\n self.templates = templates\n self.camera = cv2.VideoCapture()\n self.frame = None\n\n def load_video(self, video):\n try:\n self.camera.release()\n except:\n pass\n self.video = video\n self.camera.open(self.video)\n\n def grab_frame(self):\n ret, frame = self.camera.read()\n self.frame = frame\n return ret\n\n def show_image(self):\n cv2.imshow('Video', self.frame)\n\n # noinspection PyUnresolvedReferences\n async def process(self, thershold=0.95, mode='fast'):\n from pprint import pprint\n frames_per_second = 1 if mode == 'fast' else 5 if mode == 'deep' else 3\n tasks = list()\n frames = int(self.camera.get(7))\n images = []\n for i in range(0, frames, int(30 / frames_per_second)):\n self.camera.set(1, i)\n ret = self.grab_frame() # Get frame\n # self.show_image() # Show frame\n if not ret:\n break\n images.append(process_frame(self.frame))\n images = await asyncio.gather(*images, return_exceptions=True)\n for img in images:\n tasks.append(video_face_recognition(FSDK.LoadImageFromJpegBuffer(img), self.templates, None, thershold))\n response = await asyncio.gather(*tasks, return_exceptions=True)\n # logging.debug(str(response))\n out = dict(Message=False, Coincidences=dict())\n\n for d in response:\n if not d:\n continue\n for key, value in d.items():\n out[key].update(value)\n\n if out['Coincidences']:\n out['Message'] = True\n out['Coincidences'] = list(out['Coincidences'].values())\n return out\n\n def __del__(self):\n self.camera.release()\n","sub_path":"luxand.py","file_name":"luxand.py","file_ext":"py","file_size_in_byte":6398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"425050273","text":"import json\nimport datetime\nimport scrapy\n\n\nclass OAntagonistaSpider(scrapy.Spider):\n\n name = 'o_antagonista'\n base_url = 'http://www.oantagonista.com/pagina/%s'\n current_page = 1\n last_page = 1\n start_urls = [base_url % current_page]\n download_delay = 0.5\n posts = []\n\n def parse(self, response):\n\n for post in response.css('article.post'):\n\n post_id = post.css('article.post ::attr(id)').extract_first()\n post_summary = post.css('p ::text').extract_first()\n post_title = post.css('h2 ::text').extract_first()\n\n post_date_time = post.css('time.entry-date ::text').extract_first()\n try:\n post_date = datetime.datetime.strptime(\n post_date_time, '%d.%m.%y %H:%M').strftime('%d/%m/%y')\n except:\n post_date = ''\n\n try:\n post_time = datetime.datetime.strptime(\n post_date_time, '%d.%m.%y %H:%M').strftime('%H:%M')\n except:\n post_time = ''\n\n self.posts.append({\n 'id': post_id or '',\n 'title': post_title or '',\n 'summary': post_summary or '',\n 'time': post_time,\n 'date': post_date,\n 'page': str(self.current_page)\n })\n\n with open('posts.json', 'r+') as f:\n try:\n posts_file = f.read()\n f.seek(0)\n f.truncate(0)\n existing_posts = json.loads(posts_file)\n except Exception as e:\n existing_posts = []\n write_posts = existing_posts + self.posts\n f.write(json.dumps(write_posts, ensure_ascii=False).encode('utf8'))\n\n if self.current_page < self.last_page:\n self.current_page = self.current_page + 1\n yield scrapy.Request(self.base_url % self.current_page)\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"615530066","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n Author: kun.wang\n Create: 2015-06-24\n\nusing: PySide\n\"\"\"\n\nimport sys\n\nimport PySide.QtCore as QtCore\nimport PySide.QtGui as QtGui\n\nimport easy\nimport honey\n\n\nclass TaskTreeModel(QtCore.QAbstractItemModel):\n client = honey.client.HoneyClient()\n\n def __init__(self, parent=None):\n super(TaskTreeModel, self).__init__(parent)\n self.headers = honey.task.Task.attributes\n self.root = easy.EasyObjNode()\n\n def clear_all(self):\n self.root.remove_all_child()\n\n def set_root(self, root):\n self.root = root\n self.reset()\n\n def add(self, task, parent):\n parent_task = self.get(parent)\n position = parent_task.child_count()\n\n self.beginInsertRows(parent, position, position)\n parent_task.insert_child(position, task)\n self.endInsertRows()\n\n return True\n\n def remove(self, index):\n node = self.get(index)\n for i in reversed(range(node.child_count())):\n child_index = index.child(i, 0)\n self.remove(child_index)\n\n parent_index = index.parent()\n position = node.row()\n self.beginRemoveRows(parent_index, position, position)\n node.remove()\n self.endRemoveRows()\n return True\n\n def get(self, index):\n if index.isValid():\n task_node = index.internalPointer()\n if task_node:\n return task_node\n return self.root\n\n def get_obj(self, index):\n return self.get(index).obj\n\n def rowCount(self, parent):\n if not parent.isValid():\n parent_node = self.root\n else:\n parent_node = parent.internalPointer()\n\n return parent_node.child_count()\n\n def columnCount(self, parent):\n return len(self.headers)\n\n def data(self, index, role):\n task_node = self.get(index)\n # row = index.row()\n column = index.column()\n header = self.headers[column]\n attr_name = header.attribute\n attr_value = task_node.get_attr(header.attribute)\n if attr_name.endswith('_id'):\n class_name = attr_name[:-3]\n if class_name == 'parent':\n attr_value = task_node.parent.get_attr('name')\n else:\n obj = self.client.get_object(class_name, attr_value)\n attr_value = unicode(obj)\n\n if role == QtCore.Qt.DisplayRole:\n return attr_value\n\n if role == QtCore.Qt.BackgroundRole:\n if attr_name == \"status\":\n if task_node.get_attr(attr_name) == 0:\n return QtGui.QBrush(QtGui.QColor(0, 255, 0, 70))\n elif task_node.get_attr(attr_name) == 1:\n return QtGui.QBrush(QtGui.QColor(255, 0, 0, 70))\n elif task_node.get_attr(attr_name) == 2:\n return QtGui.QBrush(QtGui.QColor(0, 0, 255, 70))\n\n if role == QtCore.Qt.EditRole:\n return attr_value\n\n if role == QtCore.Qt.SizeHintRole:\n header_size = QtCore.QSize()\n header_size.setHeight(20)\n return header_size\n\n def headerData(self, section, orientation, role):\n if role == QtCore.Qt.DisplayRole:\n return self.headers[section].en\n\n if role == QtCore.Qt.SizeHintRole:\n header_size = QtCore.QSize()\n header_size.setHeight(30)\n return header_size\n\n if role == QtCore.Qt.TextAlignmentRole:\n return QtCore.Qt.AlignCenter\n\n def flags(self, index):\n return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEditable\n\n def parent(self, index):\n node = index.internalPointer()\n parent_node = node.parent\n if parent_node == self.root:\n return QtCore.QModelIndex()\n return self.createIndex(parent_node.row(), 0, parent_node)\n\n def index(self, row, column, parent):\n parent_node = self.get(parent)\n child_item = parent_node.child(row)\n if child_item:\n return self.createIndex(row, column, child_item)\n else:\n return QtCore.QModelIndex()\n\n\nclass TaskTreeView(QtGui.QTreeView):\n def __init__(self, parent=None):\n super(TaskTreeView, self).__init__(parent)\n self.setWindowTitle('Task Tree')\n\n def mouseReleaseEvent(self, event):\n super(TaskTreeView, self).mouseReleaseEvent(event)\n index = self.indexAt(event.pos())\n if not index.isValid():\n self.clearSelection()\n\n def get_selected_index(self):\n selects = self.task_tree_view.selectedIndexes()\n if selects:\n return selects[0]\n return None\n\n def get_selected(self):\n selects = self.task_tree_view.selectedIndexes()\n if selects:\n return selects[0], self.model().get(selects[0])\n return None, None\n\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n\n model = TaskTreeModel()\n a = TaskTreeView()\n a.setModel(model)\n a.resize(900, 600)\n a.show()\n\n sys.exit(app.exec_())\n","sub_path":"OpenCGPipeline/HoneyMongo/honey_gui/task_ui/tree_view.py","file_name":"tree_view.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"564224309","text":"# -*- coding: utf-8 -*-\n__author__ = 'yusongmin'\n\n\nimport copy\nimport numpy as np\nfrom A_Settings.a_Base_parameter import *\nfrom A_Settings.d_Dictionary import *\nfrom numpy import array\nfrom E_Functions.Database.a_Result_read import *\nfrom A_Settings.d_Dictionary import firms_strategy_set_dict as FSS_dict\n\n\"\"\"\n计算企业估计的配额的移动平均价格\n\"\"\"\ndef MA_price(firm_self, current_period, price_matrix):\n\n if current_period == 0:\n moving_average_price = quota_price_initial\n elif current_period < firm_self.Memory_length:\n moving_average_price = sum([price_matrix[current_period - i][num_tick - 1] for i in xrange(1, current_period + 1)]) / current_period\n else:\n moving_average_price = sum([price_matrix[current_period - i][num_tick - 1] for i in xrange(1, int(firm_self.Memory_length) + 1)]) / firm_self.Memory_length\n\n return moving_average_price\n\n\"\"\"\n预期中期碳价\n\"\"\"\ndef longterm_price_expect(firm_self,\n firm_list,\n sightfirms_id_list,\n tech_average_cost_array,\n current_period,\n firms_variable_space,\n firms_variable_dict,\n firms_tech_condition_space,\n price_matrix,\n tech_exogenous_variables_matrix):\n\n # 将预期企业自身也加入视野企业集合中\n sightfirms_list = [firm_list[i] for i in sightfirms_id_list]\n\n # 预期所有视野内企业的总排放\n sightfirms_total_emission = 0\n sightfirms_left_quantity_list = np.zeros((len(sightfirms_list), ))\n sightfirm_total_emission_list = np.zeros((len(sightfirms_list), ))\n num = 0\n for sightfirm in sightfirms_list:\n sightfirm_left_quantity = ((firms_variable_space[current_period][firms_variable_dict[\"quantity_accumulated\"]][sightfirm.Id] + sightfirm.Quantity_base * num_period) / (current_period + 1 + num_period)) * (num_period - 1 - current_period)\n sightfirms_left_quantity_list[num] = sightfirm_left_quantity\n sightfirm_total_emission_list[num] = firms_variable_space[current_period][firms_variable_dict[\"emission_accumulated\"]][sightfirm.Id] + \\\n sightfirm_left_quantity * firms_variable_space[current_period][firms_variable_dict[\"energy_per_quantity\"]][sightfirm.Id] * emission_factor\n sightfirms_total_emission += sightfirm_total_emission_list[num]\n num += 1\n\n # 加总所有视野内企业的总配额持有量\n sightfirms_quota_holding_list = np.zeros((1, len(sightfirms_list))).reshape(len(sightfirms_list),)\n num = 0\n for sightfirm in sightfirms_list:\n sightfirms_quota_holding_list[num] = firms_variable_space[current_period][firms_variable_dict[\"quota_holding\"]][sightfirm.Id]\n num += 1\n sightfirms_total_quota_holding = array(sightfirms_quota_holding_list).sum()\n\n # 计算所有视野内企业需要减排总量\n sightfirms_total_emission_cut = sightfirms_total_emission - sightfirms_total_quota_holding\n\n # 计算所有视野内企业的各减排技术减排空间\n tech_emission_cut_array = np.zeros((1, num_tech)).reshape(num_tech,)\n for sightfirm_num in xrange(0, len(sightfirms_list)):\n for tech in xrange(0, num_tech):\n if firms_tech_condition_space[current_period][sightfirms_list[sightfirm_num].Id][tech] == 0:\n tech_emission_cut_array[tech] += sightfirms_left_quantity_list[sightfirm_num] * tech_exogenous_variables_matrix[tech][2] * emission_factor\n\n # 计算所有视野内企业的边际减排成本曲线\n tech_averagecost_emissioncut_list = zip(tech_average_cost_array, tech_emission_cut_array)\n tech_averagecost_emissioncut_list_sorted = sorted(tech_averagecost_emissioncut_list, key = lambda x : x[0])\n\n # 根据所有视野内企业需要减排总量, 计算该范围内的均衡长期碳价\n if sightfirms_total_emission_cut <= 0:\n sightfirms_equilibrium_price = 0\n else:\n tech_emission_cut_total = 0\n for tech in xrange(0, num_tech):\n tech_emission_cut_total += tech_averagecost_emissioncut_list_sorted[tech][1]\n if tech_emission_cut_total >= sightfirms_total_emission_cut:\n sightfirms_equilibrium_price = tech_averagecost_emissioncut_list_sorted[tech][0]\n break\n if tech == num_tech - 1:\n sightfirms_equilibrium_price = fine_price\n\n # 计算移动平均碳价\n MovingAverage_price = MA_price(firm_self, current_period, price_matrix)\n\n # 计算局部均衡与移动平均价格的加权平均价格\n WeightedAverage_price = (1 - firm_self.Technical_weight) * sightfirms_equilibrium_price + firm_self.Technical_weight * MovingAverage_price\n\n # 跟fine price比较\n if WeightedAverage_price <= fine_price:\n forecast = WeightedAverage_price\n else:\n forecast = fine_price\n\n return forecast","sub_path":"FirstPaper/E_Functions/Agent/b_Forecast_process.py","file_name":"b_Forecast_process.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"29443572","text":"# encode: utf-8\n\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\nfrom django.db import transaction\n\nfrom domain.models import MedicalPrescription, ScheduledExam\n\n\nclass Command(BaseCommand):\n help = \"Update '/archived' firebase node\"\n\n @transaction.atomic\n def handle(self, *args, **options):\n try:\n\n import pyrebase\n firebase = pyrebase.initialize_app(settings.FB_CONFIG)\n db = firebase.database()\n\n archived_statuses = (MedicalPrescription.NOT_REGISTERED_EXAMS_FOUND,\n MedicalPrescription.UNREADABLE_PICTURES,\n MedicalPrescription.PICTURES_ID_SELFIE_DONT_MATCH,\n MedicalPrescription.REQUEST_EXPIRED)\n\n # Insert prescriptions:\n prescriptions = MedicalPrescription.objects.filter(status__in=archived_statuses)\n db.child('archived').remove()\n\n for instance in prescriptions:\n selfie = None\n if bool(instance.patient.selfie_uploadcare) or bool(instance.patient.selfie):\n try:\n selfie = instance.patient.selfie_uploadcare.url\n except (AttributeError, ValueError):\n selfie = instance.patient.selfie.url\n\n fb_data = {\n \"avatar\": selfie,\n \"exams\": [],\n \"key\": instance.pk,\n \"modifiedAt\": int(instance.modified.timestamp()),\n \"name\": instance.patient.full_name,\n \"status\": instance.status\n }\n\n db.child('archived').child(instance.pk).set(fb_data)\n\n # Insert scheduled exams:\n archived_statuses = (ScheduledExam.PATIENT_CANCELED_BY_CALL,\n ScheduledExam.LAB_RECORD_CANCELED,\n ScheduledExam.RESULTS_RECEIVED,\n ScheduledExam.NOT_ELIGIBLE_PATIENT_DUE_TO_AGE_OR_GENDER,\n ScheduledExam.PROCEDURES_NOT_COVERED\n )\n\n scheduled_exams = ScheduledExam.objects.filter(status__in=archived_statuses)\n\n for instance in scheduled_exams:\n selfie = None\n if bool(instance.prescription.patient.selfie_uploadcare) or bool(instance.prescription.patient.selfie):\n try:\n selfie = instance.prescription.patient.selfie_uploadcare.url\n except (AttributeError, ValueError):\n selfie = instance.prescription.patient.selfie.url\n\n fb_data = {\n \"avatar\": selfie,\n \"exams\": [scheduled_exam.exam.name for scheduled_exam in scheduled_exams],\n \"key\": instance.prescription.pk,\n \"modifiedAt\": int(instance.prescription.modified.timestamp()),\n \"name\": instance.prescription.patient.full_name,\n \"status\": instance.status\n }\n\n db.child('archived').child(instance.prescription.pk).set(fb_data)\n\n print(\"Import successfully done!\")\n except Exception as e:\n print(\"Unable to sync with firebase from signals ('archived'): {0}\".format(e))\n","sub_path":"lab_core/domain/management/commands/update_firebase_archived_node.py","file_name":"update_firebase_archived_node.py","file_ext":"py","file_size_in_byte":3401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"329920963","text":"import datetime\nimport time\n\ndef getYesterday():\n today = datetime.date.today()\n today2 = datetime.datetime.today()\n print(today)\n print(time.strptime(str(), \"%Y-%m-%d %H:%M:%S\") )\n\n oneday = datetime.timedelta(days=1)\n yesterday = today - oneday\n return yesterday\n\n\n# 输出\nprint(getYesterday())","sub_path":"smtp/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"157748353","text":"#imports the shuffle from random\nfrom random import shuffle\n\ndef rearrange(words):\n #due to how commandline handles the arguments, it must be converted to a list for proocessing\n words = list(words)\n #shuffle class is alled and the words are shuffled\n shuffle(words)\n #the list is randomized then rejoined as a single string\n print (' '.join(words))\n\nif __name__ == \"__main__\":\n #preps system for output\n import sys\n #takes command line arguments\n rearrange(sys.argv[1:])\n","sub_path":"rearrange.py","file_name":"rearrange.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"327924516","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom maoyanSpiders.items import MaoyanspiderItem\nfrom scrapy.selector import Selector\n\n\nclass MoviesSpider(scrapy.Spider):\n # 定义爬虫名称\n name = 'maoyan'\n allowed_domains = ['maoyan.com']\n # 起始URL列表\n start_urls = ['https://maoyan.com/films?showType=3']\n\n# 注释默认的parse函数\n# def parse(self, response):\n# pass\n\n\n # 爬虫启动时,引擎自动调用该方法,并且只会被调用一次,用于生成初始的请求对象(Request)。\n # start_requests()方法读取start_urls列表中的URL并生成Request对象,发送给引擎。\n # 引擎再指挥其他组件向网站服务器发送请求,下载网页\n def parse(self,response):\n selector=Selector(response)\n name = selector.xpath(\"//div[@class='movie-hover-info']/div/span[@class='name ']/text()\").extract()\n mytype = selector.xpath(\"//div[@class='movie-hover-info']/div[2]/text()\").extract()\n date = selector.xpath(\"//div[@class='movie-hover-info']/div[4]/text()\").extract()\n\n print(name, mytype, date)\n item = MaoyanspiderItem()\n item['name']=name\n item['mytype']=mytype\n item['date']=date\n yield item","sub_path":"week01/work02_scrapy/doubanmovie/maoyanSpiders/spiders/douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"34521783","text":"from flask import Request\n\nclass RequestDictionary(dict):\n def __getattr__(self, key):\n return self.get(key)\n\ndef create(**route_args) -> RequestDictionary:\n request = Request\n data = {\n **request.args,\n **request.headers,\n **request.form,\n **route_args\n }\n return RequestDictionary(data)","sub_path":"project/infrastructure/request_dict.py","file_name":"request_dict.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"263146473","text":"# -*- coding: utf-8 -*-\n# Part of TigernixERP. See LICENSE file for full copyright and licensing details.\nimport base64\nimport binascii\nimport io\nimport PIL.PdfImagePlugin # activate PDF support in PIL\nfrom PIL import Image\nimport logging\nimport os\nimport re\n\nimport suds\nfrom suds.client import Client\nfrom suds.plugin import MessagePlugin\nfrom suds.sax.element import Element\n\nSUDS_VERSION = suds.__version__\n\nfrom odoo import _\n\n\n_logger = logging.getLogger(__name__)\n# uncomment to enable logging of SOAP requests and responses\n# logging.getLogger('suds.transport').setLevel(logging.DEBUG)\n\n\nUPS_ERROR_MAP = {\n '110002': \"Please provide at least one item to ship.\",\n '110208': \"Please set a valid country in the recipient address.\",\n '110308': \"Please set a valid country in the warehouse address.\",\n '110548': \"A shipment cannot have a KGS/IN or LBS/CM as its unit of measurements. Configure it from the delivery method.\",\n '111057': \"This measurement system is not valid for the selected country. Please switch from LBS/IN to KGS/CM (or vice versa). Configure it from the delivery method.\",\n '111091': \"The selected service is not possible from your warehouse to the recipient address, please choose another service.\",\n '111100': \"The selected service is invalid from the requested warehouse, please choose another service.\",\n '111107': \"Please provide a valid zip code in the warehouse address.\",\n '111210': \"The selected service is invalid to the recipient address, please choose another service.\",\n '111212': \"Please provide a valid package type available for service and selected locations.\",\n '111500': \"The selected service is not valid with the selected packaging.\",\n '112111': \"Please provide a valid shipper number/Carrier Account.\",\n '113020': \"Please provide a valid zip code in the warehouse address.\",\n '113021': \"Please provide a valid zip code in the recipient address.\",\n '120031': \"Exceeds Total Number of allowed pieces per World Wide Express Shipment.\",\n '120100': \"Please provide a valid shipper number/Carrier Account.\",\n '120102': \"Please provide a valid street in shipper's address.\",\n '120105': \"Please provide a valid city in the shipper's address.\",\n '120106': \"Please provide a valid state in the shipper's address.\",\n '120107': \"Please provide a valid zip code in the shipper's address.\",\n '120108': \"Please provide a valid country in the shipper's address.\",\n '120109': \"Please provide a valid shipper phone number.\",\n '120113': \"Shipper number must contain alphanumeric characters only.\",\n '120114': \"Shipper phone extension cannot exceed the length of 4.\",\n '120115': \"Shipper Phone must be at least 10 alphanumeric characters.\",\n '120116': \"Shipper phone extension must contain only numbers.\",\n '120122': \"Please provide a valid shipper Number/Carrier Account.\",\n '120124': \"The requested service is unavailable between the selected locations.\",\n '120202': \"Please provide a valid street in the recipient address.\",\n '120205': \"Please provide a valid city in the recipient address.\",\n '120206': \"Please provide a valid state in the recipient address.\",\n '120207': \"Please provide a valid zipcode in the recipient address.\",\n '120208': \"Please provide a valid Country in recipient's address.\",\n '120209': \"Please provide a valid phone number for the recipient.\",\n '120212': \"Recipient PhoneExtension cannot exceed the length of 4.\",\n '120213': \"Recipient Phone must be at least 10 alphanumeric characters.\",\n '120214': \"Recipient PhoneExtension must contain only numbers.\",\n '120302': \"Please provide a valid street in the warehouse address.\",\n '120305': \"Please provide a valid City in the warehouse address.\",\n '120306': \"Please provide a valid State in the warehouse address.\",\n '120307': \"Please provide a valid Zip in the warehouse address.\",\n '120308': \"Please provide a valid Country in the warehouse address.\",\n '120309': \"Please provide a valid warehouse Phone Number\",\n '120312': \"Warehouse PhoneExtension cannot exceed the length of 4.\",\n '120313': \"Warehouse Phone must be at least 10 alphanumeric characters.\",\n '120314': \"Warehouse Phone must contain only numbers.\",\n '120412': \"Please provide a valid shipper Number/Carrier Account.\",\n '121057': \"This measurement system is not valid for the selected country. Please switch from LBS/IN to KGS/CM (or vice versa). Configure it from delivery method\",\n '121210': \"The requested service is unavailable between the selected locations.\",\n '128089': \"Access License number is Invalid. Provide a valid number (Length sholuld be 0-35 alphanumeric characters)\",\n '190001': \"Cancel shipment not available at this time , Please try again Later.\",\n '190100': \"Provided Tracking Ref. Number is invalid.\",\n '190109': \"Provided Tracking Ref. Number is invalid.\",\n '250001': \"Access License number is invalid for this provider.Please re-license.\",\n '250002': \"Username/Password is invalid for this delivery provider.\",\n '250003': \"Access License number is invalid for this delivery provider.\",\n '250004': \"Username/Password is invalid for this delivery provider.\",\n '250006': \"The maximum number of user access attempts was exceeded. So please try again later\",\n '250007': \"The UserId is currently locked out; please try again in 24 hours.\",\n '250009': \"Provided Access License Number not found in the UPS database\",\n '250038': \"Please provide a valid shipper number/Carrier Account.\",\n '250047': \"Access License number is revoked contact UPS to get access.\",\n '250052': \"Authorization system is currently unavailable , try again later.\",\n '250053': \"UPS Server Not Found\",\n '9120200': \"Please provide at least one item to ship\"\n}\n\n\nclass Package():\n def __init__(self, carrier, weight, quant_pack=False, name=''):\n self.weight = self._convert_weight(weight, carrier.ups_package_weight_unit)\n self.weight_unit = carrier.ups_package_weight_unit\n self.name = name\n self.dimension_unit = carrier.ups_package_dimension_unit\n if quant_pack:\n self.dimension = {'length': quant_pack.length, 'width': quant_pack.width, 'height': quant_pack.height}\n else:\n self.dimension = {'length': carrier.ups_default_packaging_id.length, 'width': carrier.ups_default_packaging_id.width, 'height': carrier.ups_default_packaging_id.height}\n self.packaging_type = quant_pack and quant_pack.shipper_package_code or False\n\n def _convert_weight(self, weight, unit='KGS'):\n ''' Convert picking weight (always expressed in KGS) into the specified unit '''\n if unit == 'KGS':\n return weight\n elif unit == 'LBS':\n return weight / 0.45359237\n else:\n raise ValueError\n\n\nclass LogPlugin(MessagePlugin):\n \"\"\" Small plugin for suds that catches out/ingoing XML requests and logs them\"\"\"\n def __init__(self, debug_logger):\n self.debug_logger = debug_logger\n\n def sending(self, context):\n self.debug_logger(context.envelope, 'ups_request')\n\n def received(self, context):\n self.debug_logger(context.reply, 'ups_response')\n\n\nclass FixRequestNamespacePlug(MessagePlugin):\n def __init__(self, root):\n self.root = root\n\n def marshalled(self, context):\n context.envelope = context.envelope.prune()\n\n\n# token = superself.token\n# conn = superself.conn\n# content_type = superself.content_type\n\n# payload = \"origin=501&destination=114&weight=1700&courier=jne\"\n\n# headers = {\n# 'key': token,\n# 'content-type': content_type\n# }\n\n# conn.request(\"POST\", \"/starter/cost\", payload, headers)\n\n# res = conn.getresponse()\n# data = res.read()\n\n# print(data.decode(\"utf-8\"))\n\nclass RjOngkirRequest():\n def __init__(self, token, conn, content_type, client):\n self.token = token\n self.conn = conn\n self.content_type = content_type\n self.client = client\n\n self.rate_rest = '/starter/cost'\n # self.ship_wsdl = '../api/Ship.wsdl'\n # self.void_wsdl = '../api/Void.wsdl'\n\n def _add_security_header(self, client):\n # set the detail which require to authenticate\n security_ns = ('upss', 'http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0')\n security = Element('UPSSecurity', ns=security_ns)\n\n username_token = Element('UsernameToken', ns=security_ns)\n username = Element('Username', ns=security_ns).setText(self.username)\n password = Element('Password', ns=security_ns).setText(self.password)\n username_token.append(username)\n username_token.append(password)\n\n service_token = Element('ServiceAccessToken', ns=security_ns)\n license = Element('AccessLicenseNumber', ns=security_ns).setText(self.access_number)\n service_token.append(license)\n\n security.append(username_token)\n security.append(service_token)\n\n client.set_options(soapheaders=security)\n\n def _set_client(self, wsdl, api, root):\n wsdl_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), wsdl)\n client = Client('file:///%s' % wsdl_path.lstrip('/'), plugins=[FixRequestNamespacePlug(root), LogPlugin(self.debug_logger)])\n self._add_security_header(client)\n client.set_options(location='%s%s' % (self.endurl, api))\n return client\n\n def _clean_phone_number(self, phone):\n return re.sub('[^0-9]','', phone)\n\n def check_required_value(self, shipper, ship_from, ship_to, order=False, picking=False):\n required_field = {'city': 'City', 'zip': 'ZIP code', 'country_id': 'Country', 'phone': 'Phone'}\n # Check required field for shipper\n res = [required_field[field] for field in required_field if not shipper[field]]\n if shipper.country_id.code in ('US', 'CA', 'IE') and not shipper.state_id.code:\n res.append('State')\n if not shipper.street and not shipper.street2:\n res.append('Street')\n if res:\n return _(\"The address of your company is missing or wrong.\\n(Missing field(s) : %s)\") % \",\".join(res)\n if len(self._clean_phone_number(shipper.phone)) < 10:\n return _(UPS_ERROR_MAP.get('120115'))\n # Check required field for warehouse address\n res = [required_field[field] for field in required_field if not ship_from[field]]\n if ship_from.country_id.code in ('US', 'CA', 'IE') and not ship_from.state_id.code:\n res.append('State')\n if not ship_from.street and not ship_from.street2:\n res.append('Street')\n if res:\n return _(\"The address of your warehouse is missing or wrong.\\n(Missing field(s) : %s)\") % \",\".join(res)\n if len(self._clean_phone_number(ship_from.phone)) < 10:\n return _(UPS_ERROR_MAP.get('120313'))\n # Check required field for recipient address\n res = [required_field[field] for field in required_field if field != 'phone' and not ship_to[field]]\n if ship_to.country_id.code in ('US', 'CA', 'IE') and not ship_to.state_id.code:\n res.append('State')\n if not ship_to.street and not ship_to.street2:\n res.append('Street')\n if order:\n phone = ship_to.mobile or ship_to.phone or order.partner_id.mobile or order.partner_id.phone\n if not order.order_line:\n return _(\"Please provide at least one item to ship.\")\n for line in order.order_line.filtered(lambda line: not line.product_id.weight and not line.is_delivery and line.product_id.type not in ['service', 'digital']):\n return _(\"The estimated price cannot be computed because the weight of your product is missing.\")\n if picking:\n phone = ship_to.mobile or ship_to.phone or picking.sale_id.partner_id.mobile or picking.sale_id.partner_id.phone\n for move in picking.move_lines.filtered(lambda move: not move.product_id.weight):\n return _(\"The delivery cannot be done because the weight of your product is missing.\")\n if not phone:\n res.append('Phone')\n if res:\n return _(\"The recipient address is missing or wrong.\\n(Missing field(s) : %s)\") % \",\".join(res)\n if len(self._clean_phone_number(phone)) < 10:\n return _(UPS_ERROR_MAP.get('120213'))\n return False\n\n def get_error_message(self, error_code, description):\n result = {}\n result['error_message'] = UPS_ERROR_MAP.get(error_code)\n if not result['error_message']:\n result['error_message'] = description\n return result\n\n def save_label(self, image64, label_file_type='GIF'):\n img_decoded = base64.decodebytes(image64.encode('utf-8'))\n if label_file_type == 'GIF':\n # Label format is GIF, so need to rotate and convert as PDF\n image_string = io.BytesIO(img_decoded)\n im = Image.open(image_string)\n label_result = io.BytesIO()\n im.save(label_result, 'pdf')\n return label_result.getvalue()\n else:\n return img_decoded\n\n def set_package_detail(self, client, packages, packaging_type, namespace, ship_from, ship_to, cod_info):\n Packages = []\n for i, p in enumerate(packages):\n package = client.factory.create('{}:PackageType'.format(namespace))\n if hasattr(package, 'Packaging'):\n package.Packaging.Code = p.packaging_type or packaging_type or ''\n elif hasattr(package, 'PackagingType'):\n package.PackagingType.Code = p.packaging_type or packaging_type or ''\n\n if p.dimension_unit:\n package.Dimensions.UnitOfMeasurement.Code = p.dimension_unit or ''\n package.Dimensions.Length = p.dimension['length'] or ''\n package.Dimensions.Width = p.dimension['width'] or ''\n package.Dimensions.Height = p.dimension['height'] or ''\n\n if cod_info:\n package.PackageServiceOptions.COD.CODFundsCode = str(cod_info['funds_code'])\n package.PackageServiceOptions.COD.CODAmount.MonetaryValue = cod_info['monetary_value']\n package.PackageServiceOptions.COD.CODAmount.CurrencyCode = cod_info['currency']\n\n package.PackageWeight.UnitOfMeasurement.Code = p.weight_unit or ''\n package.PackageWeight.Weight = p.weight or ''\n\n # Package and shipment reference text is only allowed for shipments within\n # the USA and within Puerto Rico. This is a UPS limitation.\n if (p.name and ship_from.country_id.code in ('US') and ship_to.country_id.code in ('US')):\n reference_number = client.factory.create('ns3:ReferenceNumberType')\n reference_number.Code = 'PM'\n reference_number.Value = p.name\n reference_number.BarCodeIndicator = p.name\n package.ReferenceNumber = reference_number\n\n Packages.append(package)\n return Packages\n\n def rj_ongkir_shipping_prince(self):\n user = self.env.user\n company_address_id = user.company_id.city\n origin = company_address_id\n destination_id = 501 #self.client.city sementara di harcode\n # payload = \"origin=501&destination=114&weight=1700&courier=jne\"\n # headers = {\n # 'key': token,\n # 'content-type': content_type\n # }\n\n # conn.request(\"POST\", \"/starter/cost\", payload, headers)\n\n # res = conn.getresponse()\n # data = res.read()\n\n pass\n\n\n\n def get_shipping_price(self, shipment_info, packages, shipper, ship_from, ship_to, packaging_type, service_type, saturday_delivery, cod_info):\n client = self._set_client(self.rate_wsdl, 'Rate', 'RateRequest')\n\n request = client.factory.create('ns0:RequestType')\n request.RequestOption = 'Rate'\n\n classification = client.factory.create('ns2:CodeDescriptionType')\n classification.Code = '00' # Get rates for the shipper account\n classification.Description = 'Get rates for the shipper account'\n\n namespace = 'ns2'\n shipment = client.factory.create('{}:ShipmentType'.format(namespace))\n\n for package in self.set_package_detail(client, packages, packaging_type, namespace, ship_from, ship_to, cod_info):\n shipment.Package.append(package)\n\n shipment.Shipper.Name = shipper.name or ''\n shipment.Shipper.Address.AddressLine = [shipper.street or '', shipper.street2 or '']\n shipment.Shipper.Address.City = shipper.city or ''\n shipment.Shipper.Address.PostalCode = shipper.zip or ''\n shipment.Shipper.Address.CountryCode = shipper.country_id.code or ''\n if shipper.country_id.code in ('US', 'CA', 'IE'):\n shipment.Shipper.Address.StateProvinceCode = shipper.state_id.code or ''\n shipment.Shipper.ShipperNumber = self.shipper_number or ''\n # shipment.Shipper.Phone.Number = shipper.phone or ''\n\n shipment.ShipFrom.Name = ship_from.name or ''\n shipment.ShipFrom.Address.AddressLine = [ship_from.street or '', ship_from.street2 or '']\n shipment.ShipFrom.Address.City = ship_from.city or ''\n shipment.ShipFrom.Address.PostalCode = ship_from.zip or ''\n shipment.ShipFrom.Address.CountryCode = ship_from.country_id.code or ''\n if ship_from.country_id.code in ('US', 'CA', 'IE'):\n shipment.ShipFrom.Address.StateProvinceCode = ship_from.state_id.code or ''\n # shipment.ShipFrom.Phone.Number = ship_from.phone or ''\n\n shipment.ShipTo.Name = ship_to.name or ''\n shipment.ShipTo.Address.AddressLine = [ship_to.street or '', ship_to.street2 or '']\n shipment.ShipTo.Address.City = ship_to.city or ''\n shipment.ShipTo.Address.PostalCode = ship_to.zip or ''\n shipment.ShipTo.Address.CountryCode = ship_to.country_id.code or ''\n if ship_to.country_id.code in ('US', 'CA', 'IE'):\n shipment.ShipTo.Address.StateProvinceCode = ship_to.state_id.code or ''\n # shipment.ShipTo.Phone.Number = ship_to.phone or ''\n if not ship_to.commercial_partner_id.is_company:\n shipment.ShipTo.Address.ResidentialAddressIndicator = suds.null()\n\n shipment.Service.Code = service_type or ''\n shipment.Service.Description = 'Service Code'\n if service_type == \"96\":\n shipment.NumOfPieces = int(shipment_info.get('total_qty'))\n\n if saturday_delivery:\n shipment.ShipmentServiceOptions.SaturdayDeliveryIndicator = saturday_delivery\n else:\n shipment.ShipmentServiceOptions = ''\n\n shipment.ShipmentRatingOptions.NegotiatedRatesIndicator = 1\n\n try:\n # Get rate using for provided detail\n response = client.service.ProcessRate(Request=request, CustomerClassification=classification, Shipment=shipment)\n\n # Check if ProcessRate is not success then return reason for that\n if response.Response.ResponseStatus.Code != \"1\":\n return self.get_error_message(response.Response.ResponseStatus.Code, response.Response.ResponseStatus.Description)\n\n result = {}\n result['currency_code'] = response.RatedShipment[0].TotalCharges.CurrencyCode\n\n # Some users are qualified to receive negotiated rates\n negotiated_rate = 'NegotiatedRateCharges' in response.RatedShipment[0] and response.RatedShipment[0].NegotiatedRateCharges.TotalCharge.MonetaryValue or None\n\n result['price'] = negotiated_rate or response.RatedShipment[0].TotalCharges.MonetaryValue\n return result\n\n except suds.WebFault as e:\n # childAtPath behaviour is changing at version 0.6\n prefix = ''\n if SUDS_VERSION >= \"0.6\":\n prefix = '/Envelope/Body/Fault'\n return self.get_error_message(e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Code').getText(),\n e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Description').getText())\n except IOError as e:\n return self.get_error_message('0', 'UPS Server Not Found:\\n%s' % e)\n\n def send_shipping(self, shipment_info, packages, shipper, ship_from, ship_to, packaging_type, service_type, saturday_delivery, cod_info=None, label_file_type='GIF', ups_carrier_account=False):\n client = self._set_client(self.ship_wsdl, 'Ship', 'ShipmentRequest')\n\n request = client.factory.create('ns0:RequestType')\n request.RequestOption = 'nonvalidate'\n\n namespace = 'ns3'\n label = client.factory.create('{}:LabelSpecificationType'.format(namespace))\n\n label.LabelImageFormat.Code = label_file_type\n label.LabelImageFormat.Description = label_file_type\n if label_file_type != 'GIF':\n label.LabelStockSize.Height = '6'\n label.LabelStockSize.Width = '4'\n\n shipment = client.factory.create('{}:ShipmentType'.format(namespace))\n shipment.Description = shipment_info.get('description')\n\n for package in self.set_package_detail(client, packages, packaging_type, namespace, ship_from, ship_to, cod_info):\n shipment.Package.append(package)\n\n shipment.Shipper.AttentionName = shipper.name or ''\n shipment.Shipper.Name = shipper.parent_id.name or shipper.name or ''\n shipment.Shipper.Address.AddressLine = [l for l in [shipper.street or '', shipper.street2 or ''] if l]\n shipment.Shipper.Address.City = shipper.city or ''\n shipment.Shipper.Address.PostalCode = shipper.zip or ''\n shipment.Shipper.Address.CountryCode = shipper.country_id.code or ''\n if shipper.country_id.code in ('US', 'CA', 'IE'):\n shipment.Shipper.Address.StateProvinceCode = shipper.state_id.code or ''\n shipment.Shipper.ShipperNumber = self.shipper_number or ''\n shipment.Shipper.Phone.Number = self._clean_phone_number(shipper.phone)\n\n shipment.ShipFrom.AttentionName = ship_from.name or ''\n shipment.ShipFrom.Name = ship_from.parent_id.name or ship_from.name or ''\n shipment.ShipFrom.Address.AddressLine = [l for l in [ship_from.street or '', ship_from.street2 or ''] if l]\n shipment.ShipFrom.Address.City = ship_from.city or ''\n shipment.ShipFrom.Address.PostalCode = ship_from.zip or ''\n shipment.ShipFrom.Address.CountryCode = ship_from.country_id.code or ''\n if ship_from.country_id.code in ('US', 'CA', 'IE'):\n shipment.ShipFrom.Address.StateProvinceCode = ship_from.state_id.code or ''\n shipment.ShipFrom.Phone.Number = self._clean_phone_number(ship_from.phone)\n\n shipment.ShipTo.AttentionName = ship_to.name or ''\n shipment.ShipTo.Name = ship_to.parent_id.name or ship_to.name or ''\n shipment.ShipTo.Address.AddressLine = [l for l in [ship_to.street or '', ship_to.street2 or ''] if l]\n shipment.ShipTo.Address.City = ship_to.city or ''\n shipment.ShipTo.Address.PostalCode = ship_to.zip or ''\n shipment.ShipTo.Address.CountryCode = ship_to.country_id.code or ''\n if ship_to.country_id.code in ('US', 'CA', 'IE'):\n shipment.ShipTo.Address.StateProvinceCode = ship_to.state_id.code or ''\n shipment.ShipTo.Phone.Number = self._clean_phone_number(shipment_info['phone'])\n if not ship_to.commercial_partner_id.is_company:\n shipment.ShipTo.Address.ResidentialAddressIndicator = suds.null()\n\n shipment.Service.Code = service_type or ''\n shipment.Service.Description = 'Service Code'\n if service_type == \"96\":\n shipment.NumOfPiecesInShipment = int(shipment_info.get('total_qty'))\n shipment.ShipmentRatingOptions.NegotiatedRatesIndicator = 1\n\n # Shipments from US to CA or PR require extra info\n if ship_from.country_id.code == 'US' and ship_to.country_id.code in ['CA', 'PR']:\n shipment.InvoiceLineTotal.CurrencyCode = shipment_info.get('itl_currency_code')\n shipment.InvoiceLineTotal.MonetaryValue = shipment_info.get('ilt_monetary_value')\n\n # set the default method for payment using shipper account\n payment_info = client.factory.create('ns3:PaymentInformation')\n shipcharge = client.factory.create('ns3:ShipmentCharge')\n shipcharge.Type = '01'\n\n # Bill Recevier 'Bill My Account'\n if ups_carrier_account:\n shipcharge.BillReceiver.AccountNumber = ups_carrier_account\n shipcharge.BillReceiver.Address.PostalCode = ship_to.zip\n else:\n shipcharge.BillShipper.AccountNumber = self.shipper_number or ''\n\n payment_info.ShipmentCharge = shipcharge\n shipment.PaymentInformation = payment_info\n\n if saturday_delivery:\n shipment.ShipmentServiceOptions.SaturdayDeliveryIndicator = saturday_delivery\n else:\n shipment.ShipmentServiceOptions = ''\n\n try:\n response = client.service.ProcessShipment(\n Request=request, Shipment=shipment,\n LabelSpecification=label)\n\n # Check if shipment is not success then return reason for that\n if response.Response.ResponseStatus.Code != \"1\":\n return self.get_error_message(response.Response.ResponseStatus.Code, response.Response.ResponseStatus.Description)\n\n result = {}\n result['label_binary_data'] = {}\n for package in response.ShipmentResults.PackageResults:\n result['label_binary_data'][package.TrackingNumber] = self.save_label(package.ShippingLabel.GraphicImage, label_file_type=label_file_type)\n result['tracking_ref'] = response.ShipmentResults.ShipmentIdentificationNumber\n result['currency_code'] = response.ShipmentResults.ShipmentCharges.TotalCharges.CurrencyCode\n\n # Some users are qualified to receive negotiated rates\n negotiated_rate = 'NegotiatedRateCharges' in response.ShipmentResults and response.ShipmentResults.NegotiatedRateCharges.TotalCharge.MonetaryValue or None\n\n result['price'] = negotiated_rate or response.ShipmentResults.ShipmentCharges.TotalCharges.MonetaryValue\n return result\n\n except suds.WebFault as e:\n # childAtPath behaviour is changing at version 0.6\n prefix = ''\n if SUDS_VERSION >= \"0.6\":\n prefix = '/Envelope/Body/Fault'\n return self.get_error_message(e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Code').getText(),\n e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Description').getText())\n except IOError as e:\n return self.get_error_message('0', 'UPS Server Not Found:\\n%s' % e)\n\n def cancel_shipment(self, tracking_number):\n client = self._set_client(self.void_wsdl, 'Void', 'VoidShipmentRequest')\n\n request = client.factory.create('ns0:RequestType')\n request.TransactionReference.CustomerContext = \"Cancle shipment\"\n voidshipment = client.factory.create('ns2:VoidShipment')\n voidshipment.ShipmentIdentificationNumber = tracking_number or ''\n\n result = {}\n try:\n response = client.service.ProcessVoid(\n Request=request, VoidShipment=voidshipment\n )\n if response.Response.ResponseStatus.Code == \"1\":\n return result\n return self.get_error_message(response.Response.ResponseStatus.Code, response.Response.ResponseStatus.Description)\n\n except suds.WebFault as e:\n # childAtPath behaviour is changing at version 0.6\n prefix = ''\n if SUDS_VERSION >= \"0.6\":\n prefix = '/Envelope/Body/Fault'\n return self.get_error_message(e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Code').getText(),\n e.document.childAtPath(prefix + '/detail/Errors/ErrorDetail/PrimaryErrorCode/Description').getText())\n except IOError as e:\n return self.get_error_message('0', 'UPS Server Not Found:\\n%s' % e)\n","sub_path":"addons_enterprise/delivery_rj_ongkir/models/rj_ongkir_request.py","file_name":"rj_ongkir_request.py","file_ext":"py","file_size_in_byte":28348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"288635110","text":"\n\n#calss header\nclass _MISUNDERSTANDING():\n\tdef __init__(self,): \n\t\tself.name = \"MISUNDERSTANDING\"\n\t\tself.definitions = [u'an occasion when someone does not understand something correctly: ', u'a disagreement, argument, or fight: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_misunderstanding.py","file_name":"_misunderstanding.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"58926883","text":"amount = int(input(\"Please enter amount:\"))\nbig = (amount / 100) * 60\nsmall = (amount / 100) * 40\ntax_a = 23\ntax_b = 41\n\ntax_a_on_big = (big / 100) * tax_a\ntax_b_on_small = (small / 100) * tax_b\n\nif amount >= 0:\n print(\"amount: \" , amount)\n print(\"tax on big: \", tax_a_on_big)\n print(\"tax on smal: \", tax_b_on_small)\n print(\"total amount of tax: \", tax_a_on_big + tax_b_on_small)\n print(amount - tax_a_on_big - tax_b_on_small)\nelse:\n print(\"Amount of income must be >= 0. Please try again.\")","sub_path":"practical 4.5/p4-5p3.py","file_name":"p4-5p3.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"291279984","text":"import numpy as np\nimport numpy.random\nimport org\nimport numpy.linalg as npl\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.patches as mpatches\nimport os.path\nimport sklearn.cluster as sklc\nimport sklearn.metrics as sklm\nimport scipy.spatial\nfrom org import Bacteria, Plant\nimport os\nimport sklearn.feature_selection as skfs\n\ndef sqlen(x):\n return np.inner(x, x)\n\n#def gen_random(pop_sizes, fitness):\n# bacteria_pop = [org.Bacteria(i) for i in np.random.uniform(-1, 1, (pop_sizes[0], fitness.gene_sizes[0]))]\n# transformed_genes = [fitness.run(bacteria.gene) for bacteria in bacteria_pop]\n# plant_pop = [org.Plant(transformed_genes[x] + np.random.uniform(-0.001, 0.001, fitness.gene_sizes[1]))\n# for x in np.random.choice(range(pop_sizes[0]), size=pop_sizes[1])]\n#\n# return bacteria_pop, plant_pop\n\n\ndef gen_same_bacteria(pop_sizes, gene_sizes):\n haplotype_b = np.random.uniform(-1, 1, gene_sizes[0])\n haplotype_p = np.random.uniform(-1, 1, gene_sizes[1])\n\n # bacteria constructor accepts\n # 1. gene\n # 2. ancestor id list\n # 3. gene id\n # if no gene id is provided, new id is created\n\n bacteria_pop = [org.Bacteria(haplotype_b, [], 0) for _ in range(pop_sizes[0])]\n #plant_pop = [org.Plant(haplotype_p, [], 0) for _ in range(pop_sizes[1])]\n plant_pop = [org.Plant(gene, [], None)\n for gene in np.random.uniform(-1, 1, (pop_sizes[1], gene_sizes[1]))]\n return bacteria_pop, plant_pop\n\n\ndef stat_av_dist_to_closest(transformed_genes, plant_pop, epoch, **kwargs):\n sm = 0\n for trans_gene in transformed_genes:\n mn = 10000\n for plant in plant_pop:\n mn = min(mn, npl.norm(trans_gene - plant.gene))\n sm += mn\n return epoch, sm / len(transformed_genes)\n\n\ndef stat_av_dist_to_anc(bacteria_pop, ancestral, epoch, **kwargs):\n return epoch, np.mean([npl.norm(bacteria.gene - ancestral.gene) for bacteria in bacteria_pop])\n\n\ndef stat_plant_percentage(transformed_genes, plant_pop, epoch, **kwargs):\n res = [0] * len(plant_pop)\n for trans_gene in transformed_genes:\n mn = 10000\n ind = -1\n for i in range(len(plant_pop)):\n c = npl.norm(trans_gene - plant_pop[i].gene)\n if mn > c:\n mn = c\n ind = i\n res[ind] = 1\n return epoch, sum(res) / len(res)\n\n\ndef stat_mean_dist(mean_dist, epoch, **kwargs):\n return epoch, mean_dist\n\ndef fitness_vis(fitness, s_in, s_out, path):\n if (s_out != 2):\n return\n fig = plt.figure()\n\n #dirs = np.random.random((3, s_in))\n dirs = []\n for i in range(s_in):\n vec = np.zeros(s_in)\n vec[i] += 1.0\n dirs.append(vec)\n\n out_x, out_y, out_c = [], [], []\n step = 0.001\n dist = 0.25\n nstep = int(dist / step)\n\n cc = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 0.0]])\n\n cnt = 0\n for i in dirs:\n for j in range(nstep):\n lul = fitness.run(i * step * j)\n out_x.append(lul[0])\n out_y.append(lul[1])\n out_c.append(tuple(cc[cnt] * (j / nstep)))\n cnt += 1\n\n plt.scatter(out_x, out_y, c=out_c, s=2)\n zim = fitness.run(np.zeros(s_in))\n plt.scatter([zim[0]], [zim[1]], c=[(1.0, 0.0, 1.0)])\n plt.grid(True)\n plt.subplots_adjust(top=0.85)\n plt.savefig(path, dpi=100)\n plt.close(fig)\n\n\ndef stat_plant_disp(plant_pop, epoch, **kwargs):\n genes = [plant.gene for plant in plant_pop]\n mean_vec = np.mean(genes, axis=0)\n res = sum([sqlen(gene - mean_vec) for gene in genes]) / len(plant_pop)\n return epoch, res\n\ndef stat_bact_disp(transformed_genes, epoch, **kwargs):\n mean_vec = np.mean(transformed_genes, axis=0)\n res = sum([sqlen(gene - mean_vec) for gene in transformed_genes]) / len(transformed_genes)\n return epoch, res\n\ndef save_2d(t_bact_genes, t_plant_genes, epoch, name, title):\n fig = plt.figure()\n plt.scatter(*zip(*t_bact_genes), color=(0, 0, 0, 0.07))\n plt.scatter(*zip(*t_plant_genes), color=(1, 0, 0, 0.5))\n #plt.title(title)\n props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n plt.grid(True)\n plt.subplots_adjust(top=0.85)\n plt.savefig(os.path.join(name, 'epoch_' + str(epoch) + '.png'), dpi=300)\n plt.close(fig)\n\ndef save_3d(t_bact_genes, t_plant_genes, epoch, name, title):\n plt.clf()\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(*zip(*t_bact_genes), color=\"black\")\n ax.scatter(*zip(*t_plant_genes), color=\"red\")\n #plt.figtext(title)\n plt.figtext(0.05, 0.95, title, fontsize=14,\n verticalalignment='top', bbox=props)\n plt.savefig(os.path.join(name, 'epoch_' + str(epoch) + '.png'), dpi=100)\n\n if (epoch % 50 == 0):\n plt.show()\n else:\n plt.close()\n\ndef pop_distance(t_bact_genes, t_plant_genes):\n d = []\n\n for k in range(4, 15):\n bact_clustered = kmeans_cluster(t_bact_genes, k)\n plant_clustered = kmeans_cluster(t_plant_genes, k)\n mtx1, mtx2, disparity = scipy.spatial.procrustes(bact_clustered, plant_clustered)\n d.append(disparity)\n return min(d)\n\ndef kmeans_cluster(a, k):\n model = sklc.KMeans(k, n_init=10)\n model.fit(a)\n return model.cluster_centers_\n\ndef normed_distance_db(bact_pop, plant_pop, bact_db, plant_db):\n d1, d2 = distance_db(bact_pop, bact_db), distance_db(plant_pop, plant_db)\n return d1 / Bacteria.mut_v, d2 / Plant.mut_v\n\ndef distance_db(population, db):\n sum = 0\n\n for org in population:\n if len(org.parent_ids) != 0:\n sum += npl.norm(org.gene - db[org.parent_ids[0]]) / len(org.parent_ids)\n\n return sum / len(population)\n\ndef update_db(bact_pop, plant_pop, bact_db, plant_db, epoch, n):\n if epoch == 0 or epoch % n != 0:\n return update_simple_db(bact_pop, bact_db), update_simple_db(plant_pop, plant_db)\n else:\n return update_and_erase_db(bact_pop, bact_db), update_and_erase_db(plant_pop, plant_db)\n\ndef update_simple_db(population, db = dict()):\n for org in population:\n if org.g_id not in db:\n db[org.g_id] = org.gene\n\n return db\n\ndef update_and_erase_db(population, db):\n new_db = dict()\n for org in population:\n for db_id in org.parent_ids:\n new_db[db_id] = db[db_id]\n new_db[org.g_id] = org.gene\n return new_db\n\ndef flush_file(file):\n file.flush()\n os.fsync(file)\n\ndef uniform_labels(t_genes, k, mn, mx):\n siz = len(mn)\n probs = np.array([0 for _ in range(k ** siz)])\n for g in t_genes:\n coords = ((g - mn) / (mx - mn) * (k - 1e-4)).astype(int)\n\n label = 0\n for i in coords:\n label = label * k + i\n probs[label] += 1\n probs = probs / np.sum(probs)\n return probs\n\ndef update_t_db(population, db, fitness, epoch):\n if (epoch % 100 == 0):\n db = dict()\n\n res = []\n for org in population:\n if org.g_id not in db:\n db[org.g_id] = fitness.run(org.gene)\n res.append(db[org.g_id])\n\n return res, db\n\ndef intra_labeling(pop_genes, k):\n mn = np.min(pop_genes, axis=0)\n mx = np.max(pop_genes, axis=0)\n\n flag = False\n for i in range(len(mx)):\n if (mx[i] == mn[i]):\n flag = True\n\n if (flag):\n return ([1] + [0] * (len(pop_genes) - 1))\n probs = uniform_labels(pop_genes, k, mn, mx)\n\n return probs\n\ndef inter_labeling(t_bact_genes, t_plant_genes, k):\n p_mn = np.min(t_plant_genes, axis=0)\n b_mn = np.min(t_bact_genes, axis=0)\n mn = np.min(np.array([b_mn, p_mn]), axis = 0)\n\n p_mx = np.max(t_plant_genes, axis=0)\n b_mx = np.max(t_bact_genes, axis=0)\n mx = np.max(np.array([b_mx, p_mx]), axis=0)\n\n p_probs = uniform_labels(t_plant_genes, k, mn, mx)\n b_probs = uniform_labels(t_bact_genes, k, mn, mx)\n\n return b_probs, p_probs\n\ndef pop_entropy(probs):\n sm = 0\n for i in probs:\n if (i != 0):\n sm -= i * np.log(i)\n return sm\n\ndef mc_diversity(pop, samples):\n sm = 0\n for i in range(samples):\n ind = np.random.randint(0, len(pop), 2)\n sm += np.linalg.norm(pop[ind[0]].gene - pop[ind[1]].gene)\n\n return sm / samples\n\ndef hell_dist(b_probs, p_probs):\n score = 0\n for i in range(len(b_probs)):\n score += np.sqrt(p_probs[i] * b_probs[i]);\n\n return np.sqrt(1 - score);","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"644438256","text":"#encoding=utf-8\n# dna序列\n\n#a、t、g、c分别代表数字0,1,2,3\ndef j2d(j=\"\"):\n if j==\"a\":return 0\n elif j==\"t\":return 1\n elif j==\"g\":return 2\n elif j==\"c\":return 3\n pass\n\ndef d2j(j=63):\n if j==0:return \"a\"\n elif j==1:return \"t\"\n elif j==2:return \"g\"\n elif j==3:return \"c\"\n pass\n\n#核苷酸转代表值\ndef nucle2digital(nucle = \"\"):\n try:\n return j2d(nucle[0])*16+j2d(nucle[1])*4+j2d(nucle[2])\n except:\n import random\n return random.choice(xrange(64))\n pass\ndef digital2nucle(d):\n return d2j(d / 16)+d2j((d-d/16*16)/4)+d2j((d - d/4*4))\n\ndef data2vec(data,startcutfrom=0):\n '''\n 得到切分DNA序列 ------------------(还无法确定起始密码子)\n :param data:\n :return:\n '''\n if startcutfrom==0:tmp = data\n elif startcutfrom==1:tmp =data[1:]\n elif startcutfrom==2:tmp = data[2:]\n arr1 = []\n while(len(tmp)!=0):\n arr1.append(tmp[:3])\n tmp= tmp[3:]\n tmp=data[1:]\n\n return arr1[:-1]\n\ndef data2digitalVec(data,startcutfrom=0):\n '''\n 得到序列的特征向量\n :param data:string DNA序列\n :return:\n '''\n\n digitalV = []\n\n for i in range(64):\n digitalV.append(0)\n for i in data2vec(data,startcutfrom):\n index = nucle2digital(i)\n digitalV[index]+=1\n return digitalV\n\ndef data2digitalVec16(data, startcutfrom=0):\n '''\n 得到序列的特征向量,压缩后\n :param data:string DNA序列\n :return:\n '''\n partern = [40,\n 58,\n 43,\n 10,\n 0,\n 32,\n 34,\n 42,\n 2,\n 14,\n 23,\n 46,\n 44,\n 3,\n 5,\n 48,\n\n 21,\n 20,\n 16,\n 17,\n 1,\n 29,\n 37,\n 53,\n 4,\n 19,\n 13,\n 22,\n 41,\n 26\n ]\n digitalV = []\n\n for i in range(len(partern)):\n digitalV.append(0)\n for i in data2vec(data, startcutfrom):\n index = nucle2digital(i)\n if partern.count(index)!=0:\n digitalV[partern.index(index)] += 1\n return digitalV\n\n\n","sub_path":"tools/dna2vec/basic_convert.py","file_name":"basic_convert.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"42620721","text":"#!/usr/bin/python3\n\"\"\"Show nicely formatted status, mileage charge percent etc \"\"\"\n\nimport argparse\nimport logging\nimport json\nimport os\nimport time\n\nfrom datetime import datetime\nfrom math import radians, sin, cos, acos\n\nfrom bimmer_connected.account import ConnectedDriveAccount\nfrom bimmer_connected.country_selector import get_region_from_name, valid_regions\nfrom bimmer_connected.vehicle import VehicleViewDirection\n\ndef main() -> None:\n \"\"\"Main function.\"\"\"\n logging.basicConfig(level=logging.CRITICAL) \n\n parser = argparse.ArgumentParser(description='script to show nicely foramted status mileage etc ')\n subparsers = parser.add_subparsers(dest='cmd')\n subparsers.required = True\n\n status_parser = subparsers.add_parser('status', description='get current status of the vehicle')\n _add_default_arguments(status_parser)\n _add_position_arguments(status_parser)\n\n args = parser.parse_args()\n args.func(args)\n\n\ndef get_status(args) -> None:\n \"\"\"Get the vehicle status.\"\"\"\n account = ConnectedDriveAccount(args.username, args.password, get_region_from_name(args.region))\n if args.lat and args.lng:\n for vehicle in account.vehicles:\n vehicle.set_observer_position(args.lat, args.lng)\n account.update_vehicle_states()\n\n for vehicle in account.vehicles:\n print ()\n print(vehicle.name)\n \"\"\"print('VIN: {}'.format(vehicle.vin))\"\"\"\n miles = 1.609344\n mileage = int (vehicle.state.mileage / miles)\n print('mileage: {:0}'.format(mileage))\n \n maxRange = vehicle.state.maxRangeElectric / miles\n range = vehicle.state.remainingRangeElectricMls\n\n print('E-Range: {} miles'.format(range))\n print('Battery: {}%'.format(vehicle.state.chargingLevelHv ))\n\n position = vehicle.state.position\n\n \"\"\" home location \"\"\" \n hlat = radians (53.429768)\n hlon = radians (-2.757043)\n\n lat = radians (position[\"lat\"])\n lon = radians (position[\"lon\"])\n\n dist = 6378 * acos(sin(hlat)*sin(lat) + cos(hlat)*cos(lat)*cos(hlon - lon))\n dist = dist / miles\n if dist > 0 :\n print(\"Location: %.1f miles from home\" % dist )\n else :\n print(\"Location: home\")\n\n sinceCharge = round( maxRange - range,1)\n print (\"Distance since last charge: {} miles\" .format(sinceCharge))\n\n BASE_URL = 'https://{server}/webapi/v1'\n VEHICLES_URL = BASE_URL + '/user/vehicles'\n VEHICLE_VIN_URL = VEHICLES_URL + '/{vin}'\n VEHICLE_TRIP_URL = VEHICLE_VIN_URL + '/statistics/lastTrip'\n response = account.send_request(\n VEHICLE_TRIP_URL.format(server=account.server_url, vin=vehicle.vin), logfilename='status',\n params=\"\")\n lastTrip = response.json()['lastTrip']\n print ()\n print (\"Last Trip:\")\n\n date = datetime.strptime(lastTrip['date'],'%Y-%m-%dT%H:%M:%S+0100')\n print (date)\n duration = lastTrip[\"duration\"]\n distance = lastTrip[\"totalDistance\"]\n distance = round (distance / miles ,1)\n print (\"{} miles in {} minutes\" .format(distance,duration))\n\n\t# convert kWh/100km to miles / kWh\n mpk = round (100 / (lastTrip['avgElectricConsumption'] * miles ),2)\n print (\"{} mi/kWh\" .format(mpk))\n\n print (\"Efficiency: {} /5.0\" .format(lastTrip['efficiencyValue'] * 5.0))\n\ndef _add_default_arguments(parser: argparse.ArgumentParser):\n \"\"\"Add the default arguments username, password, region to the parser.\"\"\"\n parser.add_argument('username', help='Connected Drive user name')\n parser.add_argument('password', help='Connected Drive password')\n parser.add_argument('region', choices=valid_regions(), help='Region of the Connected Drive account')\n\n\ndef _add_position_arguments(parser: argparse.ArgumentParser):\n \"\"\"Add the lat and lng attributes to the parser.\"\"\"\n parser.add_argument('lat', type=float, nargs='?', const=0.0,\n help='optional: your gps latitide (as float)')\n parser.add_argument('lng', type=float, nargs='?', const=0.0,\n help='optional: your gps longitude (as float)')\n parser.set_defaults(func=get_status)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"bimmer_connected/status.py","file_name":"status.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"260951857","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nsns.set()\nsns.set_style(\"whitegrid\")\n\ndata = np.load(\"affectations.npy\")\n\ndef filter_func(item):\n return len(np.unique(item)) == len(item)\n\n\nfilter_iterable = filter(filter_func, data)\nfiltered_data = np.array([item for item in filter_iterable])\n\n#filtered_data = data\n\nprepared_data = []\n\nfor d in filtered_data:\n for i in range(filtered_data.shape[1]):\n prepared_data.append([\"Base {}\".format(i), \"Agent {}\".format(d[i])])\n\n\"\"\"\nfor base in range(filtered_data.shape[1]):\n base_data = []\n\n for agent in range(filtered_data.shape[1]):\n count = len(np.where(filtered_data[:, base] == agent)[0])\n base_data.append(count)\n\n prepared_data.append(base_data)\n\"\"\"\n\n\ndataframe = pd.DataFrame(prepared_data, columns=['Bases', 'Agents'])\nax = sns.countplot(x=\"Bases\", hue=\"Agents\", data=dataframe)\nplt.savefig(\"distribution.png\")\nplt.show()","sub_path":"entropy.py","file_name":"entropy.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"333944998","text":"from multiprocessing import Pool\n\ndef runMetropolis(chainIndex):\n import sys\n import os\n DIRNAME = os.path.dirname(__file__)\n sys.path.append(os.path.join(DIRNAME, \"..\", \"..\", \"src\"))\n\n from LCA import PrepareRecurrentWeights, RunLCASimulation, GetValueInputZeroReference, \\\n getValueInput2Attributes2Choices\n from LUT import prepareStdNormalLUT, SampleFromLUT\n\n import numpy as np\n import time\n import pickle\n from scipy.stats import skew, truncnorm, chisquare\n\n # read observed data\n data = np.genfromtxt(\"dataZeroSure_cleaned_250_10500_zScore3.csv\", delimiter=',')[:, 1:]\n allStakes = np.unique(data[:, -2:], axis=0)\n\n np.random.seed()\n\n LUTInterval = 0.0001\n numAccumulators = 2\n stdNormalLUT = prepareStdNormalLUT(LUTInterval)\n sampleFromLUT = SampleFromLUT(stdNormalLUT)\n sampleFromZeroMeanLUT = lambda stdDev: sampleFromLUT(0, stdDev, numAccumulators)\n\n # set-up the LCA\n identityUtilityFunction = lambda x: x\n getValueInput = GetValueInputZeroReference(identityUtilityFunction)\n\n maxTimeSteps = 750\n deltaT = 0.02\n prepareRecurrentWeights = PrepareRecurrentWeights(numAccumulators)\n lca = RunLCASimulation(getValueInput, sampleFromZeroMeanLUT, prepareRecurrentWeights, maxTimeSteps, deltaT)\n\n def getStartingActivation(startingBias, threshold):\n if startingBias < 0:\n return [-1*startingBias*threshold, 0]\n else:\n return [0, startingBias*threshold]\n\n getChoiceAttributes = lambda gain, loss: np.array([[0, 0], [gain, loss]])\n\n def getAllThresholds(thresholdBias, threshold):\n if thresholdBias < 0:\n return [(1+thresholdBias)*threshold, threshold]\n else:\n return [threshold, threshold*(1-thresholdBias)]\n\n lcaWrapper = lambda gain, loss, decay, competition, noiseStdDev, nonDecisionTime, threshold, constantInput1, constantInput2: \\\n lca((0.5, 0.5), getChoiceAttributes(gain, loss), getStartingActivation(0, threshold), decay, competition, (constantInput1, constantInput2),\n noiseStdDev, nonDecisionTime, getAllThresholds(0, threshold))\n\n\n def selectConditionTrials(data, gain, loss):\n selectedData = data[data[:, 2] == gain][:]\n selectedData = selectedData[selectedData[:, 3] == loss][:]\n return selectedData\n\n def computePData(data, gain, loss):\n conditionTrialData = selectConditionTrials(data, gain, loss)\n responses = conditionTrialData[:, 0]\n return np.mean(responses)\n\n def computeRTStatsData(data, gain, loss, choice):\n conditionTrialData = selectConditionTrials(data, gain, loss)\n dataForThisChoice = conditionTrialData[conditionTrialData[:, 0] == choice]\n if np.shape(dataForThisChoice)[0] == 0:\n return (0, 0, 0)\n reactionTimes = dataForThisChoice[:, 1]\n return (np.mean(reactionTimes), np.std(reactionTimes), skew(reactionTimes))\n\n def filterFunction(tup):\n if tup[-1] != -1:\n return True\n else:\n return False\n\n\n # define the cost function\n class CostFunction:\n def __init__(self, numSimulationsPerCondition, allStakes):\n self.numSimulationsPerCondition = numSimulationsPerCondition\n self.allStakes = allStakes\n\n def __call__(self, parameters):\n allModelData = np.zeros(4)\n for stakes in self.allStakes:\n gainValue, lossValue = stakes\n allSimulations = [lcaWrapper(gainValue, lossValue, *parameters) for _ in\n range(self.numSimulationsPerCondition)]\n allValidResponseSimulations = list(filter(filterFunction, allSimulations))\n numValidResponses = len(allValidResponseSimulations)\n if numValidResponses < self.numSimulationsPerCondition / 3:\n return (-1, parameters[3])\n _, allModelRTs, allModelResponses = zip(*allValidResponseSimulations)\n modelStakes = np.hstack(\n (np.full((numValidResponses, 1), gainValue), np.full((numValidResponses, 1), lossValue)))\n modelDataForStakes = np.hstack(\n (np.array(allModelResponses).reshape(-1, 1), np.array(allModelRTs).reshape(-1, 1), modelStakes))\n allModelData = np.vstack((allModelData, modelDataForStakes))\n\n allModelData = allModelData[1:, :]\n\n actualDataMeanRT = np.mean(data[:, 1])\n simDataMeanRT = np.mean(allModelData[:, 1])\n delta = simDataMeanRT - actualDataMeanRT\n if delta > parameters[3]:\n delta = parameters[3]\n\n allModelData[:, 1] = allModelData[:, 1] - delta\n\n totalCost = 0\n quantiles = np.array([0.1, 0.3, 0.5, 0.7, 0.9])\n observedProportionsChoiceWise = np.array([0.1, 0.2, 0.2, 0.2, 0.2, 0.1])\n for stakes in self.allStakes:\n gain, loss = stakes\n observedTrials = selectConditionTrials(data, gain, loss)\n numObservedTrials = np.shape(observedTrials)[0]\n modelTrials = selectConditionTrials(allModelData, gain, loss)\n numModelTrials = np.shape(modelTrials)[0]\n for choice in range(2):\n observedTrialsForChoice = observedTrials[observedTrials[:, 0] == choice]\n observedRTsForChoice = observedTrialsForChoice[:, 1]\n numObservedRTsForChoice = np.size(observedRTsForChoice)\n observedPOfThisChoice = numObservedRTsForChoice / numObservedTrials\n\n if numObservedRTsForChoice < 5:\n continue\n\n quantilesBoundaries = np.quantile(observedRTsForChoice, quantiles)\n\n expectedFrequencies = \\\n np.histogram(observedRTsForChoice, bins=np.concatenate(([0], quantilesBoundaries, [100])))[\n 0] / numObservedTrials\n\n if numObservedRTsForChoice == 5 or 0 in expectedFrequencies:\n expectedFrequencies = observedProportionsChoiceWise * observedPOfThisChoice\n\n modelTrialsForChoice = modelTrials[modelTrials[:, 0] == choice]\n modelRTsForChoice = modelTrialsForChoice[:, 1]\n modelFrequencies = \\\n np.histogram(modelRTsForChoice, bins=np.concatenate(([0], quantilesBoundaries, [100])))[\n 0] / numModelTrials\n\n totalCost += chisquare(modelFrequencies, expectedFrequencies)[0]\n return (totalCost, parameters[3] - delta)\n\n\n costFunction = CostFunction(75, allStakes)\n bounds = ((0, 5), (0, 5), (0, 75), (0, 2), (0, 30), (0, 75), (0, 75))\n # decay, competition, noiseStdDev, nonDecisionTime, threshold, constantInput1, constantInput2\n rangeOfParams = np.diff((np.array(bounds))).flatten()\n initialParameterVariance = rangeOfParams/(1.5*numTotalChains)\n parameterVarianceMultiplier = np.full(np.shape(initialParameterVariance), 0.99)\n\n\n SAVE_DIRECTORY = 'savedModels/onlyFixedUtilityBias'.format(str(bounds))\n if not os.path.exists(SAVE_DIRECTORY):\n os.makedirs(SAVE_DIRECTORY)\n\n\n\n SAVEFILE = os.path.join(SAVE_DIRECTORY, '{}.pickle'.format(str(chainIndex)))\n\n def pickleRecord(record):\n saveFile = open(SAVEFILE, 'wb')\n pickle.dump(record, saveFile)\n saveFile.close()\n\n def generateProposalParams(currentParams, variances):\n np.random.seed()\n newParams = []\n for i in range(len(currentParams)):\n myclip_a = bounds[i][0]\n myclip_b = bounds[i][1]\n my_mean = currentParams[i]\n my_std = variances[i]\n if my_std == 0:\n newParam = my_mean\n else:\n a, b = (myclip_a - my_mean) / my_std, (myclip_b - my_mean) / my_std\n newParam = truncnorm.rvs(a, b, loc=my_mean, scale=my_std)\n newParams.append(newParam)\n\n return newParams\n\n try:\n saveFile = open(SAVEFILE, \"rb\")\n record = pickle.load(saveFile)\n bestParameters = record[-1, :-1]\n minimumCost = record[-1, -1]\n # print(\"Best parameters: \", bestParameters, \" Best cost: \", minimumCost)\n numIterationsPrevious = np.shape(record)[0]\n # (\"NumIterations: \", numIterationsPrevious)\n parameterVarianceMultiplier = parameterVarianceMultiplier**(numIterationsPrevious//100)\n # print(\"Num Iterations: \", numIterationsPrevious, \" Multiplier: \", parameterVarianceMultiplier)\n parameterVariance = np.multiply(initialParameterVariance, parameterVarianceMultiplier)\n except:\n numIterationsPrevious = 0\n counter = 0\n while True:\n print(counter)\n counter += 1\n # initialParameterValues = generateProposalParams(meanStartingPointForSearch, initialParameterVariance)\n low, high = list(zip(*bounds))\n initialParameterValues = np.random.RandomState().uniform(low, high)\n # print(initialParameterValues)\n initialCost, adjustedContTime = costFunction(initialParameterValues)\n if initialCost != -1:\n initialParameterValues[3] = adjustedContTime\n break\n\n print(\"Chain: \", chainIndex, \"Initial value identified: \", initialParameterValues, \" Cost: \", initialCost)\n\n bestParameters = initialParameterValues\n parameterVariance = np.asarray(initialParameterVariance)\n minimumCost = initialCost\n record = np.hstack((bestParameters, minimumCost))\n\n pickleRecord(record)\n\n minimizationIteration = numIterationsPrevious\n pickleFlag = False\n while True:\n minimizationIteration += 1\n startTime = time.time()\n # decrease the value of variance\n if minimizationIteration % 100 == 0 and minimizationIteration != 0:\n parameterVariance = parameterVarianceMultiplier * parameterVariance\n\n # propose new parameters\n newParameters = generateProposalParams(bestParameters, parameterVariance)\n\n # compute cost\n cost, adjustedNonDecisionTime = costFunction(newParameters)\n\n if cost != -1:\n # update parameters\n if cost < minimumCost:\n pickleFlag = True\n # print(\"updating parameters and cost\")\n bestParameters = newParameters\n bestParameters[3] = adjustedNonDecisionTime\n minimumCost = cost\n else:\n pickleFlag = False\n\n # record best parameters\n iterationRecord = np.hstack((bestParameters, minimumCost))\n record = np.vstack((record, iterationRecord))\n\n if pickleFlag:\n pickleRecord(record)\n\n\n # time for iteration\n endTime = time.time()\n iterationTime = endTime - startTime\n # print(\"Iteration: {} Time: {}\".format(minimizationIteration, iterationTime))\n # print(\"Proposed Value of params: \", newParameters)\n # print(\"Best Value of params: \", bestParameters)\n # print(\"Cost: \", cost)\n # print(\"Best cost: \", minimumCost)\n # print(\"-------------------------------\")\n\n\n print('Chain: {}, iteration: {}, Best cost: {}'.format(chainIndex, minimizationIteration, minimumCost))\n\n\nnumTotalChains = 5\n\np = Pool(numTotalChains)\np.map(runMetropolis, range(numTotalChains))","sub_path":"LCA/dataset2/singleBiasModels/fitOnlyFixedUtilityBias.py","file_name":"fitOnlyFixedUtilityBias.py","file_ext":"py","file_size_in_byte":11491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"14230344","text":"from flaskblog import app\nimport unittest\n\nclass FlaskTestCase(unittest.TestCase):\n\n def test_homepage(self):\n tester = app.test_client(self)\n response = tester.get(\"/home\")\n self.assertEqual(response.status_code, 200)\n self.assertTrue(b'Welcome to Kinetic Labs' in response.data)\n self.assertTrue(b'New messages every time you refresh' in response.data)\n\n def test_aboutpage(self):\n tester = app.test_client(self)\n response = tester.get(\"/about\")\n self.assertEqual(response.status_code, 200)\n self.assertTrue((b'About Page' in response.data))\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"288530036","text":"from flask import current_app as app, render_template, request, redirect, jsonify, url_for, Blueprint, session\nfrom CTFd.models import db\nfrom .models import Containers\nfrom CTFd.utils.decorators import (\n during_ctf_time_only,\n authed_only,\n admins_only,\n cache\n)\nfrom . import utils\nimport math\n\ndef load(app):\n app.db.create_all()\n containers = Blueprint('containers', __name__, template_folder='templates')\n\n @containers.route('/containers', methods=['GET'])\n @during_ctf_time_only\n @authed_only\n def list_container():\n containers_per_page = 10\n # Get page if page parameter is set in the url\n page = 1\n if 'page' in request.args:\n page = int(request.args.get('page'))\n \n # Get amount of items\n count = Containers.query.filter(Containers.owner==session[\"id\"]).filter(Containers.deleted == False).count()\n\n # Get all containers that the user owns and that are not deleted by the user\n containers = Containers.query.filter(Containers.owner==session[\"id\"]).filter(Containers.deleted == False).paginate(page=page, per_page=containers_per_page).items\n\n for c in containers:\n # We get the container stauts by using the docker inspect command\n c.status = utils.container_status(c.name)\n # Ports are also from inspect\n c.ports = ', '.join(utils.container_ports(c.name, verbose=True))\n # We render the container page with all the users containers\n return render_template('containers.html', containers=containers, pages=math.ceil(count/containers_per_page), page=page, admin=False, base=\"base.html\")\n\n\n @containers.route('/containers//stop', methods=['POST'])\n @during_ctf_time_only\n @authed_only\n def stop_container(container_id):\n container = Containers.query.filter_by(id=container_id).first_or_404()\n # Check if the user actually owns the container\n if container.owner is not session[\"id\"]:\n return '0'\n if utils.container_stop(container.name):\n return '1'\n else:\n return '0'\n\n\n @containers.route('/containers//start', methods=['POST'])\n @during_ctf_time_only\n @authed_only\n def run_container(container_id):\n container = Containers.query.filter_by(id=container_id).first_or_404()\n # Check if the user actually owns the container\n if container.owner is not session[\"id\"]:\n return '0'\n # Check if the container still exists, if not we use the image\n if utils.container_status(container.name) == 'missing':\n if utils.run_image(container.name):\n return '1'\n else:\n return '0'\n else:\n if utils.container_start(container.name):\n return '1'\n else:\n return '0'\n\n\n @containers.route('/containers//delete', methods=['POST'])\n @during_ctf_time_only\n @authed_only\n def delete_container(container_id):\n container = Containers.query.filter_by(id=container_id).first_or_404()\n # Check if the user actually owns the container\n if container.owner is not session[\"id\"]:\n return '0'\n if utils.delete_image(container.name):\n # We don't delete the container info from the db because we want to log them\n container.deleted = True\n db.session.commit()\n db.session.close()\n return '1'\n\n\n @containers.route('/containers/new', methods=['POST'])\n @during_ctf_time_only\n @authed_only\n def new_container():\n # We append the username so that the user can only access containers in their own namespace\n name = session[\"name\"] + \"-\" + request.form.get('name')\n # Docker requires lowercase lettering\n name = name.lower()\n # If another container has the same name, add a random string to it\n if utils.container_already_exists(name):\n name += '_' + utils.randomString(8)\n # Check that the name is valid\n if not set(name) <= set('abcdefghijklmnopqrstuvwxyz0123456789-_'):\n return redirect(url_for('containers.list_container'))\n owner = session[\"id\"]\n buildfile = request.form.get('buildfile')\n # Files are the associated files you can upload\n files = request.files.getlist('files[]')\n utils.create_image(owner=owner, name=name, buildfile=buildfile, files=files)\n utils.run_image(name)\n return redirect(url_for('containers.list_container'))\n\n\n @containers.route('/containers/import', methods=['POST'])\n @during_ctf_time_only\n @authed_only\n def import_container():\n # Appending the namespace\n name = session[\"name\"] + \"-\" + request.form.get('name')\n # Check that the name is valid\n if not set(name) <= set('abcdefghijklmnopqrstuvwxyz0123456789-_'):\n return redirect(url_for('containers.list_container'))\n utils.import_image(name=name)\n return redirect(url_for('containers.list_container'))\n \n @containers.route('/admin/containers/overview', methods=['GET'])\n @admins_only\n def admin_overview():\n containers_per_page = 10\n # Get page if page parameter is set in the url\n page = 1\n if 'page' in request.args:\n page = int(request.args.get('page'))\n \n # Get page if page parameter is set in the url\n running = False\n if 'running' in request.args:\n if request.args.get('running') == 'True':\n running = True\n\n # The admin can view all past and present containers\n # Get amount of items\n all_containers = Containers.query\n # Check if the admin wants to display only running containers\n if running:\n for c in all_containers:\n if utils.container_status(c.name) == 'running':\n c.running = True\n all_containers = all_containers.filter_by(running=True)\n\n # Get amount of containers and divide them into pages\n count = all_containers.count()\n containers = all_containers.paginate(page=page, per_page=containers_per_page).items\n # Add info about the containers from docker inspect\n for c in containers:\n c.status = utils.container_status(c.name)\n c.ports = ', '.join(utils.container_ports(c.name, verbose=True))\n\n return render_template('containers.html', containers=containers, pages=math.ceil(count/containers_per_page), page=page, running=running, admin=True, base=\"admin/base.html\")\n \n @containers.route('/admin/containers/', methods=['GET'])\n @admins_only\n def get_dockerfile(container_id):\n # The admin can view the buildfile of all containers\n container = Containers.query.filter_by(id=container_id).first_or_404()\n # tags are so that the newlines are interperated\n return render_template('container_buildfile.html', container_name=container.name, buildfile=container.buildfile)\n\n @containers.route('/admin/conatainers/delete_all_deleted', methods=['POST'])\n @admins_only\n def delete_all():\n # The admin can view the buildfile of all containers\n try:\n rows_deleted_count = Containers.query.filter_by(deleted=True).delete()\n db.session.commit()\n return '1'\n except:\n db.session.rollback()\n return '0'\n\n app.register_blueprint(containers)","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"425599524","text":"\"\"\"policy.py\n\nRequirements: $PATH must include pomdpsol-appl for 'appl' policies and\npomdpsol-aitoolbox for 'aitoolbox' policies.\n\n\"\"\"\nfrom __future__ import division\nimport collections\nimport os\nimport time\nimport copy\nimport random\nimport math\nimport subprocess\nimport numpy as np\nfrom .pomdp import POMDPPolicy, POMDPModel\nfrom . import util\nfrom .util import ensure_dir\nfrom . import work_learn_problem as wlp\nfrom . import param\n\nZMDP_ALIAS = os.environ.get('ZMDP_ALIAS', 'pomdpsol-zmdp')\n\nclass Policy:\n \"\"\"Policy class\n\n Assumes policy files for appl policies live in relative folder 'policies'\n\n \"\"\"\n def __init__(self, policy_type, n_worker_classes, params_gt,\n **kwargs):\n #print 'Reinitializing policy'\n default_discount = 0.99\n self.policy = policy_type\n self.epsilon = kwargs.get('epsilon', None)\n self.explore_actions = kwargs.get('explore_actions', None)\n self.explore_policy = kwargs.get('explore_policy', None)\n self.thompson = bool(kwargs.get('thompson', False))\n self.hyperparams = kwargs.get('hyperparams', None)\n self.desired_accuracy = params_gt.get('desired_accuracy', None)\n\n if self.rl_p():\n name = kwargs['hyperparams']\n cls = getattr(param, name)\n self.model = POMDPModel(\n n_worker_classes, params=params_gt,\n hyperparams=cls(params_gt, n_worker_classes),\n estimate_all=True)\n if self.explore_policy is not None:\n self.explore_policy = Policy(\n policy_type=self.explore_policy['type'],\n n_worker_classes=n_worker_classes,\n params_gt=params_gt,\n **self.explore_policy)\n else:\n self.model = POMDPModel(n_worker_classes, params=params_gt)\n\n if self.policy in ('appl', 'zmdp'):\n self.discount = kwargs.get('discount', default_discount)\n self.timeout = kwargs.get('timeout', None)\n elif self.policy == 'aitoolbox':\n self.discount = kwargs.get('discount', default_discount)\n self.horizon = kwargs['horizon']\n elif self.policy == 'test_and_boot':\n self.teach_type = kwargs.get('teach_type', None)\n self.n_teach = kwargs.get('n_teach', 0)\n self.n_blocks = kwargs.get('n_blocks', None)\n if self.n_blocks != 0:\n self.n_test = kwargs['n_test']\n self.n_work = kwargs['n_work']\n self.accuracy = kwargs['accuracy']\n n_test_actions = len(\n [a for a in self.model.actions if a.is_quiz()])\n self.accuracy_window = kwargs.get('accuracy_window', None)\n if self.accuracy_window is None:\n self.accuracy_window = self.n_test * n_test_actions\n self.final_action = kwargs.get('final_action', 'work')\n elif self.policy != 'work_only':\n raise NotImplementedError\n\n self.params_estimated = dict()\n self.hparams_estimated = dict()\n self.estimate_times = dict()\n self.resolve_times = []\n self.external_policy = None\n self.use_explore_policy = False\n\n def rl_p(self):\n \"\"\"Policy does reinforcement learning.\"\"\"\n return self.epsilon is not None or self.thompson\n\n def get_epsilon_probability(self, worker, t, budget_frac):\n \"\"\"Return probability specified by the given exploration function.\n\n Exploration function is a function of the worker (w or worker)\n the current timestep (t), and the fraction of the exploration\n budget (f or budget_frac).\n\n WARNING: Evaluates the expression in self.epsilon without security\n checks.\n\n \"\"\"\n # Put some useful variable abbreviations in the namespace.\n w = worker\n f = budget_frac\n e = math.e\n if isinstance(self.epsilon, basestring):\n return eval(self.epsilon)\n else:\n return self.epsilon\n\n def prep_worker(self, model_filepath, policy_filepath, history,\n resolve_p=False,\n resolve_random_restarts=1,\n previous_workers=None, explore=None):\n \"\"\"Reestimate and resolve as needed.\n\n Args:\n history (.history.History): History of workers.\n IMPORTANT: Do not call .history.History.new_worker() before\n running this function or the worker count will be incorrect.\n resolve_p: Resolve or not.\n resolve_random_restarts (int): Number of random restarts to use\n when re-estimating model.\n previous_workers (Optional[int]): Number of previous workers.\n Defaults to one less than number of workers in history object.\n\n \"\"\"\n t = 0\n self.use_explore_policy = False\n\n estimate_p = self.rl_p() and resolve_p\n model = self.model\n if estimate_p:\n start = time.clock()\n model.estimate(history=history,\n last_params=(len(self.params_estimated) > 0),\n random_restarts=resolve_random_restarts)\n if self.thompson:\n model.thompson_sample()\n self.estimate_times[worker] = time.clock() - start\n self.params_estimated[worker] = copy.deepcopy(\n model.get_params_est())\n self.hparams_estimated[worker] = copy.deepcopy(model.hparams)\n if resolve_p:\n utime1, stime1, cutime1, cstime1, _ = os.times()\n self.external_policy = self.run_solver(\n model_filepath=model_filepath, policy_filepath=policy_filepath)\n utime2, stime2, cutime2, cstime2, _ = os.times()\n # All solvers are run as subprocesses, so count elapsed\n # child process time.\n self.resolve_times.append(cutime2 - cutime1 + \\\n cstime2 - cstime1)\n\n def get_best_action(self, history, belief=None):\n \"\"\"Get best action according to policy.\n\n If policy requires an external_policy, assumes it already exists.\n\n self.n_blocks should be None unless teaching actions disabled.\n\n Accuracy for test_and_boot policy is averaged across question\n types.\n\n Args:\n history (History object): Defined in history.py.\n\n Returns: Action index.\n\n \"\"\"\n valid_actions = self.get_valid_actions(history)\n model = self.model\n a_ask = model.actions.index(wlp.Action('ask'))\n a_boot = model.actions.index(wlp.Action('boot'))\n worker = history.n_workers() - 1\n current_AO = history.history[-1]\n if len(current_AO) == 0:\n current_actions = []\n current_observations = []\n else:\n current_actions, current_observations, _ = zip(*current_AO)\n n_actions = len(current_actions)\n\n # Get POMDP policy.\n rewards = self.external_policy.get_action_rewards(belief)\n valid_actions_with_rewards = set(valid_actions).intersection(\n set(rewards))\n if len(valid_actions_with_rewards) == 0:\n raise Exception('No valid actions in policy')\n max_reward = max(rewards.values())\n valid_rewards = dict((a, rewards[a]) for a in valid_actions_with_rewards)\n max_valid_reward = max(valid_rewards.values())\n if max_reward > max_valid_reward:\n raise Exception('Warning: best reward not available')\n # Take random best action.\n best_valid_action = random.choice(\n [a for a in valid_rewards if\n valid_rewards[a] == max_valid_reward])\n return best_valid_action\n\n def run_solver(self, model_filepath, policy_filepath):\n \"\"\"Run POMDP solver.\n\n Args:\n model_filepath (str): Path for input to POMDP solver.\n policy_filepath (str): Path for computed policy.\n\n Returns:\n policy (POMDPPolicy)\n\n \"\"\"\n model = self.model\n if self.policy == 'appl':\n with open(model_filepath, 'w') as f:\n model.write_pomdp(f, discount=self.discount)\n args = ['pomdpsol-appl',\n model_filepath,\n '-o', policy_filepath]\n if self.timeout is not None:\n args += ['--timeout', str(self.timeout)]\n _ = subprocess.check_output(args)\n return POMDPPolicy(policy_filepath,\n file_format='policyx')\n elif self.policy == 'aitoolbox':\n with open(model_filepath, 'w') as f:\n model.write_txt(f)\n args = ['pomdpsol-aitoolbox',\n '--input', model_filepath,\n '--output', policy_filepath,\n '--discount', str(self.discount),\n '--horizon', str(self.horizon),\n '--n_states', str(len(model.states)),\n '--n_actions', str(len(model.actions)),\n '--n_observations', str(len(model.observations))]\n _ = subprocess.check_output(args)\n return POMDPPolicy(policy_filepath,\n file_format='aitoolbox',\n n_states=len(model.states))\n elif self.policy == 'zmdp':\n with open(model_filepath, 'w') as f:\n model.write_pomdp(f, discount=self.discount)\n args = [ZMDP_ALIAS,\n 'solve', model_filepath,\n '-o', policy_filepath]\n if self.timeout is not None:\n args += ['-t', str(self.timeout)]\n _ = subprocess.check_output(args)\n return POMDPPolicy(policy_filepath,\n file_format='zmdp',\n n_states=len(model.states))\n\n\n def get_valid_actions(self, history):\n \"\"\"Return valid action indices based on the history.\"\"\"\n current_AO = history.history[-1]\n if len(current_AO) == 0:\n current_actions = []\n current_observations = []\n else:\n current_actions, current_observations, _ = zip(*current_AO)\n\n try:\n last_action = self.model.actions[current_actions[-1]]\n except IndexError:\n last_action = None\n return [i for i, a in enumerate(self.model.actions) if\n a.valid_after(last_action)]\n","sub_path":"crowdgating/policy.py","file_name":"policy.py","file_ext":"py","file_size_in_byte":10547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"100564858","text":"\ndef sum(current,max):\n if current-1):\n return\n if(resultMap['pos_tel_before']>0 and tmpResult.find(' ')>-1):\n print('tel_before {}'.format(resultMap['pos_tel_before']))\n telBefore=resultMap['tel_before'].split(':')\n if(len(telBefore)>1):\n telBeforeNew=telBefore[1]\n telAfter=tmpResult.split(':')\n if(len(telAfter)>1):\n telAfterNew=telAfter[1]\n lsStr1 = list(telAfterNew)\n for idx, val in enumerate(telAfterNew):\n if (val == ' '):\n lsStr1[idx] = telBeforeNew[idx]\n\n tmpResult = jaconv.z2h(tmpResult, digit=True, ascii=True)\n\n if(tmpResult.find('話')>-1):\n tmpResult=tmpResult.split('話')[1]\n if(tmpResult.find(':')>-1):\n tmpResult=tmpResult.split(':')[1]\n tmpResult = numberUtils.numberReplacement(tmpResult)\n strList=re.findall(r'\\d+', tmpResult)\n tmpResult=''.join(strList)\n if(len(tmpResult)>10):\n tmpResult=tmpResult[-10:-1]\n if(resultMap['3_tel']=='none'):#init value\n resultMap['3_tel'] = tmpResult\n elif(len(resultMap['3_tel'])6):\n print('output tel{} {}'.format('-'*10,tmpResult))\n if(tmpResult!='none'):\n resultMap['pos_tel_after']=i","sub_path":"receiptUtils/telUtils.py","file_name":"telUtils.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"414298512","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@Author: Kimmyzhang\r\n@Email: 902227553.com \r\n@File: kimmyzhang_20170908_03.py\r\n@Time: 2017/11/6 15:50\r\nQ3:\r\n酒馆有m个龙头,每个龙头出酒量相等,都为1.现有n名顾客,按照顺序1...n接酒,i号顾客接酒量为w_i。\r\n接酒开始时,1到m号顾客分别占领一个酒龙头,同时开始,并且一人接完后,下一人立刻接替。求总接酒时间?\r\n输入:\r\nn m\r\nw_i\r\n输出:\r\n总接酒时间\r\n样例输入:\r\n5 3\r\n1 2 3 4 5\r\n样例输出:\r\n7\r\n\"\"\"\r\n\r\n\r\n# 判断是否有位置进入\r\ndef get_empty_posi(nums):\r\n\r\n # 获得当前已经取完酒的位置\r\n zero_posi = []\r\n for i in range(len(nums)):\r\n if nums[i] == 0:\r\n zero_posi.append(i)\r\n return zero_posi\r\n\r\n\r\ndef solution_by_simu(n, m, w_list):\r\n\r\n # 初始时的酒量\r\n posi_list = [w for w in w_list[:m]]\r\n # 待进入酒桶的酒量\r\n remain_list = [w for w in w_list[m:]]\r\n\r\n time = 0 # 初始时间\r\n while max(posi_list) != 0:\r\n posi_list = [num - 1 for num in posi_list]\r\n temp_list = get_empty_posi(posi_list)\r\n len_temp = len(temp_list)\r\n if len_temp != 0:\r\n for i in range(len_temp):\r\n posi_list[temp_list[i]] = remain_list[i]\r\n del remain_list[i]\r\n remain_list.append(0)\r\n time += 1\r\n\r\n return time\r\n\r\n\r\nif __name__ == '__main__':\r\n n = 5\r\n m = 3\r\n w_list = list(range(1, n + 1))\r\n res = solution_by_simu(n, m, w_list)\r\n print(res)","sub_path":"20170908/kimmyzhang_20170908_03.py","file_name":"kimmyzhang_20170908_03.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"374694703","text":"from django.shortcuts import get_object_or_404, render\nfrom dnd.menu import menu_item, submenu_item, MenuItem\nfrom dnd.dnd_paginator import DndPaginator\nfrom dnd.filters import FeatFilter\nfrom dnd.models import Rulebook, FeatCategory, Feat\nfrom dnd.views import is_3e_edition, permanent_redirect_view, permanent_redirect_object\n\n\n@menu_item(MenuItem.CHARACTER_OPTIONS)\n@submenu_item(MenuItem.CharacterOptions.FEATS)\ndef feat_index(request):\n f = FeatFilter(request.GET, queryset=Feat.objects.select_related(\n 'rulebook', 'rulebook__dnd_edition').distinct())\n\n form_submitted = 1 if '_filter' in request.GET else 0\n\n paginator = DndPaginator(f.qs, request)\n\n return render(request, 'dnd/feats/feat_index.html', context={'feat_list': paginator.items(),\n 'paginator': paginator, 'filter': f, 'form_submitted': form_submitted,},)\n\n\n@menu_item(MenuItem.CHARACTER_OPTIONS)\n@submenu_item(MenuItem.CharacterOptions.FEAT_CATEGORIES)\ndef feat_category_list(request):\n feat_category_list = FeatCategory.objects.all()\n\n paginator = DndPaginator(feat_category_list, request)\n\n return render(request, 'dnd/feats/feat_category_list.html', context={'feat_category_list': paginator.items(),\n 'paginator': paginator,},)\n\n\n@menu_item(MenuItem.CHARACTER_OPTIONS)\n@submenu_item(MenuItem.CharacterOptions.FEAT_CATEGORIES)\ndef feat_category_detail(request, category_slug):\n feat_category = get_object_or_404(FeatCategory, slug=category_slug)\n feat_list = feat_category.feat_set.select_related('rulebook',\n 'rulebook__dnd_edition').all()\n\n if feat_category.slug == 'trait':\n request.submenu_item = MenuItem.CharacterOptions.TRAITS\n elif feat_category.slug == 'flaw':\n request.submenu_item = MenuItem.CharacterOptions.FLAWS\n elif feat_category.slug == 'skill-trick':\n request.submenu_item = MenuItem.CharacterOptions.SKILL_TRICKS\n\n paginator = DndPaginator(feat_list, request)\n\n return render(request, 'dnd/feats/feat_category_detail.html', context=\n {'feat_category': feat_category, 'feat_list': paginator.items(), 'paginator': paginator,\n 'i_like_it_url': request.build_absolute_uri(), 'inaccurate_url': request.build_absolute_uri(), },)\n\n\n@menu_item(MenuItem.CHARACTER_OPTIONS)\n@submenu_item(MenuItem.CharacterOptions.FEATS)\ndef feats_in_rulebook(request, rulebook_slug, rulebook_id):\n rulebook = get_object_or_404(Rulebook.objects.select_related('dnd_edition'),\n pk=rulebook_id)\n if not rulebook.slug == rulebook_slug:\n return permanent_redirect_view(request, 'feats_in_rulebook',\n kwargs={\n 'rulebook_slug': rulebook.slug,\n 'rulebook_id': rulebook_id, })\n\n feat_list = rulebook.feat_set.select_related('rulebook',\n 'rulebook__dnd_edition').all()\n\n paginator = DndPaginator(feat_list, request)\n\n return render(request, 'dnd/feats/feats_in_rulebook.html', context={'rulebook': rulebook,\n 'feat_list': paginator.items(), 'paginator': paginator,\n 'display_3e_warning': is_3e_edition(rulebook.dnd_edition),},)\n\n\n@menu_item(MenuItem.CHARACTER_OPTIONS)\n@submenu_item(MenuItem.CharacterOptions.FEATS)\ndef feat_detail(request, rulebook_slug, rulebook_id, feat_slug, feat_id):\n feat = get_object_or_404(\n Feat.objects.select_related('rulebook', 'rulebook__dnd_edition'),\n pk=feat_id)\n if (feat.slug != feat_slug or\n str(feat.rulebook.id) != rulebook_id or\n feat.rulebook.slug != rulebook_slug):\n return permanent_redirect_object(request, feat)\n\n feat_category_list = feat.feat_categories.select_related().all()\n required_feats = feat.required_feats.select_related('required_feat',\n 'required_feat__rulebook').all()\n required_by_feats = feat.required_by_feats.select_related('source_feat',\n 'source_feat__rulebook').all()\n required_skills = feat.required_skills.select_related('skill').all()\n special_prerequisities = feat.featspecialfeatprerequisite_set.select_related(\n 'special_feat_prerequisite').all()\n # related feats\n related_feats = Feat.objects.filter(slug=feat.slug).exclude(rulebook__id=feat.rulebook.id).select_related(\n 'rulebook', 'rulebook__dnd_edition').all()\n\n return render(request, 'dnd/feats/feat_detail.html', context={'feat': feat, 'rulebook': feat.rulebook,\n 'feat_category_list': feat_category_list, 'required_feats': required_feats,\n 'required_by_feats': required_by_feats, 'required_skills': required_skills,\n 'special_prerequisities': special_prerequisities, 'i_like_it_url': request.build_absolute_uri(),\n 'inaccurate_url': request.build_absolute_uri(), 'display_3e_warning': is_3e_edition(feat.rulebook.dnd_edition),\n 'related_feats': related_feats,},)\n","sub_path":"dndtools/dnd/feats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"151927796","text":"#ハイパーパラメータの探索Permalink\nimport time\nimport pandas as pd\nfrom tqdm import tqdm\nfrom sklearn.svm import SVC\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\n\ndef output_info(model, valid_acc, test_acc):\n with open('result59.txt', 'a') as ouput_file:\n print(f'algorithm: {model}', file = ouput_file)\n print(f'valid accuracy: {valid_acc}', file = ouput_file)\n print(f'test accuracy : {test_acc}', file = ouput_file)\n\nif __name__ == '__main__':\n X_train = pd.read_table('train.feature.txt', header = None)\n Y_train = pd.read_table('train.txt', header = None)[1]\n X_valid = pd.read_table('valid.feature.txt', header = None)\n Y_valid = pd.read_table('valid.txt', header = None)[1]\n X_test = pd.read_table('test.feature.txt', header = None)\n Y_test = pd.read_table('test.txt', header = None)[1]\n\n # 標準化\n sc = StandardScaler()\n sc.fit(X_train)\n X_train = sc.transform(X_train)\n X_valid = sc.transform(X_valid)\n X_test = sc.transform(X_test)\n\n # # 主成分分析\n # # 次元圧縮前の特徴量は13109次元\n # pca = PCA(n_components=512)\n # X_train = pca.fit_transform(X_train)\n # X_valid = pca.transform(X_valid)\n # X_test = pca.transform(X_test)\n\n # 必要な情報を格納する変数\n best_model = None\n best_acc = -1 # valid上の最大の正解率\n\n # ロジスティック回帰\n C_candidate = [1e-2, 1e-1, 1e0, 1e1, 1e2]\n for c in tqdm(C_candidate):\n clf = LogisticRegression(penalty = 'l1', solver='saga', random_state = 0, C = c)\n clf.fit(X_train, Y_train)\n valid_acc = accuracy_score(Y_valid, clf.predict(X_valid))\n if best_acc < valid_acc:\n best_model = clf\n best_acc = valid_acc\n test_acc = accuracy_score(Y_test, best_model.predict(X_test)) # test上で評価する\n output_info(best_model, best_acc, test_acc) # 結果を出力する\n best_acc = -1 # validの正解率をリセットする\n\n # SVM\n C_candidate = [1e-2, 1e-1, 1e0, 1e1, 1e2]\n for c in tqdm(C_candidate):\n clf = SVC(kernel = 'linear', C = c, class_weight = 'balanced', random_state = 0)\n clf.fit(X_train, Y_train)\n valid_acc = accuracy_score(Y_valid, clf.predict(X_valid))\n if best_acc < valid_acc:\n best_model = clf\n best_acc = valid_acc\n test_acc = accuracy_score(Y_test, best_model.predict(X_test))\n output_info(best_model, best_acc, test_acc)\n best_acc = -1\n\n # # カーネルSVM\n # # 非常に時間がかかる\n # C_candidate = [1e-2, 1e-1, 1e0, 1e1, 1e2]\n # gamma_candidate = [1e-2, 1e-1, 1e0, 1e1, 1e2]\n # for c in tqdm(C_candidate):\n # for gam in tqdm(gamma_candidate):\n # clf = SVC(kernel=\"rbf\", C=c, gamma=gam, class_weight=\"balanced\", random_state=0)\n # clf.fit(X_train, Y_train)\n # valid_acc = accuracy_score(Y_valid, clf.predict(X_valid))\n # if best_acc < valid_acc:\n # best_model = clf\n # best_acc = valid_acc\n # test_acc = accuracy_score(Y_test, best_model.predict(X_test))\n # output_info(best_model, best_acc, test_acc)\n # best_acc = -1\n\n # ランダムフォレスト\n max_depth_candidate = [16, 32, 64, 128, 256]\n for m in max_depth_candidate:\n clf = RandomForestClassifier(max_depth = m, random_state = 0)\n clf.fit(X_train, Y_train)\n valid_acc = accuracy_score(Y_valid, clf.predict(X_valid))\n if best_acc < valid_acc:\n best_model = clf\n best_acc = valid_acc\n test_acc = accuracy_score(Y_test, best_model.predict(X_test))\n output_info(best_model, best_acc, test_acc)\n best_acc = -1","sub_path":"pan/chapter06/X59.py","file_name":"X59.py","file_ext":"py","file_size_in_byte":3983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"235053854","text":"import os\nfrom nltk.corpus import reuters\n\nreuters_file = \"/home/afroditi/PycharmProjects/flask/myweb/reuters.txt\"\n\n\ndef collection_stats():\n # List of documents\n documents = reuters.fileids()\n print(str(len(documents)) + \" documents\")\n\n train_docs = list(filter(lambda doc: doc.startswith(\"train\"), documents))\n print(str(len(train_docs)) + \" total train documents\")\n\n test_docs = list(filter(lambda doc: doc.startswith(\"test\"), documents))\n print(str(len(test_docs)) + \" total test documents\")\n\n # List of categories\n categories = reuters.categories()\n print(\"Categories:\", categories)\n print(str(len(categories)) + \" categories\")\n\n # Documents in a category\n category_docs = reuters.fileids(\"acq\")\n\n # Words for a document\n document_id = category_docs[0]\n document_words = reuters.words(category_docs[0])\n print(document_words)\n # print(len(document_words))\n\n # Raw document\n # print(reuters.raw(document_id))\n\n\ndef raw_to_file():\n category_docs = reuters.fileids(\"sugar\")\n # print(len(category_docs))\n # print(category_docs[0:20])\n # document_id = category_docs[0]\n for doc_id in category_docs[0:30]:\n # print(reuters.raw(doc_id))\n with open(\"reuters.txt\", \"a\") as f:\n f.write(reuters.raw(doc_id))\n f.write(\"***********************************************************************\")\n category_docs = reuters.fileids(\"coffee\")\n for doc_id in category_docs[0:30]:\n with open(\"reuters.txt\", \"a\") as f:\n f.write(reuters.raw(doc_id))\n f.write(\"***********************************************************************\")\n category_docs = reuters.fileids(\"housing\")\n for doc_id in category_docs[0:30]:\n with open(\"reuters.txt\", \"a\") as f:\n f.write(reuters.raw(doc_id))\n f.write(\"***********************************************************************\")\n\n\ndef delete_file(file):\n if os.path.exists(file):\n os.remove(file)\n\n\ndef main():\n train_docs = []\n test_docs = []\n\n for doc_id in reuters.fileids():\n if doc_id.startswith(\"train\"):\n train_docs.append(reuters.raw(doc_id))\n else:\n test_docs.append(reuters.raw(doc_id))\n # print(train_docs)\n\n\nif __name__ == '__main__':\n # main()\n # collection_stats()\n delete_file(reuters_file)\n raw_to_file()\n\n\n\n","sub_path":"code/flask/myweb/reuters.py","file_name":"reuters.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"164595364","text":"\"\"\"\n# A Python script that reads in the Iris data set stored in the data subdirectory under\n# the current project and then prints the four numerical values on \n# each row in a nice format on the screen. The printed data are for:\n# petal length, petal width, sepal length and sepal width. \n# These values are listed with decimal places aligned, and \n# with a space between the columns.\n# H1 = Sepal Length\n# H2 = Sepal Width\n# H3 = Petal Length\n# H4 = Petal Width\n# H5 = Group Classification(1, 2, 3)\n\nAn interesting observation from the next two plots confirms the existing observations on the \nIris data set. There is a marked separation between setosa whereas, there seem not to be much \nseparation among the versicolor and the virginica.\nThis observation further confirms the Fishers' Linear Discriminant relationship experiments. \nExplored Samples:(H1 vs H2) & (H3 vs H4)\n\"\"\"\n# Francis Adepoju. March 31 - April 28 2018 \n# End of Module Project\n# Investigating the Iris_flower_data_set\n# http://python-for-multivariate-analysis.readthedocs.io/ ....python book\" \n# http://archive.ics.uci.edu/ml/machine-learning-databases/iris/\n# https://en.wikipedia.org/wiki/Iris_flower_data_set\n# A script for plotting multivariate tabular data as gridded scatter plots.\n\n#import pandas.plotting.scatter_matrix as pd2 and all necessary libraries for this analytics\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nnp.set_printoptions(suppress=True)\n\n# Sample number of rows to print for a dataframe [0 <= n <= 150]\nDISPLAY_MAX_ROWS = 40\npd.set_option('display.max_rows', DISPLAY_MAX_ROWS)\n\n# Read in the data file from csv kept in /data directory\n#data = pd.read_csv(\"data/iris.csv\", header = 0)... no listed header in the file\ndata = pd.read_csv('data/iris.csv', delimiter=',', header=None) \n\n# Rename the columns to be similar to R naming convention for easy access...\ndata.columns = [ \"H\"+str(i) for i in range(1, len(data.columns)+1) ]\ndata.H5 = data.H5.astype(str) # Column 5 holds the Group name as type string\n\n\"\"\"\nSimilar plots as the previous ones but with line of regression passing through the mid-point of\nthe distributions...\n\"\"\"\n# Plot H1 vs H2: Sepal Length vs Width, WITH REGRESSION\nsns.lmplot(\"H1\", \"H2\", data, hue=\"H5\", legend_out=0)\nplt.suptitle(\"SEPAL REGRESSION PLOT\")\nplt.grid()\n# Plot H1 vs H2: Sepal Length vs Width, WITH REGRESSION\nsns.lmplot(\"H3\", \"H4\", data, hue=\"H5\", legend_out=0)\nplt.suptitle(\"PETAL REGRESSION PLOT\")\nplt.grid()\n# Render the two plots\nplt.show()\n\n","sub_path":"data4-Regression.py","file_name":"data4-Regression.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"571209078","text":"#!/usr/bin/python\n\nimport time\nimport json\nimport gc\n\ninfile=\"/home/stephen/data/smtp/runs/IE-20180316-181141/records.fresh\"\n\ndef searchIp(ip):\n with open(infile,'r') as f:\n for line in f:\n j_content = json.loads(line)\n if (j_content['ip']==ip):\n return j_content\n \n # print(result)\n return result\n\ndef searchP443Fingerprint(fp):\n result=[]\n with open(infile,'r') as f:\n for line in f:\n j_content = json.loads(line)\n fprint=\"\"\n try:\n fprint=j_content['p443']['data']['http']['response']['request']['tls_handshake']['server_certificates']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']\n except:\n pass\n if (fprint and fprint==fp):\n result.append(j_content)\n \n # print(result)\n return result\n\ndef searchP443FingerprintGroupByCipherSuite(fp):\n result={}\n with open(infile,'r') as f:\n for line in f:\n j_content = json.loads(line)\n fprint=\"\"\n try:\n fprint=j_content['p443']['data']['http']['response']['request']['tls_handshake']['server_certificates']['certificate']['parsed']['subject_key_info']['fingerprint_sha256']\n except:\n pass\n if (fprint and fprint==fp):\n cipherSuite=j_content['p443']['data']['http']['response']['request']['tls_handshake']['server_hello']['cipher_suite']['name']\n if not cipherSuite in result:\n result[cipherSuite]=[]\n result[cipherSuite].append(j_content)\n \n # print(result)\n return result\n\n\ndef searchIpTest():\n print(\"Search IP Test:\")\n avgTime = 0\n ip = \"34.240.5.183\"\n for i in range(5):\n startTime=time.time()\n searchIp(ip)\n endTime=time.time()\n timeTaken=endTime-startTime\n print(\" {}: {}s\".format(i, timeTaken))\n avgTime=((avgTime*i)+timeTaken)/(i+1)\n print(\" Avg time taken: {}s\".format(avgTime))\n\ndef searchP443FingerprintTest():\n print(\"Search P443 Fingerprint Test:\")\n avgTime = 0\n fp = \"9f0050378fa2a1389b35cf74e0f1063ad42eaebc5a324b10c6aacf3ab08f7a94\"\n for i in range(5):\n startTime=time.time()\n result=searchP443Fingerprint(fp)\n endTime=time.time()\n timeTaken=endTime-startTime\n print(\" {}: {}s {} matches found\".format(i, timeTaken, len(result)))\n avgTime=((avgTime*i)+timeTaken)/(i+1)\n gc.collect()\n print(\" Avg time taken: {}s\".format(avgTime))\n\ndef searchP443FingerprintGroupByCipherSuiteTest():\n print(\"Search P443 Fingerprint, Group By Cipher Suite Test:\")\n avgTime = 0\n fp = \"9f0050378fa2a1389b35cf74e0f1063ad42eaebc5a324b10c6aacf3ab08f7a94\"\n for i in range(5):\n startTime=time.time()\n result = searchP443FingerprintGroupByCipherSuite(fp)\n endTime=time.time()\n timeTaken=endTime-startTime\n matches = 0\n for suite in result:\n matches += len(result[suite])\n print(\" {}: {}s {} matches found\".format(i, timeTaken, matches))\n for suite in result:\n print(\" {}: {}\".format(suite, len(result[suite])))\n avgTime=((avgTime*i)+timeTaken)/(i+1)\n print(\" Avg time taken: {}s\".format(avgTime))\n\ndef runTests():\n # searchIpTest()\n # searchP443FingerprintTest()\n searchP443FingerprintGroupByCipherSuiteTest()\n\nrunTests()","sub_path":"Code/Evaluation/JsonFile.py","file_name":"JsonFile.py","file_ext":"py","file_size_in_byte":3473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"171449843","text":"#!/usr/bin/python3\n#coding: utf-8\n\n\nimport cgi\nimport sys\nimport datetime\nfrom os import environ\nimport io\nimport urllib.parse\nimport pymysql\n\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')\n\nhtml = \"\"\"\n\n\n\n\n%s\n\n\n\"\"\"\nform=cgi.FieldStorage()\nid = form.getfirst(\"ID\", \"default\")\n\nconnection = pymysql.connect(\n host = \"localhost\",\n user = \"pi\",\n password = \"takeru_ryuou\",\n db = \"kifu\",\n charset = \"utf8\",\n cursorclass = pymysql.cursors.DictCursor )\n\nwith connection.cursor() as cursor:\n sql = \"SELECT KIFU FROM kifu WHERE ID=%s\"\n cursor.execute(sql,(id))\n results = cursor.fetchall()\n kifu = results[0]['KIFU']\n\nprint(\"Content-type: text/html\\n\")\nprint(html%(kifu))\n","sub_path":"www/kifu.py","file_name":"kifu.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"564468170","text":"from .checks import is_bin\n\n\n# ================== INTEGER ================== #\ndef bintoint(binary):\n # If number is int, convert to string\n if type(binary) is int:\n binary = str(binary)\n # Raise error if not in binary format\n if not is_bin(binary):\n raise TypeError(\"The argument is not binary\")\n\n # Calculate decimal from binary\n dec = 0\n for i in range(len(binary) - 1, -1, -1):\n if int(binary[0]):\n dec += 2**i\n binary = binary[1:]\n return dec\n\n\n# ================== UTF8 ================== #\ndef bintoutf8(binary):\n # If number is int, convert to string\n if type(binary) is int:\n binary = str(binary)\n # Raise error if not in binary format\n if not is_bin(binary):\n raise TypeError(\"The argument is not binary\")\n return _bintoutf(binary, 8)\n\n\n# ================== UTF16 ================== #\ndef bintoutf16(binary):\n # If number is int, convert to string\n if type(binary) is int:\n binary = str(binary)\n # Raise error if not in binary format\n if not is_bin(binary):\n raise TypeError(\"The argument is not binary\")\n return _bintoutf(binary, 16)\n\n\n# ================== COMMON UTF ================== #\ndef _bintoutf(binary, typeutf: int = 8):\n # Get binary letter by letter\n binary_split = []\n while not (binary == \"\"):\n binary_split.append(binary[:typeutf])\n binary = binary[typeutf:]\n\n # Convert binary to utf with chr()\n text = \"\"\n for byte in binary_split:\n text += chr(bintoint(byte))\n\n return text\n\n\n# ================== SINGLE PRECISION FLOAT ================== #\ndef bintofloat(binary):\n # If number is int, convert to string\n if type(binary) is int:\n binary = str(binary)\n # Raise error if not in binary format\n if not is_bin(binary):\n raise TypeError(\"The argument is not binary\")\n # Raise error if binary is not the correct lenght\n if not len(binary) == 64:\n raise ValueError(\"The binary is not a double (must be 64-bits long)\")\n\n return _bintofloat(binary, 8, 23)\n\n\n# ================== DOUBLE PRECISION FLOAT ================== #\ndef bintodouble(binary):\n # If number is int, convert to string\n if type(binary) is int:\n binary = str(binary)\n # Raise error if not in binary format\n if not is_bin(binary):\n raise TypeError(\"The argument is not binary\")\n # Raise error if binary is not the correct lenght\n if not len(binary) == 64:\n raise ValueError(\"The binary is not a double (must be 64-bits long)\")\n\n return _bintofloat(binary, 11, 52)\n\n\n# ================== COMMON FLOAT ================== #\ndef _bintofloat(binary, exponentbit: int, mantissabit: int):\n # Get the sign of float (0: +, 1: -)\n sign = \"\"\n if int(binary[0]):\n sign = \"-\"\n binary = binary[1:]\n\n # Get the binary of exponenent and convert to a decimal value\n exponentbin = binary[:exponentbit]\n binary = binary[exponentbit:]\n exponent = bintoint(exponentbin) - ((2 ** (exponentbit - 1)) - 1)\n\n # Convert the rest of the binary (mantissa) to float\n decimal = 1.0\n for i in range(1, mantissabit + 1):\n if int(binary[0]):\n decimal += (1 / 2 ** i)\n binary = binary[1:]\n\n return float(sign + str(decimal * (2**exponent)))\n\n\n# ================== HEX ================== #\ndef bintohex(binary):\n # If number is int, convert to string\n if type(binary) is int:\n binary = str(binary)\n # Raise error if not in binary format\n if not is_bin(binary):\n raise TypeError(\"The argument is not binary\")\n\n hexa = hex(bintoint(binary))[2:].upper()\n\n return hexa\n\n\n# ================== OCT ================== #\ndef bintooct(binary):\n # If number is int, convert to string\n if type(binary) is int:\n binary = str(binary)\n # Raise error if not in binary format\n if not is_bin(binary):\n raise TypeError(\"The argument is not binary\")\n\n octa = oct(bintoint(binary))[2:].upper()\n\n return octa\n","sub_path":"pythonExercicios/venv/Lib/site-packages/pyconverter/frombin.py","file_name":"frombin.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"617178527","text":"import os\nimport glob\nimport numpy as np\nimport pandas as pd\nimport nibabel\nfrom joblib import Parallel, delayed, Memory\nfrom nistats.design_matrix import (make_design_matrix, check_design_matrix)\nfrom pypreprocess.external.nistats.glm import FMRILinearModel\nfrom pypreprocess.reporting.base_reporter import ProgressReport\nfrom pypreprocess.reporting.glm_reporter import (generate_subject_stats_report,\n group_one_sample_t_test)\nfrom nilearn.plotting import plot_prob_atlas, show\nimport matplotlib.pyplot as plt\n\nn_jobs = int(os.environ.get(\"N_JOBS\", 1))\n\n\ndef _load_contrast_names(cfile):\n contrast_names = []\n with open(cfile, 'r') as fd:\n cons = [x.rstrip(\"\\r\\n\") for x in fd.readlines()]\n cons = [x for x in cons if x]\n for c in cons:\n c = c.split(\" \")\n contrast_names.append(c[1])\n return contrast_names\n\n\ndef _load_condition_keys(cfile):\n conditions = {}\n with open(cfile, 'r') as fd:\n conds = [x.rstrip(\"\\r\\n\") for x in fd.readlines()]\n conds = [x for x in conds if x]\n for c in conds:\n c = c.split(\" \")\n conditions[c[1]] = c[2]\n return conditions\n\n\n# meta data\ntr = 2.\ndrift_model = 'Cosine'\nhrf_model = 'spm + derivative'\nhfcut = 128.\n\ndata_dir = os.environ.get(\"DATA_DIR\", \"/home/elvis/nilearn_data/ds001\")\noutput_dir = os.environ.get(\"OUTPUT_DIR\",\n os.path.join(data_dir,\n \"pypreprocess_output/ds001\"))\ncondition_keys = _load_condition_keys(\n os.path.join(data_dir, \"models/model001/condition_key.txt\"))\ncontrast_names = _load_contrast_names(\n os.path.join(data_dir, \"models/model001/task_contrasts.txt\"))\nsubject_ids = map(os.path.basename,\n sorted(glob.glob(\"%s/sub*\" % output_dir)))[:8]\n\n\ndef do_subject_glm(subject_id):\n subject_output_dir = os.path.join(output_dir, subject_id)\n\n # make design matrices\n design_matrices = []\n func = []\n anat = os.path.join(subject_output_dir, \"anatomy\", \"whighres001_brain.nii\")\n for run_path in sorted(glob.glob(os.path.join(\n data_dir, subject_id, \"model/model001/onsets/task*\"))):\n run_id = os.path.basename(run_path)\n run_func = glob.glob(os.path.join(subject_output_dir, \"BOLD\", run_id,\n \"wrbold*.nii\"))\n assert len(run_func) == 1\n run_func = run_func[0]\n run_onset_paths = sorted(glob.glob(os.path.join(\n data_dir, subject_id, \"model/model001/onsets/%s/*\" % run_id)))\n onsets = map(np.loadtxt, run_onset_paths)\n conditions = np.hstack(\n [[condition_keys[\"cond%03i\" % (c + 1)]] * len(onsets[c])\n for c in range(len(run_onset_paths))])\n onsets = np.vstack((onsets))\n onsets *= tr\n run_func = nibabel.load(run_func)\n func.append(run_func)\n n_scans = run_func.shape[-1]\n onset, duration, modulation = onsets.T\n\n frametimes = np.linspace(0, (n_scans - 1) * tr, n_scans)\n paradigm = pd.DataFrame(dict(name=conditions, onset=onset,\n duration=duration, modulation=modulation))\n design_matrix = make_design_matrix(frametimes, paradigm,\n hrf_model=hrf_model,\n drift_model=drift_model,\n period_cut=hfcut)\n design_matrices.append(design_matrix)\n n_runs = len(func)\n\n # specify contrasts\n _, _, names = check_design_matrix(design_matrix)\n n_columns = len(names)\n contrast_matrix = np.eye(n_columns)\n contrasts = {}\n for c in range(len(condition_keys)):\n contrasts[names[2 * c]] = contrast_matrix[2 * c]\n contrasts[\"avg\"] = np.mean(contrasts.values(), axis=0)\n\n # more interesting contrasts\n contrasts_ = {}\n for contrast, val in contrasts.items():\n if not contrast == \"avg\":\n contrasts_[\"%s_minus_avg\" % contrast] = val - contrasts[\"avg\"]\n contrasts = contrasts_\n\n # fit GLM\n from nilearn.image import smooth_img\n func = smooth_img(func, fwhm=8.)\n print('Fitting a GLM (this takes time)...')\n fmri_glm = FMRILinearModel(func, [check_design_matrix(design_matrix)[1]\n for design_matrix in design_matrices],\n mask='compute')\n fmri_glm.fit(do_scaling=True, model='ar1')\n\n # save computed mask\n mask_path = os.path.join(subject_output_dir, \"mask.nii\")\n print(\"Saving mask image to %s ...\" % mask_path)\n nibabel.save(fmri_glm.mask, mask_path)\n\n # compute contrast maps\n z_maps = {}\n effects_maps = {}\n for contrast_id, contrast_val in contrasts.items():\n print(\"\\tcontrast id: %s\" % contrast_id)\n z_map, t_map, effects_map, var_map = fmri_glm.contrast(\n [contrast_val] * n_runs, con_id=contrast_id, output_z=True,\n output_stat=True, output_effects=True, output_variance=True)\n for map_type, out_map in zip(['z', 't', 'effects', 'variance'],\n [z_map, t_map, effects_map, var_map]):\n map_dir = os.path.join(subject_output_dir, '%s_maps' % map_type)\n if not os.path.exists(map_dir):\n os.makedirs(map_dir)\n map_path = os.path.join(\n map_dir, '%s.nii.gz' % contrast_id)\n print(\"\\t\\tWriting %s ...\" % map_path)\n nibabel.save(out_map, map_path)\n if map_type == 'z':\n z_maps[contrast_id] = map_path\n if map_type == 'effects':\n effects_maps[contrast_id] = map_path\n\n # # generate stats report\n # stats_report_filename = os.path.join(subject_output_dir, \"reports\",\n # \"report_stats.html\")\n # generate_subject_stats_report(\n # stats_report_filename, contrasts, z_maps, fmri_glm.mask, anat=anat,\n # threshold=2.3, cluster_th=15, design_matrices=design_matrices, TR=tr,\n # subject_id=\"sub001\", n_scans=n_scans, hfcut=hfcut,\n # paradigm=paradigm, frametimes=frametimes,\n # drift_model=drift_model, hrf_model=hrf_model)\n # ProgressReport().finish_dir(subject_output_dir)\n\n return dict(subject_id=subject_id, mask=mask_path,\n effects_maps=effects_maps, z_maps=z_maps, contrasts=contrasts)\n\n\n# first level GLM\nmem = Memory(os.path.join(output_dir, \"cache_dir\"))\nn_jobs = min(n_jobs, len(subject_ids))\nfirst_levels = Parallel(n_jobs=n_jobs)(delayed(mem.cache(do_subject_glm))(\n subject_id) for subject_id in subject_ids)\n\n# run second-level GLM\ngroup_zmaps = group_one_sample_t_test(\n [subject_data[\"mask\"] for subject_data in first_levels],\n [subject_data[\"effects_maps\"] for subject_data in first_levels],\n first_levels[0][\"contrasts\"],\n output_dir, threshold=2.)\nplot_prob_atlas([zmap for zmap in group_zmaps.values() if \"_minus_\" in zmap],\n threshold=1.2, view_type=\"filled_contours\")\nplt.savefig(\"group_zmaps.png\")\nshow()\n","sub_path":"scripts/openfmri.py","file_name":"openfmri.py","file_ext":"py","file_size_in_byte":7094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"155622172","text":"from openfermion.hamiltonians import MolecularData\nfrom openfermionpsi4 import run_psi4\nfrom openfermion.utils import uccsd_generator,uccsd_convert_amplitude_format\nfrom forestopenfermion import exponentiate,qubitop_to_pyquilpauli\nfrom openfermion.transforms import get_fermion_operator, jordan_wigner\nimport numpy as np\nfrom pyquil.quil import Program\nimport pyquil.api as api\nfrom pyquil.gates import *\nfrom forestopenfermion import exponentiate\nfrom grove.pyvqe.vqe import VQE\nfrom scipy.optimize import minimize\n\ndef ansatz(amps,n_orbitals=14,n_electrons=10):\n \"\"\" Return pyquil program UCC ansatz\"\"\"\n amp_singles = amps[:n_orbitals**2]\n amp_doubles = amps[n_orbitals**2:]\n x = amp_singles.reshape(n_orbitals,n_orbitals)\n y = amp_doubles.reshape(n_orbitals,n_orbitals,n_orbitals,n_orbitals)\n p = Program()\n for i in range(n_electrons):\n p += X(i)\n p += exponentiate(jordan_wigner(uccsd_generator(x,y)) / (-1j))\n return p\n\ndef expectation(p1,p2,p3,multi=1):\n \"\"\" \n Return UCC expectation value for a specified geometry \n * First runs a psi4 ccsd calculation to get single and double\n amplitudes to use as ansatz for UCC\n * Generates a Hamiltonian for the specified geometry\n * Obtains expectation value using VQE \n \"\"\"\n geometry = [['O',p1], ['H',p2], ['H',p3]]\n molecule = MolecularData(geometry, \n basis='sto-3g',\n multiplicity=multi,\n description=str(round(rad, 2)) \n + \"_\" + str(round(ang,2))\n )\n # Run Psi4.\n molecule = run_psi4(molecule,\n run_ccsd=1,\n run_fci=1)\n # Print out some results of calculation.\n print('\\nRAD: {}, ANG: {}\\n'.format(rad,ang))\n print('FCI energy: {} Hartree.'.format(molecule.fci_energy))\n\n singles_initial = molecule.ccsd_single_amps.flatten()\n doubles_initial = molecule.ccsd_double_amps.flatten()\n amps = np.concatenate((singles_initial,doubles_initial),axis=0)\n\n print(\"Compiling the Hamiltonian...\")\n hamiltonian=jordan_wigner(get_fermion_operator(molecule.get_molecular_hamiltonian()))\n hamiltonian.compress()\n hamiltonian = qubitop_to_pyquilpauli(hamiltonian)\n print(\"Hamiltonian complete\")\n\n vqe = VQE(minimizer=minimize, \n minimizer_kwargs={'method': 'nelder-mead',\n 'options': {'fatol':1.5e-3}}\n )\n result = vqe.expectation(ansatz(amps), hamiltonian, None, qvm)\n print(\"VQE Expectation Value: {} Hartree\".format(result))\n\n return result\n\nqvm = api.QVMConnection()\n# Set grid parameters\nN = 12\nr_min = 0.6\nr_max = 1.5\na_min = 30\na_max = 180\n\n# Get expectation values for a grid of parameters\nfor rad in np.linspace(r_min,r_max,N):\n for ang in np.linspace(a_min,a_max,N):\n p1 = [0,0,0]\n p2 = [rad,0,0]\n p3 = [rad*np.cos(ang*np.pi/180),rad*np.sin(ang*np.pi/180),0]\n\n exp = expectation(p1,p2,p3) \n with open('resources/contour_results.txt','a') as f:\n f.write(str(exp)+\"\\n\")\n print(\"Result saved.\") \n","sub_path":"research/2019_08_22_h2o/h2o_gen_contours.py","file_name":"h2o_gen_contours.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"374025099","text":"\"\"\"\n @author Victor I. Afolabi\n A.I. engineer/researcher & Software engineer\n javafolabi@gmail.com\n \n Created on 07 January, 2018 @ 7:27 PM.\n \n Copyright © 2018. Victor. All rights reserved.\n\"\"\"\nimport os.path\n\n# import models.neural_network.pre_trained as pre_trained\n# import models.projects as projects\n# TODO: Fix this code leak. This is where keras is imported automatically when project starts\nfrom models.neural_network.pre_trained.inception import Inception\nfrom models.projects.utils import maybe_download_or_upload\nfrom models.projects.search import Search\nfrom helpers.consts import STATIC_DIR\n\n\ndef process(request):\n try:\n # Upload image.\n image_path = upload(request)\n\n # Classify image.\n predictions = predict(image_path, top=5)\n\n # Search top prediction label\n # s = predictions['top']['label']\n # print(f'Searching for {s}')\n # search_results = search(s)\n\n return {\n 'image_path': image_path,\n 'predictions': predictions,\n # 'search_results': search_results\n }\n except Exception as e:\n raise Exception(e)\n\n\ndef upload(request):\n image = None\n if 'upload-file' not in request.form:\n image = {'file': request.files['upload-file'], 'type': 'upload'}\n elif 'camera-file' not in request.form:\n image = {'file': request.files['camera-file'], 'type': 'upload'}\n elif request.form['image-url']:\n image = {'file': request.form['image-url'], 'type': 'url'}\n path = maybe_download_or_upload(image, folder='')\n if path and type(path) == str:\n return path\n else:\n raise Exception('Trouble uploading image')\n\n\ndef predict(path, top=5):\n \"\"\"\n Predicts what class an image input belongs to using the imagenet\n pre-trained weights.\n\n :param path: str,\n Image path relative to the static directory\n e.g.\n >>> path = 'images/uploads/elephant.jpg'\n >>> results = model.predict(path=path, top=3)\n\n :param top: int,\n How many class predictions to be returned.\n\n :return: results, dict\n Results containing to items: top prediction & all predictions\n top prediction contains a dictionary of the score and label.\n all predictions is a dictionary of labels and scores of `top`\n number of classes.\n\n e.g.\n >>> results['top']\n >>> # {'label': 'african_elephant', 'score': 0.832}\n >>> results['all']\n >>> # {'african_elephant': 0.832, 'zambia_elephant': 0.132, ...}\n \"\"\"\n print('Loading pre-trained inception model...')\n # Full/absolute image path\n full_img_path = os.path.join(STATIC_DIR, path)\n\n # Loading the a pre-trained InceptionV3 model.\n model = Inception(weights='imagenet')\n\n # Predict the image label.\n pred = model.predict(full_img_path, top=top)\n\n # Clean up predictions\n pred = list(map(_predict_pprint, pred))\n\n # Top prediction's labels and their scores\n top_label = pred[0][0]\n top_score = pred[0][1]\n\n return {\n 'top': {'label': top_label, 'score': top_score},\n 'all': dict(pred)\n }\n\n\ndef search(prediction):\n search = Search()\n results = search.search(prediction)\n return results\n\n\ndef _predict_pprint(label_score):\n # label_score[0] = imagenet class id\n label = label_score[1]\n score = f'{label_score[2]:.2%}'\n label = label.replace('_', ' ').capitalize()\n return label, score\n","sub_path":"models/projects/image_search.py","file_name":"image_search.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"126441642","text":"from keras.layers.core import Dropout\nfrom keras.layers.core import Flatten\nfrom keras.layers.core import Dense\n\nclass FCHeadNet:\n @staticmethod\n def build(baseModel, classes, D):\n \"\"\"\n Complete a transfer learning with a FC head layer. as described:\n INPUT => fc => RELU => DO => FC => SOFTMAX\n :param baseModel: model without FC head (VGG, resnet, etc.)\n :param classes: number of output classes to classify\n :param D: Number of hidden nodes in the FC layer after input\n :return: headModel (baseModel with new set of FC layers on end\n \"\"\"\n # init base model and add our head of FC layers\n headModel = baseModel.output\n headModel = Flatten(name=\"flatten\")(headModel)\n headModel = Dense(D, activation=\"relu\")(headModel)\n headModel = Dropout(0.5)(headModel)\n\n # add a softmax layer\n headModel = Dense(classes, activation=\"softmax\")(headModel)\n\n return headModel\n\n\n\n","sub_path":"BlogTutorials/pyimagesearch/nn/conv/fcheadnet.py","file_name":"fcheadnet.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"325454410","text":"#user/bin/python\n# -*- coding:UTF-8 -*-\n\nimport numpy as np\nimport math\n\ndef cal_SVD(matr, m, n):\n # print(m,n)\n CC_T = np.matmul(matr, matr.T)\n C_TC = np.matmul(matr.T, matr)\n # print(CC_T)\n # print(C_TC)\n eigenValuesofCC_T = np.linalg.eig(CC_T)\n eigenValuesofC_TC = np.linalg.eig(C_TC)\n sigma_matr = np.sqrt(np.diag(eigenValuesofC_TC[0]))\n U = eigenValuesofCC_T[1].T\n V = eigenValuesofC_TC[1].T\n print(U)\n print(V)\n print(sigma_matr)\n # print(np.matmul(np.matmul(U,sigma_matr), V.T))\n\nif __name__ == \"__main__\":\n matr = np.array([[1,0,1,0,0,0],\n [0,1,0,0,0,0],\n [1,1,0,0,0,0],\n [1,0,0,1,1,0],\n [0,0,0,1,0,1]])\n # print(matr.shape[0])\n # cal_SVD(matr, matr.shape[0], matr.shape[1])\n u,sigma,vt=np.linalg.svd(matr)\n print(u)\n print(sigma)\n print(vt)","sub_path":"big_data_analysis/Assignment/assignment1/pros/assignment2_1.py","file_name":"assignment2_1.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"545111494","text":"import subprocess\nimport socket\nimport pickle\n\n\ndef find_outside_ip_unix() -> str:\n #ip_pattern = \"192.168.\"\n ip_pattern = \"134.245.\"\n ip = \"0.0.0.0\"\n ifconfig = subprocess.check_output(\"ifconfig | awk '/inet/ { print $2 } ' \", shell=True).split()\n for element in ifconfig:\n str_index = element.decode(\"utf-8\").find(ip_pattern)\n if str_index != -1:\n ip = element.decode(\"utf-8\")[str_index:]\n\n return ip\n\n\ndef send_to_socket(readable_msg, addr):\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n try:\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) # must be disabled for Linux <3.9\n except:\n pass\n\n try:\n server.connect(addr)\n except:\n print(\"Can't connect to \" + str(addr))\n return # leave this\n pickled_msg = pickle.dumps(readable_msg)\n server.send((str(len(pickled_msg)) + \":\").encode('utf-8') + pickled_msg)\n # print(str(len(pickled_msg)))\n\n server.close()","sub_path":"BA_ersteSchritte/functionStoreage.py","file_name":"functionStoreage.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"54223772","text":"import re\nimport inspect\nfrom django.conf.urls import url, include\n\nfrom django_generic_plus.urls import add_url_hierachy\nfrom .apps import DjangoHaiHueConfig as app_settings\nfrom . import views\n\nfrom .models import HueLight,HueLightProduct\n\napp_name = app_settings.name\n\n# django hue API v1\napi_endpoints = [\n url(r'^apiv1/sethsv/$', views.sethsv, name='sethsv'),\n url(r'^apiv1/change_switch_state/$', views.change_switch_state, name='change_switch_state'),\n]\n\nurlpatterns = [\n # ex: /music_viewer_app/\n url(r'^$', views.index, name='index'),\n url(r'^mqtt/$', views.mqtt, name='mqtt'),\n url(r'^mqtt/switch$', views.mqtt_get, name='mqtt_get'),\n]\nurlpatterns += api_endpoints\n\ndetail_views = {}\nlist_views = {}\nmodel_actions = {\n HueLight: {\n 'sethsv': views.sethsv,\n 'turn-switch': views.change_switch_state\n }\n}\n\nbase_model_names = [\"HueLight\", \"HueLightProduct\"]\n\nfor model in base_model_names:\n model_cls = globals()[model]\n add_url_hierachy(urlpatterns,\n app_settings.name,\n model_cls,\n detail_views=detail_views,\n list_views=list_views,\n model_actions=model_actions)\nprint(urlpatterns)\n","sub_path":"django_hai_hue/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"466480023","text":"from mpesa import app,api\nfrom flask_restful import Resource\nfrom flask import request, jsonify\n\nclass Test(Resource):\n def get(self):\n return {\"harman\": \"ok\"}\n\n def post(self):\n data = request.get_json()\n return data\n\n\napi.add_resource(Test, \"/\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"mpesa/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"497157248","text":"def primes(n):\n is_prime = [True] * (n+1)\n is_prime[0] = False\n is_prime[1] = False\n for i in range(2, n+1):\n if not is_prime[i]:\n continue\n k = i+i\n while k <= n:\n is_prime[k] = False\n k += i\n return is_prime\n\n\ndef prime_factorization(n):\n dct = {}\n tmp = n\n for i in range(2, int(n**0.5)+1):\n if tmp == 1:\n break\n if tmp % i == 0:\n cnt = 0\n while tmp % i == 0:\n cnt += 1\n tmp //= i\n dct[i] = cnt\n if tmp != 1:\n dct[tmp] = 1\n if len(dct) == 0:\n dct[n] = 1\n\n return dct\n\nif __name__ == \"__main__\":\n # test primes()\n print('-- test primes() --')\n n = 100\n is_prime = primes(n)\n for i in range(n+1):\n if is_prime[i]:\n print(i)\n\n # test prime_factorization()\n print('-- test prime_factorization() --')\n print(36, prime_factorization(36))\n print((10**9+7)*5, prime_factorization((10**9+7)*5))\n","sub_path":"algorithms/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"313346416","text":"def interaction(recsys, environment, n=100):\n \"\"\" Interaction between RecSystem and Environment. \"\"\"\n for _ in range(n):\n user, actions = environment.current_state()\n action = recsys.best_action(user, actions)\n payoff = environment.reaction(user['id'], action['id'])\n recsys.update(user, action, payoff)\n\n return None\n\n\n# class Experiment:\n# def interaction(self, n=100):\n# interaction(self.recsys, self.environment, n=n)\n# return None\n","sub_path":"interaction.py","file_name":"interaction.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"3382495","text":"def separator():\n print(\"---------------\")\n\n#using snake case for this assignment\n\n\nimport findspark\nfindspark.init()\nfindspark.find()\n\nfrom pyspark.sql.functions import col\nimport pyspark\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import lit\nfrom pyspark.sql.functions import udf\nfrom pyspark.sql.functions import when\nfrom pyspark.sql.functions import countDistinct\nfrom pyspark.sql.functions import log10\nfrom pyspark.ml.feature import StringIndexer\nfrom textblob import TextBlob\nfrom pyspark.sql.types import StringType\nimport re\nfrom datetime import datetime\nspark = SparkSession.builder.getOrCreate()\n\n\ndef get_score(comment):\n try:\n text = TextBlob(comment)\n return text.sentiment.polarity\n except Exception:\n return 'null'\ndef clean(comment):\n try:\n return clean_sentence(comment)\n except Exception:\n return 'null'\ndef translate(comment):\n try:\n translator = Translator()\n result = translator.translate(comment,dest='en')\n return comment\n except ValueError:\n return 0.0\n\ndef clean_sentence(sentence):\n sequence = sentence\n new = re.sub(r\"#[A-Za-z0-9]+\", \"\", sequence)\n new = re.sub(r\"https?://[A-Za-z0-9./]+\", \"\", new)\n new = re.sub(r\"\\.\", \" \", new) # delete points and replace with white space\n new = re.sub(\"[^a-zA-Z ]\", \"\", new) # Only letters and spaces\n new = re.sub(\" [^aeiou] \", \" \", new) # Remove single consonants\n new = re.sub(\"\\n\", \" \", new)\n new = re.sub(\"[ ]+\", \" \", new) # remove multiple white spaces\n new = new.strip()\n new = new.lower()\n return new\n\n\ndf = spark.read.csv('reviews.csv',sep=',',header = True, inferSchema=True)\ndf = df.limit(1000)\nudf_clean = udf(lambda x: clean(x), StringType())\nudf_translate = udf(lambda x: translate(x), StringType())\nudf_score = udf(lambda x: get_score(x), StringType())\n\ndf = df.withColumn('listing_id', \n when(col('listing_id').cast('Integer').isNull(), \n lit('null')).otherwise(col('listing_id').cast('Integer')))\ndf = df.withColumn('reviewer_id', \n when(col('reviewer_id').cast('Integer').isNull(), \n lit('null')).otherwise(col('reviewer_id')))\n\n\ndf = df.na.drop(subset=['listing_id','comments','reviewer_id'])\nprint(datetime.now())\ndf = df.withColumn('clean_comment',udf_clean(col('comments')))\nprint(datetime.now())\ndf = df.withColumn('english_clean_comment',udf_translate(col('clean_comment')))\nprint(datetime.now())\ndf = df.withColumn('score',udf_score(col('english_clean_comment')))\nprint(datetime.now())\ndf = df.drop('comments')\ndf = df.drop('clean_comment')\ndf = df.drop('date')\ndf = df.drop('id')\n#df.write.mode('overwrite').save(\"awspath/done3.csv\",header=True)\n#df.write.mode('overwrite').save(\"done3.csv\",header=True)\ndf.write.mode('overwrite').csv('done.csv',header=True)\n","sub_path":"spark_reviews.py","file_name":"spark_reviews.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"333773625","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0010_auto_20150807_1338'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='mensajes',\n name='published',\n field=models.BooleanField(default=True, verbose_name='Publicado?'),\n ),\n migrations.AddField(\n model_name='mensajes',\n name='published_in',\n field=models.ForeignKey(default=True, to='blog.Entrada'),\n ),\n ]\n","sub_path":"blog/migrations/0011_auto_20150807_1410.py","file_name":"0011_auto_20150807_1410.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"7749662","text":"from torch import Tensor, Size\nfrom gpytorch.distributions.multivariate_normal import MultivariateNormal\nfrom gpytorch.settings import fast_computations\nfrom botorch.posteriors.gpytorch import GPyTorchPosterior\nfrom typing import Optional, Type, TypeVar\n\nT = TypeVar('T', bound='SampleAveragePosterior')\nclass SampleAveragePosterior(GPyTorchPosterior):\n \"\"\"\n The use case for SampleAveragePosterior is for a model with some non-determinism \n in the prediction step, for example, if the model is doing sampling internally.\n\n SampleAveragePosterior computes multiple posteriors for the same input points. This\n creates a Monte-Carlo approximation to model's non-determinism. Each one of these\n multiple posteriors is a Gaussian distribution, so the Monte-Carlo approximation \n is actually a Gaussian mixture distribution. Since GPyTorchPosteriors have to be \n normally distributed, SampleAveragePosterior then approximates this Gaussian \n mixture distribution as a Gaussian distribution.\n\n There is no guarantee that this is a good approximation. However, if it is bad\n approximation then it probably means you shouldn't be using Gaussian processes\n for your problem anyway!\n \n SampleAveragePosterior hides all of this complexity. Use it by simply wrapping an\n existing GPyTorchPosterior in a SampleAveragePosterior. The outermost dim is then\n assumed to be the sample batch.\n\n # e.g.\n num_samples = 100\n original_shape = Size([10,5])\n # create multiple posteriors at identical input points\n expanded_test_X = test_X.unsqueeze(dim=0).expand(num_samples, *original_shape)\n # posterior.event_shape = Size([100,10,5])\n posterior = model.posterior(expanded_test_X)\n # wrap in SampleAveragePosterior, now posterior.event_shape = Size([10,5])\n posterior = SampleAveragePosterior.from_gpytorch_posterior(posterior)\n \"\"\"\n\n def __init__(self, mvn: MultivariateNormal) -> None:\n \"\"\"\n Args:\n mvn: Batch MultivariateNormal\n Outermost dimension (dim=0) of mvn is filled with samples.\n These samples will be combined by taking their mean.\n \"\"\"\n super().__init__(mvn)\n\n @property\n def num_samples(self) -> int:\n \"\"\"The number of samples that the posterior is averaged over.\"\"\"\n return super().event_shape[0]\n\n @property\n def event_shape(self) -> Size():\n \"\"\"The event shape (i.e. the shape of a single sample) of the posterior.\"\"\"\n return super().event_shape[1:]\n\n @property\n def mean(self) -> Tensor:\n \"\"\"\n The posterior mean.\n = mean of each Gaussian\n\n Reference:\n https://stats.stackexchange.com/questions/16608/what-is-the-variance-of-the-weighted-mixture-of-two-gaussians\n We have num_samples Gaussians, and since each Gaussian is drawn using Monte Carlo, then each Gaussian has equal weight\n \"\"\"\n return super().mean.mean(dim=0)\n\n @property\n def variance(self) -> Tensor:\n \"\"\"\n The posterior variance.\n = avg of variance + gvg of squared mean - square of avg mean\n\n Reference:\n https://stats.stackexchange.com/questions/16608/what-is-the-variance-of-the-weighted-mixture-of-two-gaussians\n We have num_samples Gaussians, and since each Gaussian is drawn using Monte Carlo, then each Gaussian has equal weight\n \"\"\"\n return super().variance.mean(dim=0) + super().mean.square().mean(dim=0) - super().mean.mean(dim=0).square()\n\n def _replacement_super_rsample(\n self,\n sample_shape: Optional[Size] = None,\n base_samples: Optional[Tensor] = None,\n ) -> Tensor:\n \"\"\"Sample from the posterior (with gradients).\n\n This is basically a copy of super().rsample(), however there\n is one line in super().rsample() where the base samples are reshaped\n using self.event_shape and this fails because I have re-written event shape.\n Effectively I have two event shapes, an internal event shape which is\n Size([self.num_samples, *self.event_shape]), and an external event shape\n which is self.event_shape.\n \n Args:\n sample_shape: A `torch.Size` object specifying the sample shape. To\n draw `n` samples, set to `torch.Size([n])`. To draw `b` batches\n of `n` samples each, set to `torch.Size([b, n])`.\n base_samples: An (optional) Tensor of `N(0, I)` base samples of\n appropriate dimension, typically obtained from a `Sampler`.\n This is used for deterministic optimization.\n\n Returns:\n A `sample_shape x event_shape`-dim Tensor of samples from the posterior.\n \"\"\"\n if sample_shape is None:\n sample_shape = Size([1])\n if base_samples is not None:\n if base_samples.shape[: len(sample_shape)] != sample_shape:\n raise RuntimeError(\"sample_shape disagrees with shape of base_samples.\")\n # get base_samples to the correct shape\n # THIS IS THE LINE I HAVE CHANGED\n base_samples = base_samples.expand(sample_shape + Size([self.num_samples]) + self.event_shape)\n # remove output dimension in single output case\n if not self._is_mt:\n base_samples = base_samples.squeeze(-1)\n with fast_computations(covar_root_decomposition=False):\n samples = self.mvn.rsample(\n sample_shape=sample_shape, base_samples=base_samples\n )\n # make sure there always is an output dimension\n if not self._is_mt:\n samples = samples.unsqueeze(-1)\n return samples\n\n def rsample(self, sample_shape: Optional[Size] = None, base_samples: Optional[Tensor] = None) -> Tensor:\n \"\"\"\n Args:\n sample_shape: shape of the additional sample dimensions\n base_samples: sample_shape * event_shape Tensor\n \"\"\"\n sample_average_dim = len(sample_shape)\n if base_samples is not None:\n # expand\n base_samples = base_samples.unsqueeze(sample_average_dim).expand(*sample_shape, self.num_samples, *self.event_shape)\n samples = self._replacement_super_rsample(sample_shape=sample_shape, base_samples=base_samples)\n # compact\n return samples.mean(dim=sample_average_dim)\n\n @classmethod\n def from_gpytorch_posterior(cls: Type[T], posterior: GPyTorchPosterior) -> T:\n return cls(mvn=posterior.mvn)\n\n","sub_path":"src/dagbo/sample_average_posterior.py","file_name":"sample_average_posterior.py","file_ext":"py","file_size_in_byte":6525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"234096192","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param a list of ListNode\n # @return a ListNode\n def mergeKLists(self, lists):\n k = len(lists)\n currentHeads = [None] * k\n for i in range(0, k):\n currentHeads[i] = ListNode\n","sub_path":"leetcode/Merge_k_list.py","file_name":"Merge_k_list.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"480387399","text":"#!/usr/bin/env python3\n#-*- coding:utf-8 -*-\n\n__author__ = 'tongzi'\n\nimport tensorflow as tf\n\nwith tf.Graph().as_default():\n\tc1 = tf.constant(5, dtype=tf.float64, name='c')\n\twith tf.name_scope('apple'):\n\t\tc2 = tf.constant(6, dtype=tf.int16, name='c')\n\t\tc3 = tf.constant(7, dtype=tf.int32, name='c')\n\t\t\nprint(c1.name)\nprint(c2.name)\nprint(c3.name)","sub_path":"prefix_name_test.py","file_name":"prefix_name_test.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"62818326","text":"import torch\nfrom torch import nn\n\nfrom algorithms.base.model_utils import create_encoder, create_core \nfrom algorithms.utils.action_distributions import sample_actions_log_probs, is_continuous_action_space\nfrom utils.timing import Timing\nfrom utils.utils import AttrDict\n\n\nclass _DQNBase(nn.Module):\n def __init__(self, action_space, cfg, timing):\n super().__init__()\n self.cfg = cfg\n self.action_space = action_space\n self.timing = timing\n self.encoders = []\n self.cores = []\n\n def model_to_device(self, device):\n self.to(device)\n for e in self.encoders:\n e.model_to_device(device)\n\n def device_and_type_for_input_tensor(self, input_tensor_name):\n return self.encoders[0].device_and_type_for_input_tensor(input_tensor_name)\n\n def initialize_weights(self, layer):\n # gain = nn.init.calculate_gain(self.cfg.nonlinearity)\n gain = 1.0\n\n if self.cfg.policy_initialization == 'orthogonal':\n if type(layer) == nn.Conv2d or type(layer) == nn.Linear:\n nn.init.orthogonal_(layer.weight.data, gain=gain)\n layer.bias.data.fill_(0)\n elif type(layer) == nn.GRUCell or type(layer) == nn.LSTMCell: # TODO: test for LSTM\n nn.init.orthogonal_(layer.weight_ih, gain=gain)\n nn.init.orthogonal_(layer.weight_hh, gain=gain)\n layer.bias_ih.data.fill_(0)\n layer.bias_hh.data.fill_(0)\n else:\n pass\n elif self.cfg.policy_initialization == 'xavier_uniform':\n if type(layer) == nn.Conv2d or type(layer) == nn.Linear:\n nn.init.xavier_uniform_(layer.weight.data, gain=gain)\n layer.bias.data.fill_(0)\n elif type(layer) == nn.GRUCell or type(layer) == nn.LSTMCell:\n nn.init.xavier_uniform_(layer.weight_ih, gain=gain)\n nn.init.xavier_uniform_(layer.weight_hh, gain=gain)\n layer.bias_ih.data.fill_(0)\n layer.bias_hh.data.fill_(0)\n else:\n pass\n\n\n\nclass _SimpleDQN(_DQNBase):\n def __init__(self, make_encoder, make_core, action_space, cfg, timing):\n super().__init__(action_space, cfg, timing)\n\n # in case of shared weights we're using only a single encoder and a single core\n self.encoder = make_encoder()\n self.encoders = [self.encoder]\n\n self.core = make_core(self.encoder)\n self.cores = [self.core]\n\n core_out_size = self.core.get_core_out_size()\n self.q_tail = nn.Linear(core_out_size, self.action_space.n)\n\n self.apply(self.initialize_weights)\n self.train() # eval() for inference?\n\n def forward_head(self, obs_dict):\n x = self.encoder(obs_dict)\n return x\n\n def forward_core(self, head_output):\n return self.core(head_output)\n\n def forward_tail(self, core_output):\n q_values = self.q_tail(core_output)\n\n result = AttrDict(dict(\n q_values=q_values,\n ))\n\n return result\n\n def forward(self, obs_dict):\n x = self.forward_head(obs_dict)\n x = self.forward_core(x)\n result = self.forward_tail(x)\n return result\n\n\nclass _DQN:\n def __init__(self, main, target):\n self.main = main\n self.target = target\n\n\ndef create_dqn(cfg, obs_space, action_space, timing=None):\n if timing is None:\n timing = Timing()\n\n def make_encoder():\n return create_encoder(cfg, obs_space, timing)\n\n def make_core(encoder):\n return create_core(cfg, encoder.get_encoder_out_size())\n\n main = _SimpleDQN(make_encoder, make_core, action_space, cfg, timing)\n target = _SimpleDQN(make_encoder, make_core, action_space, cfg, timing)\n return _DQN(main, target)\n","sub_path":"algorithms/dqn/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"487235303","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 22 11:13:12 2019\n\n@author: jvergara\n\"\"\"\nimport matplotlib \nmatplotlib.use('Agg')\nimport sys\nsys.path.append('/users/jvergara/python_code')\nimport Jesuslib_eth as jle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport glob\nfrom netCDF4 import Dataset\nimport os\n# TensorFlow and tf.keras\nimport tensorflow as tf\n#from tensorflow import keras\nfrom sklearn.model_selection import train_test_split\nif __name__=='__main__':tf.enable_eager_execution()\n\nhome_folder,store_folder,sc_folder=jle.Create_project_folders('BIAS_PRECIP_ML',sc=1)\nstore_folder='/scratch/snx3000/jvergara/BIAS_PRECIP_ML/'\nswitzerland_mask=np.load(store_folder+'swiss_mask.npy')\n\nmodel_name='temp_3_layer_3_fields_1drop_l1'\n#sess = tf.Session()\n#%% =============================================================================\n# Load data\n# =============================================================================\n\nmodel_data=np.load(store_folder+'COSMO_daily_cumulated_prec.npy')\nmodel_data_T=np.load(store_folder+'COSMO_daily_mean_dd_T_2M.npy')\nmodel_data_RH=np.load(store_folder+'COSMO_daily_mean_RELHUM_2M.npy')\n#model_data_T=np.load(store_folder+'COSMO_daily_mean_ASWD_S.npy')\n#model_data=model_data[:1096]\nobs_data=np.load(store_folder+'RdisaggH_daily_cumulated_prec.npy')[:model_data.shape[0],]\nobs_data_T=np.load(store_folder+'TabsD_daily.npy')[:model_data.shape[0],]+273.15\n\nmissing_data=obs_data<0\nobs_data[missing_data]=0\nmodel_data[missing_data]=0\nbias=model_data-obs_data\n\nobs_data_T[np.isnan(model_data_T)]=np.nan\n\nbias_T=model_data_T-obs_data_T\n\n\n\n\n\n#%% =============================================================================\n# Plot current biases\n# =============================================================================\nds_lat_lon=Dataset(store_folder+'RdisaggH_ch01r.swisscors_latlon.nc')\n\nlevels=np.linspace(-3,3,11)\njle.Quick_plot(bias.mean(axis=0),'Biases COSMOpompa-RdisaggH ',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu,cb_format=\"%1.2f\",cb_label='mm/day')\njle.Quick_plot(bias_T.mean(axis=0),'Biases COSMOpompa-TabsD',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu_r,cb_format=\"%1.2f\",cb_label='C')\n\n\n\n#%% =============================================================================\n# Split training and evaluation\n# =============================================================================\n\nmask=switzerland_mask\ndef reconstruct_array(array_flat,mask):\n indx=0\n r_array=np.zeros(mask.shape)\n for i in range(r_array.shape[0]):\n for j in range(r_array.shape[1]):\n if mask[i,j]:\n r_array[i,j]=np.nan\n else:\n r_array[i,j]=array_flat[indx]\n indx+=1\n return r_array\nbias_flat=bias.mean(axis=0).flatten()\nbias_flat_reduced=bias_flat[~switzerland_mask.flatten()]\nbias_reconstructed=reconstruct_array(bias_flat_reduced,mask)\njle.Quick_plot(bias_reconstructed,'Biases RdisaggH-COSMOpompa ',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu,cb_format=\"%1.2f\",cb_label='mm/day')\n#bias_flat=bias.reshape((bias.shape[0],bias.shape[1]*bias.shape[2]))\n\n#%%\n\nbias_data_flat=bias.reshape((bias.shape[0],bias.shape[1]*bias.shape[2]))\nbias_T_data_flat=bias_T.reshape((bias_T.shape[0],bias_T.shape[1]*bias_T.shape[2]))\nmodel_data_flat=model_data.reshape((model_data.shape[0],model_data.shape[1]*model_data.shape[2]))\nmodel_data_T_flat=model_data_T.reshape((model_data.shape[0],model_data.shape[1]*model_data.shape[2]))\nmodel_data_RH_flat=model_data_RH.reshape((model_data.shape[0],model_data.shape[1]*model_data.shape[2]))\nobs_data_flat=obs_data.reshape((obs_data.shape[0],obs_data.shape[1]*obs_data.shape[2]))\nobs_data_T_flat=obs_data_T.reshape((obs_data.shape[0],obs_data.shape[1]*obs_data.shape[2]))\n\nbias_data_flat=bias_data_flat[:,~switzerland_mask.flatten()]\nbias_T_data_flat=bias_T_data_flat[:,~switzerland_mask.flatten()]\nmodel_data_flat=model_data_flat[:,~switzerland_mask.flatten()]\nmodel_data_T_flat=model_data_T_flat[:,~switzerland_mask.flatten()]\nmodel_data_RH_flat=model_data_RH_flat[:,~switzerland_mask.flatten()]\nobs_data_flat=obs_data_flat[:,~switzerland_mask.flatten()]\nobs_data_T_flat=obs_data_T_flat[:,~switzerland_mask.flatten()]\n\n\n#%%\n#model_data=np.load(store_folder+'COSMO_daily_cumulated_prec.npy')\n#model_data_T=np.load(store_folder+'COSMO_daily_mean_dd_T_2M.npy')\n#model_data_RH=np.load(store_folder+'COSMO_daily_mean_RELHUM_2M.npy')\n##model_data_T=np.load(store_folder+'COSMO_daily_mean_ASWD_S.npy')\n##model_data=model_data[:1096]\n#obs_data=np.load(store_folder+'RdisaggH_daily_cumulated_prec.npy')[:model_data.shape[0],]\n#obs_data_T=np.load(store_folder+'TabsD_daily.npy')[:model_data.shape[0],]+273.15\n\n\n\nnp.save(store_folder+'COSMO_daily_cumulated_prec_flat.npy',model_data_flat)\nnp.save(store_folder+'COSMO_daily_mean_dd_T_2M_flat.npy',model_data_T_flat)\nnp.save(store_folder+'COSMO_daily_mean_RELHUM_2M_flat.npy',model_data_RH_flat)\nnp.save(store_folder+'RdisaggH_daily_cumulated_prec_flat.npy',obs_data_flat)\nnp.save(store_folder+'TabsD_daily_flat.npy',obs_data_T_flat)\n\n\n\n\n\n#%%\ncut=int(len(model_data_flat)*0.8)\nmodel_data_T_train=model_data_T_flat[:cut,]\nmodel_data_T_val=model_data_T_flat[cut:,]\nmodel_data_RH_train=model_data_RH_flat[:cut,]\nmodel_data_RH_val=model_data_RH_flat[cut:,]\ninput_tensor_train=model_data_flat[:cut,]\ninput_tensor_val=model_data_flat[cut:,]\n#target_tensor_train=bias_data_flat[:cut,]\n#target_tensor_val=bias_data_flat[cut:,]\ntarget_tensor_train=bias_T_data_flat[:cut,]\ntarget_tensor_val=bias_T_data_flat[cut:,]\n#target_tensor_val=bias_data_flat[cut:,]\n#obs_data_val=obs_data_flat[cut:,]\nobs_data_val=obs_data_flat[cut:,]\nobs_data_train=obs_data_flat[:cut,]\n\nobs_data_T_val=obs_data_T_flat[cut:,]\nobs_data_T_train=obs_data_T_flat[:cut,]\n\n\n\n\n# input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(model_data_flat, bias_data_flat, test_size=0.2)\n\n#%%\ninput_tensor_train=np.concatenate((input_tensor_train,model_data_T_train,model_data_RH_train),axis=1)\ninput_tensor_val=np.concatenate((input_tensor_val,model_data_T_val,model_data_RH_val),axis=1)\n\n\n#%%\n# =============================================================================\n# Normalize\n# =============================================================================\n\n#Create means and std\n\nmeans_input=input_tensor_train.mean(axis=0)\nstd_input=np.std(input_tensor_train,axis=0)\n\ndef Normalize_input(array):\n normalized=(array-means_input)/std_input\n return normalized\ninput_tensor_train_norm=np.apply_along_axis(Normalize_input,1,input_tensor_train)\ninput_tensor_val_norm=np.apply_along_axis(Normalize_input,1,input_tensor_val)\n\ndef DeNormalize_input(array_norm):\n array=(array_norm*std_input)+means_input\n return array\n\n#%%\nmeans_target=target_tensor_train.mean(axis=0)\nstd_target=np.std(target_tensor_train,axis=0)\n\ndef Normalize_target(array):\n normalized=(array-means_target)/std_target\n return normalized\ntarget_tensor_train_norm=np.apply_along_axis(Normalize_target,1,target_tensor_train)\ntarget_tensor_val_norm=np.apply_along_axis(Normalize_target,1,target_tensor_val)\n\ndef DeNormalize_target(array_norm):\n array=(array_norm*std_target)+means_target\n return array\ntarget_tensor_train_norm_denorm=np.apply_along_axis(DeNormalize_target,1,target_tensor_train_norm)\n\n\n#plt.hist(target_tensor_train[:,30])\n#plt.hist(target_tensor_train_norm[30,:])\n#plt.hist(target_tensor_train_norm_denorm[30,:])\n#diffs=target_tensor_train_norm_denorm[30,:]-target_tensor_train[30,:]\n\n\n\n#%% =============================================================================\n# Define model\n# =============================================================================\nif __name__=='__main__':\n single_field_index=46718\n import tensorflow.contrib.eager as tfe\n model = tf.keras.Sequential([\n tf.keras.layers.Dense(1600,activation=tf.nn.relu,input_shape=(single_field_index*3,)),\n tf.keras.layers.Dense(1600,kernel_regularizer=tf.keras.regularizers.l1(0.001)),\n tf.keras.layers.Dropout(0.5),\n # tf.keras.layers.Dense(1600, activation=tf.nn.relu),\n tf.keras.layers.Dense(6400,kernel_regularizer=tf.keras.regularizers.l1(0.001), activation=tf.nn.relu),\n# tf.keras.layers.Dropout(0.5),\n # tf.keras.layers.Dense(46718),\n # tf.keras.layers.Dropout(0.5),\n tf.keras.layers.Dense(46718),\n ])\n optimizer = tf.keras.optimizers.RMSprop(0.001)\n optimizer=tf.train.RMSPropOptimizer(0.0001)\n# optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.002)\n def loss(model, inputs, targets):\n error = model(inputs) - targets\n return tf.reduce_mean(tf.square(error))\n model.compile(loss='mean_squared_error',\n optimizer=optimizer)\n \n model.summary()\n \n \n \n #%% =============================================================================\n # Fit model\n # =============================================================================\n \n checkpoint_path = store_folder+\"cp_\"+model_name+\"-{epoch:03d}.ckpt\"\n cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, \n save_weights_only=True,\n verbose=1,period=50)\n from tensorflow.keras.callbacks import CSVLogger\n \n csv_logger = CSVLogger(store_folder+\"model_history_\"+model_name+\".csv\", append=True)\n \n history = model.fit(input_tensor_train,\n target_tensor_train,\n epochs=1500,\n # batch_size=100,\n validation_data=(input_tensor_val, target_tensor_val),\n callbacks = [cp_callback,csv_logger])#,\n # verbose=2)\n #sess = tf.Session()\n \n predictions=model(input_tensor_val)\n predictions=predictions.numpy()\n predictions_2D=reconstruct_array(predictions.mean(axis=0),switzerland_mask)\n jle.Quick_plot(predictions_2D,'Bias predictions RdisaggH-COSMOpompa ',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu,cb_format=\"%1.2f\",cb_label='mm/day')\n \n #%%\n #corrected_model=input_tensor_val+predictions\n \n \n #jle.Quick_plot(reconstruct_array(predictions.mean(axis=0),switzerland_mask),'Bias predictions RdisaggH-COSMOpompa ',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu,cb_format=\"%1.2f\",cb_label='mm/day')\n #obs_data_val\n \n \n model.save(store_folder+model_name+'.h5')\n \n '''\n new_bias_flat=(obs_data_val-corrected_model).numpy()\n old_bias_flat=(target_tensor_val).numpy()\n \n new_bias=np.zeros((new_bias_flat.shape[0],switzerland_mask.shape[0],switzerland_mask.shape[1]))\n old_bias=np.zeros((old_bias_flat.shape[0],switzerland_mask.shape[0],switzerland_mask.shape[1]))\n for i in range(new_bias_flat.shape[0]):\n print(i)\n new_bias[i,]=reconstruct_array(new_bias_flat[i],switzerland_mask)\n old_bias[i,]=reconstruct_array(old_bias_flat[i],switzerland_mask)\n \n \n \n \n #corrected_model_2D \n #jle.Quick_plot(bias.mean(axis=0),'Biases RdisaggH-COSMOpompa ',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu,cb_format=\"%1.2f\",cb_label='mm/day')\n jle.Quick_plot(target_tensor_val.mean(axis=0),'Biases RdisaggH-COSMOpompa ',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu,cb_format=\"%1.2f\",cb_label='mm/day')\n jle.Quick_plot(new_bias.mean(axis=0),'New biases RdisaggH-COSMOpompa ',metadata_dataset=ds_lat_lon,levels=levels,extend='both',cmap=plt.cm.RdBu,cb_format=\"%1.2f\",cb_label='mm/day')\n '''\n","sub_path":"create_model_T2M_and_Prec.py","file_name":"create_model_T2M_and_Prec.py","file_ext":"py","file_size_in_byte":11721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"1090163","text":"#!/usr/bin/env python\n\nimport cv2\nimport time\nimport numpy as np\nfrom helper import switch_color, read_image, adaptive_thresholding\n\n# Function for Lab 5\n# Take an black and white image and find the object in it, returns an associated image with different color for each image\n# You will implement your algorithm for rastering here\ndef associate_objects(bw_image, pixellabel, associate_image):\n\n height, width = bw_image.shape[0], bw_image.shape[1]\n \n # Create a demo image of colored lines\n num = 0 \n for row in range(height):\n for col in range(width):\n pixellabel[row][col] = num\n num = num + 1\n if(num == 10):\n num = 0 \n\n for row in range(height):\n for col in range(width):\n (blue, green, red) = switch_color(pixellabel[row][col])\n associate_image[row][col][0] = blue\n associate_image[row][col][1] = green\n associate_image[row][col][2] = red\n\n return associate_image\n\n\nif __name__ == '__main__':\n\n image_name = \"./images/1.jpg\"\n image, gray_image = read_image(image_name)\n bw_image = adaptive_thresholding(gray_image)\n\n height, width = bw_image.shape[0], bw_image.shape[1]\n \n # Create a 2D array pixellabel[height][width]\n # In the bw_image, 0 is black, 255 is white\n # If image pixel is white pixellabel[row][col] = -1\n # If image pixel is black pixellabel[row][col] = 0\n # pixellabel = ((bw_image.copy()+1)*-1+1)*-1\n pixellabel = ((bw_image.copy()+1)*-1+1)*-1 # numpy.int16 == short\n \n associate_image = np.zeros([height, width, 3], dtype=np.uint8)\n\n start_time = time.time()\n result_image = associate_objects(bw_image, pixellabel, associate_image)\n end_time = time.time()\n print(\"Associate objects without Cython processed %s seconds.\" % (end_time - start_time))\n\n cv2.imshow(\"(1) Original Image\", image)\n cv2.imshow(\"(2) Gray Image\", gray_image)\n cv2.imshow(\"(3) Binary Image\", bw_image)\n cv2.imshow(\"(4) Result Image\", result_image)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \n\n","sub_path":"lab56_checkout/lab5_func.py","file_name":"lab5_func.py","file_ext":"py","file_size_in_byte":2081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"620246290","text":"from sklearn.model_selection import train_test_split\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn import metrics\r\nimport cv2\r\nimport numpy as np\r\nimport glob \r\nimport os.path\r\n\r\n# Directory and file detection using path name\r\ndef list(path): \r\n fichier=[] \r\n l = glob.glob(path+'\\\\*')\r\n for i in l: \r\n if os.path.isdir(i):fichier.extend(list(i))\r\n else: fichier.append(i) \r\n return fichier # Return a string array that contains the name of different path file\r\n\r\n# Preparation of both matrix X(arx) and y(ary)\r\ndef dataPreparation(file):\r\n arx = []\r\n ary = []\r\n for i in range(0, len(file)):\r\n img = cv2.imread(file[i]) # Read the image at the i'th position\r\n dsize = (100, 100) #\r\n img = cv2.resize(img, dsize) # Resize it\r\n arx.append(img) # Add it to our array\r\n # _______________creation of our y matrix ________________\r\n if 'ColorClassification\\Black' in file[i]: # Just detect the path name and add a value in our y array\r\n ary.append(0) #\r\n if 'ColorClassification\\Blue' in file[i]: #\r\n ary.append(1) #\r\n if 'ColorClassification\\Brown' in file[i]: #\r\n ary.append(2) #\r\n if 'ColorClassification\\Green' in file[i]: #\r\n ary.append(3) #\r\n if 'ColorClassification\\Orange' in file[i]: #\r\n ary.append(4) #\r\n if 'ColorClassification\\Red' in file[i]: #\r\n ary.append(5) #\r\n if 'ColorClassification\\Violet' in file[i]: #\r\n ary.append(6) #\r\n if 'ColorClassification\\White' in file[i]: #\r\n ary.append(7) #\r\n if 'ColorClassification\\Yellow' in file[i]: #______________________________________________________\r\n ary.append(8) # \r\n arx = np.array(arx) # Transorm my final X array to a numpy array ( matrix )\r\n arx = arx.reshape(107,-1) # Reshape it for cast to 2dim \r\n arx = arx/255.0 # Divide all my matrix so that values are between 0 and 1\r\n ary = np.array(ary) # Transform my fianel y array to a numpy array ( matrix )\r\n #\r\n return arx, ary # Return both matrix \r\n\r\n# Preparation of the model that we gonna use ( using matrix X and y )\r\ndef modelPreparation(file): \r\n X, y = dataPreparation(file) \r\n \r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1) # Split matrix into random train and test subsets\r\n #\r\n random_forest_classifier = RandomForestClassifier(n_estimators=20, max_depth=10) # Creation of n Forest Classifier\r\n random_forest_classifier.fit(X_train,y_train) # Build a forest of trees from the training set ( X, y )\r\n #\r\n y_pred = random_forest_classifier.predict(X_test) # Predict class for X\r\n print(\"Model Accuracy :\",metrics.accuracy_score(y_test, y_pred)) # Accuracy classification score\r\n #\r\n return random_forest_classifier # Return my model\r\n\r\n# Treatments for our new image\r\ndef newDataTreatment(img_name): # ___ We apply the same processing of our X matrix on our new image and return it ___\r\n data = cv2.imread(img_name) #\r\n dsize = (100, 100) #\r\n #\r\n data = cv2.resize(data, dsize) #\r\n data = np.array(data) #\r\n data = data.reshape(1, -1) #\r\n data = data/255.0 #\r\n #\r\n return data # Return ou matrix\r\n\r\n#Testing new image on our model\r\ndef testNewData(random_forest_classifier):\r\n colorName = ['Black', 'Blue', 'Brown', 'Green', 'Orange', 'Red', 'Violet', 'White', 'Yellow']\r\n \r\n data_one = newDataTreatment(\"images_test\\\\1.jpg\") # Using 1st image\r\n data_two = newDataTreatment(\"images_test\\\\5.jpg\") # Using 5th image\r\n #\r\n res_data_one = random_forest_classifier.predict(data_one) # Apply our model\r\n res_data_two = random_forest_classifier.predict(data_two) # on our images\r\n #\r\n print(\"The color of the first image is %s\" % colorName[res_data_one[0]]) # Print the result of our prediction\r\n print(\"The color of the second image is %s\" % colorName[res_data_two[0]])\r\n\r\n\r\n\r\n## ___Main___ ##\r\n \r\nfile = list('ColorClassification')\r\nmodel = modelPreparation(file)\r\ntestNewData(model)\r\n\r\n\r\n","sub_path":"Imagik_MachineLearning.py","file_name":"Imagik_MachineLearning.py","file_ext":"py","file_size_in_byte":5827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"441408573","text":"\n\n#calss header\nclass _UNAVAILABLE():\n\tdef __init__(self,): \n\t\tself.name = \"UNAVAILABLE\"\n\t\tself.definitions = [u'If someone is unavailable, they are not able to talk to people or meet people, usually because they are doing other things: ', u'If something is unavailable, you cannot get it or use it: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_unavailable.py","file_name":"_unavailable.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"181095312","text":"# needs super thinking about it\nclass Solution:\n def combinationSum4(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n dp = [0] * (target + 1)\n dp[0] = 1\n for oneT in range(1, target + 1):\n for num in nums:\n if oneT >= num:\n dp[oneT] = dp[oneT] + dp[oneT - num]\n return dp[-1]\n\n\n\ns = Solution()\nprint(s.combinationSum4([1,2,3], 4))\n","sub_path":"python/377_combinationSum4.py","file_name":"377_combinationSum4.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"277780952","text":"from rdkit.ML.Descriptors import MoleculeDescriptors\nfrom rdkit.Chem import Descriptors\nfrom rdkit import Chem\nimport pandas as pd\nimport argparse\n\n\n\n\ndef calc_descriptors_from_file(filename):\n \"\"\" calculates rdkit descriptors from a smiles.txt file \"\"\"\n df = pd.read_table(filename, header=None)\n df['rdkit'] = [Chem.MolFromSmiles(smi) for smi in df[0]]\n df[pd.isnull(df['rdkit'])].to_csv('errors.txt')\n df = df[~pd.isnull(df['rdkit'])]\n calc = MoleculeDescriptors.MolecularDescriptorCalculator([desc[0] for desc in Descriptors.descList])\n\n X = pd.DataFrame([list(calc.CalcDescriptors(mol)) for mol in df['rdkit']],\n columns=list(calc.GetDescriptorNames()),\n index=df[0].values)\n\n X.to_csv('descriptors.csv')\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Process RDKit descriptors from smiles.txt file.')\n parser.add_argument('filename', metavar='F', type=str,\n help='the filename of the smiles.txt file')\n\n args = parser.parse_args()\n\n calc_descriptors_from_file(args.filename)","sub_path":"calculate_descriptors.py","file_name":"calculate_descriptors.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"409559817","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 25 18:04:20 2018\r\n@author: Carl\r\n\"\"\"\r\n\r\nimport os\r\nSCRIPT_PATH = os.path.dirname(os.path.abspath( __file__ ))\r\nimport glob\r\nos.environ[\"KERAS_BACKEND\"] = \"tensorflow\"\r\nimport numpy as np\r\nfrom sklearn.utils import shuffle\r\nimport time\r\nimport cv2\r\nimport scipy\r\nimport imageio\r\nfrom PIL import Image\r\nimport matplotlib.gridspec as gridspec\r\nfrom keras.layers import Dense\r\nfrom keras.layers import Reshape\r\nfrom keras.layers.core import Activation\r\nfrom keras.layers.normalization import BatchNormalization\r\nfrom keras.layers.convolutional import UpSampling2D\r\nfrom keras.layers.pooling import MaxPooling2D\r\nfrom keras.layers.core import Flatten\r\nfrom keras.layers import Input\r\nfrom keras.utils import plot_model\r\nfrom keras.layers import Conv2D, Conv2DTranspose, Dropout\r\nfrom keras.models import Model\r\nfrom keras.optimizers import SGD, Adam, RMSprop\r\nfrom keras.layers.advanced_activations import LeakyReLU\r\nfrom ACGAN_animate_model import ACGAN\r\nfrom loadimage import pictureload, return_label_num\r\nimport matplotlib.pyplot as plt\r\nfrom keras.models import load_model\r\nimport keras.backend as K\r\nfrom scipy.interpolate import spline\r\nK.set_image_dim_ordering('tf')\r\n\r\nfrom collections import deque\r\n\r\nnp.random.seed(36)\r\n\r\ndef norm_img(img):\r\n img = (img / 127.5) - 1\r\n return img\r\n\r\ndef denorm_img(img):\r\n img = (img + 1) * 127.5\r\n return img.astype(np.uint8) \r\n\r\ndef load_data(batch_size, image_shape, data = None):\r\n sample_dim = (batch_size,) + image_shape\r\n sample = np.empty(sample_dim, dtype=np.float32)\r\n all_data_dirlist = pictureload()\r\n all_data_dirlist = all_data_dirlist.sample(n=batch_size)\r\n alltable = all_data_dirlist.iloc[:,0]\r\n # print(all_data_dirlist.iloc[:,1])\r\n i = 0 \r\n for index, row in alltable.iteritems():\r\n image = Image.open(row)\r\n image = image.resize(image_shape[:-1])\r\n image = image.convert('RGB') #remove transparent ('A') layer\r\n image = np.asarray(image)\r\n image = norm_img(image)\r\n sample[i,...] = image\r\n i += 1\r\n return sample, all_data_dirlist.iloc[:,1]\r\n\r\ndef save_img_batch(img_batch,img_save_dir):\r\n plt.figure(figsize=(4,4))\r\n gs1 = gridspec.GridSpec(4, 4)\r\n gs1.update(wspace=0, hspace=0)\r\n rand_indices = np.random.choice(img_batch.shape[0],16,replace=False)\r\n #print(rand_indices)\r\n for i in range(16):\r\n #plt.subplot(4, 4, i+1)\r\n ax1 = plt.subplot(gs1[i])\r\n ax1.set_aspect('equal')\r\n rand_index = rand_indices[i]\r\n image = img_batch[rand_index, :,:,:]\r\n fig = plt.imshow(denorm_img(image))\r\n plt.axis('off')\r\n fig.axes.get_xaxis().set_visible(False)\r\n fig.axes.get_yaxis().set_visible(False)\r\n plt.tight_layout()\r\n plt.savefig(img_save_dir,bbox_inches='tight',pad_inches=0)\r\n # plt.show() \r\n\r\nnum_steps = 10000\r\nbatch_size = 64\r\nlatent_dim = 110\r\nnum_classes = return_label_num()\r\nimage_shape = (32,32,3)\r\n###################### still need modify\r\nimg_save_dir = SCRIPT_PATH + \"/train_record\"\r\n######################\r\nlog_dir = img_save_dir\r\nsave_model_dir = img_save_dir\r\n\r\n\r\n# load discriminator and generator models\r\nacgan = ACGAN(num_classes)\r\nd_model, g_model, gan = acgan.return_model()\r\n\r\ng_model.summary()\r\nplot_model(g_model, to_file=SCRIPT_PATH+'/model_plots/generate.png')\r\n\r\nd_model.summary()\r\nplot_model(d_model, to_file=SCRIPT_PATH+'/model_plots/discriminator.png')\r\nd_model.trainable = False\r\n\r\n# build gan model\r\ngan.summary()\r\nplot_model(gan, to_file=SCRIPT_PATH+'/model_plots/gan.png')\r\n\r\n# loss data record\r\navg_disc_fake_loss = deque([0], maxlen=250) \r\navg_disc_real_loss = deque([0], maxlen=250)\r\navg_GAN_loss = deque([0], maxlen=250)\r\n\r\nfor step in range(num_steps): \r\n tot_step = step\r\n print(\"Begin step: \", tot_step)\r\n step_begin_time = time.time() \r\n\r\n # load dataset\r\n real_data_X, label_batch = load_data(batch_size, image_shape)\r\n\r\n # generate noise to picture\r\n noise = np.random.normal(0, 0.5, (batch_size, latent_dim))\r\n sampled_labels = np.random.randint(0, num_classes, batch_size)\r\n \r\n fake_data_X = g_model.predict([noise, sampled_labels.reshape((-1, 1))], verbose=0) \r\n if (tot_step % 10) == 0:\r\n step_num = str(tot_step).zfill(4)\r\n save_img_batch(fake_data_X,img_save_dir + \"/generateimage/\" + step_num + \"_image.png\")\r\n\r\n d_model.trainable = True\r\n g_model.trainable = False\r\n\r\n for train_ix in range(3):\r\n if step % 30 != 0:\r\n X_real = real_data_X\r\n # Label Soomthing\r\n y_real = np.random.uniform(0.7, 1.2, size=(batch_size,))\r\n aux_y1 = label_batch.values.reshape(-1, )\r\n dis_metrics_real = d_model.train_on_batch(X_real, [y_real, aux_y1])\r\n # Label Soomthing\r\n X_fake = fake_data_X\r\n y_fake = np.random.uniform(0.0, 0.3, size=(batch_size,))\r\n aux_y2 = sampled_labels\r\n # see if the discriminator can figure itself out...\r\n dis_metrics_fake = d_model.train_on_batch(X_fake, [y_fake, aux_y2])\r\n print(\"Disc: real loss: %f fake loss: %f\" % (dis_metrics_real[0], dis_metrics_fake[0]))\r\n avg_disc_fake_loss.append(dis_metrics_fake[0])\r\n avg_disc_real_loss.append(dis_metrics_real[0])\r\n else:\r\n # make the labels the noisy for the discriminator: occasionally flip the labels\r\n # when training the discriminator\r\n X_real = fake_data_X\r\n y_real = np.random.uniform(0.0, 0.3, size=(batch_size,))\r\n aux_y1 = sampled_labels\r\n dis_metrics_real = d_model.train_on_batch(X_real, [y_real, aux_y1])\r\n # Label Soomthing\r\n X_fake = real_data_X\r\n y_fake = np.random.uniform(0.7, 1.2, size=(batch_size,))\r\n aux_y2 = label_batch.values.reshape(-1, )\r\n # see if the discriminator can figure itself out...\r\n dis_metrics_fake = d_model.train_on_batch(X_fake, [y_fake, aux_y2])\r\n \r\n # train generate\r\n g_model.trainable = True\r\n d_model.trainable = False\r\n\r\n noise = np.random.normal(0, 0.5, (2 * batch_size, latent_dim))\r\n sampled_labels = np.random.randint(0, num_classes, 2 * batch_size)\r\n trick = np.random.uniform(0.7, 1.2, size=(2 * batch_size,))\r\n gan_metrics = gan.train_on_batch(\r\n [noise, sampled_labels.reshape((-1, 1))], [trick, sampled_labels])\r\n avg_GAN_loss.append(gan_metrics[0])\r\n print(\"GAN loss: %f\" % (gan_metrics[0]))\r\n\r\n text_file = open(log_dir+\"/training_log.txt\", \"a\")\r\n text_file.write(\"Step: %d Disc: real loss: %f fake loss: %f GAN loss: %f\\n\" % (tot_step, avg_disc_real_loss[0], avg_disc_fake_loss[0],avg_GAN_loss[0]))\r\n text_file.close()\r\n avg_GAN_loss.append(gan_metrics[0])\r\n\r\n # g_model.trainable = True\r\n # d_model.trainable = False\r\n\r\n # # train gan\r\n # noise = np.random.normal(0, 0.5, (2 * nb_test, latent_size))\r\n # sampled_labels = np.random.randint(0, class_num, 2 * nb_test)\r\n # trick = np.ones(2 * nb_test)\r\n # generator_test_loss = combined.evaluate(\r\n # [noise, sampled_labels.reshape((-1, 1))],\r\n # [trick, sampled_labels], verbose=False) \r\n \r\n # GAN_X = np.random.normal(0, 1, size=(batch_size,)+noise_shape)\r\n # GAN_Y = real_data_Y\r\n # gan_metrics = gan.train_on_batch(GAN_X,GAN_Y)\r\n # print(\"GAN loss: %f\" % (gan_metrics[0]))\r\n \r\n \r\n end_time = time.time()\r\n diff_time = int(end_time - step_begin_time)\r\n print(\"Step %d completed. Time took: %s secs.\" % (tot_step, diff_time))\r\n \r\n if ((tot_step+1) % 500) == 0:\r\n print(\"-----------------------------------------------------------------\")\r\n print(\"Average Disc_fake loss: %f\" % (np.mean(avg_disc_fake_loss))) \r\n print(\"Average Disc_real loss: %f\" % (np.mean(avg_disc_real_loss))) \r\n print(\"Average GAN loss: %f\" % (np.mean(avg_GAN_loss)))\r\n print(\"-----------------------------------------------------------------\")\r\n d_model.trainable = True\r\n g_model.trainable = True\r\n # g_model.save(save_model_dir+'/models_set/'+str(tot_step)+\"_GENERATOR_weights_and_arch.hdf5\")\r\n # d_model.save(save_model_dir+'/models_set/'+str(tot_step)+\"_DISCRIMINATOR_weights_and_arch.hdf5\")\r\n g_model.save_weights(save_model_dir+'/models_set/'+str(tot_step)+\"_GENERATOR_weights_and_arch.hdf5\")\r\n d_model.save_weights(save_model_dir+'/models_set/'+str(tot_step)+\"_DISCRIMINATOR_weights_and_arch.hdf5\")\r\n\r\n#generator = load_model(save_model_dir+'9999_GENERATOR_weights_and_arch.hdf5')\r\n\r\n#generate final sample images\r\n# for i in range(10):\r\n# noise = np.random.normal(0, 1, size=(batch_size,)+noise_shape)\r\n# fake_data_X = generator.predict(noise) \r\n# save_img_batch(fake_data_X,img_save_dir+\"/generateimage/\"+\"final\"+\"\"str(i)+\"_image.png\")\r\n\r\n\r\n# \"\"\"\r\n# #Display Training images sample\r\n# save_img_batch(sample_from_dataset(batch_size, image_shape, data_dir = data_dir),img_save_dir+\"_12TRAINimage.png\")\r\n# \"\"\"\r\n\r\n# #Generating GIF from PNG\r\n# images = []\r\n# all_data_dirlist = list(glob.glob(img_save_dir+\"*_image.png\"))\r\n# for filename in all_data_dirlist:\r\n# img_num = filename.split('\\\\')[-1][0:-10]\r\n# if (int(img_num) % 100) == 0:\r\n# images.append(imageio.imread(filename))\r\n# imageio.mimsave(img_save_dir+'movie.gif', images) \r\n \r\n# \"\"\"\r\n# Alternate way to convert PNG to GIF (ImageMagick):\r\n# >convert -delay 10 -loop 0 *_image.png animated.gif\r\n# \"\"\"","sub_path":"old model/ACGAN_animate_main2.py","file_name":"ACGAN_animate_main2.py","file_ext":"py","file_size_in_byte":9543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"36349589","text":"\n\n\"\"\"\n\nAuthor: Nyasha Pride Masamba\n\nBased on the lessons from Codecademy at https://www.codecademy.com/learn/python\n\nThis Python program is an example of modularity, encapsulation and algorithmic thinking.\nIt is simply a function that takes in a list of numbers. It will then return another list\nwith all odd numbers in the list, and returns the result. Do not directly modify the list \nyou are given as input; instead, return a new list with only the even numbers.\n\nExample input and output:\npurify([1,2,3]) should return [2]. \n\n\"\"\"\n\n\ndef purify(lst):\n purified = []\n for i in lst:\n if i % 2 == 0:\n purified.append(i)\n return purified","sub_path":"18_purify.py","file_name":"18_purify.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"92645238","text":"from engine.poteen.basePage import BasePage\nfrom engine.poteen.elements.basic.button import Button\nfrom engine.poteen.elements.basic.input import Input\n\n\nclass IpRangeRow(BasePage):\n def __init__(self, parent=None):\n self.ip_range_start = Input(\n xpath=\".//input[@name='ip_ranges-start']\",\n element_name=\"Ip range start\")\n\n self.ip_range_end = Input(\n xpath=\".//input[@name='ip_ranges-end']\",\n element_name=\"Ip range end\")\n\n self.ip_range_add = Button(\n xpath=\".//button[contains(@class,'ip-ranges-add')]\",\n element_name=\"Ip range add\")\n\n self.ip_range_delete = Button(\n xpath=\".//button[contains(@class,'ip-ranges-delete')]\",\n element_name=\"Ip range delete\")\n\n BasePage.__init__(self, parent)\n","sub_path":"tests/components/functionality/cluster/generic/ip_range_row.py","file_name":"ip_range_row.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"268932432","text":"import json\nimport sys\nfrom reporter import Reporter\n\n\nclass JSONReporter(Reporter):\n def __init__(self, explorer):\n super().__init__(explorer)\n\n def report(self, filename=None):\n report = super().get_values()\n f = sys.stdout\n if filename is not None:\n f = open(filename, 'w')\n json.dump(report, f)\n","sub_path":"src/json_reporter.py","file_name":"json_reporter.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"297574884","text":"import json\nimport logging\nfrom pprint import pformat\nfrom urllib.parse import quote as urlquote\n\nimport httpx\n\nfrom .db import DB\n\n\nclass OrbitDbAPI ():\n def __init__ (self, **kwargs):\n self.logger = logging.getLogger(__name__)\n self.__config = kwargs\n self.__base_url = self.__config.get('base_url')\n self.__use_db_cache = self.__config.get('use_db_cache', True)\n self.__timeout = self.__config.get('timeout', 30)\n self.__session = httpx.Client()\n self.logger.debug('Base url: ' + self.__base_url)\n\n @property\n def session(self):\n return self.__session\n\n @property\n def base_url(self):\n return self.__base_url\n\n @property\n def use_db_cache(self):\n return self.__use_db_cache\n\n def _do_request(self, *args, **kwargs):\n self.logger.log(15, json.dumps([args, kwargs]))\n kwargs['timeout'] = kwargs.get('timeout', self.__timeout)\n try:\n return self.__session.request(*args, **kwargs)\n except:\n self.logger.exception('Exception during api call')\n raise\n\n def _call_raw(self, method, endpoint, **kwargs):\n url = '/'.join([self.__base_url, endpoint])\n return self._do_request(method, url, **kwargs)\n\n def _call(self, method, endpoint, **kwargs):\n res = self._call_raw(method, endpoint, **kwargs)\n try:\n result = res.json()\n except:\n self.logger.warning('Json decode error', exc_info=True)\n self.logger.log(15, res.text)\n raise\n try:\n res.raise_for_status()\n except:\n self.logger.exception('Server Error')\n self.logger.error(pformat(result))\n raise\n return result\n\n def list_dbs(self):\n return self._call('GET', 'dbs')\n\n def db(self, dbname, local_options=None, **kwargs):\n if local_options is None: local_options = {}\n return DB(self, self.open_db(dbname, **kwargs), **{**self.__config, **local_options})\n\n def open_db(self, dbname, **kwargs):\n endpoint = '/'.join(['db', urlquote(dbname, safe='')])\n return self._call('POST', endpoint, **kwargs)\n\n def searches(self):\n endpoint = '/'.join(['peers', 'searches'])\n return self._call('GET', endpoint)\n","sub_path":"orbitdbapi/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"259276903","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\nfrom azure.core.configuration import Configuration, ConnectionConfiguration\nfrom azure.core.pipeline import policies\n\nfrom ..version import VERSION\n\n\nclass KeyVaultClientConfiguration(Configuration):\n \"\"\"Configuration for KeyVaultClient\n Note that all parameters used to create this instance are saved as instance\n attributes.\n\n :param credentials: Credentials needed for the client to connect to Azure.\n :type credentials: :mod:`A msrestazure Credentials\n object`\n \"\"\"\n\n def __init__(self, credentials, **kwargs):\n\n if credentials is None:\n raise ValueError(\"Parameter 'credentials' must not be None.\")\n\n super(KeyVaultClientConfiguration, self).__init__(**kwargs)\n self._configure(**kwargs)\n\n self.user_agent_policy.add_user_agent('azsdk-python-azure-keyvault/{}'.format(VERSION))\n self.generate_client_request_id = True\n self.accept_language = None\n\n self.credentials = credentials\n\n def _configure(self, **kwargs):\n self.connection = ConnectionConfiguration(**kwargs)\n self.user_agent_policy = policies.UserAgentPolicy(**kwargs)\n self.headers_policy = policies.HeadersPolicy(**kwargs)\n self.proxy_policy = policies.ProxyPolicy(**kwargs)\n self.logging_policy = policies.NetworkTraceLoggingPolicy(**kwargs)\n self.retry_policy = policies.AsyncRetryPolicy(**kwargs)\n self.redirect_policy = policies.AsyncRedirectPolicy(**kwargs)\n","sub_path":"sdk/keyvault/azure-security-keyvault/azure/security/keyvault/_generated/v2016_10_01/aio/_configuration_async.py","file_name":"_configuration_async.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"584056380","text":"from flask import Flask, render_template\n# from flask_datepicker import datepicker\n# Some junk to solve loading module path from parent dir\nimport sys\nimport os\nspliter = '\\\\' if os.name == 'nt' else '/'\nsys.path.append(\n spliter.join(\n os.getcwd().split(\n spliter\n )[:-1]\n )\n)\n# End of junk\nfrom flask_fontpicker import fontpicker\n\napp = Flask(__name__, template_folder='.')\nl = [\n 'https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css',\n 'https://code.jquery.com/ui/1.12.1/jquery-ui.min.js',\n 'https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js',\n 'https://www.jqueryscript.net/demo/Google-Web-Font-Picker-Plugin-With-jQuery-And-jQuery-UI-Webfont-selector/webfont.select.js',\n 'https://www.jqueryscript.net/demo/Google-Web-Font-Picker-Plugin-With-jQuery-And-jQuery-UI-Webfont-selector/webfont.select.css'\n]\nlf = []\nfor ll in l:\n lf.append('static/' + ll.split('/')[-1:][0])\nfontpicker(app, local=lf)\n\n\n@app.route('/')\ndef root():\n return render_template('index.html')\n\n\napp.run(debug=True, port=4000)\n","sub_path":"testing_example/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"225132616","text":"from enum import Enum\nfrom torch import nn\n\nfrom . import deeplab\n\n\nclass Supported(Enum):\n DeepLabV3_ResNet101 = 'deeplabv3_resnet101'\n\n\nfrom semseg.device import Device\n\n\ndef build(name: str, device: Device):\n if name == Supported.DeepLabV3_ResNet101.value:\n model: nn.Module = deeplab.DeepLabV3_ResNet101()\n else:\n msg = str(\n \"\\n================\\n\"\n \"NOT Support Error:\\n\"\n f\" Given: \\n\\t{name}\\n\"\n \" Only the following networks\\n\"\n )\n for net_name in Supported:\n msg += f\"\\t{net_name.value}\\n\"\n raise ValueError(msg)\n\n model = model.to(device.get())\n if device.N_gpu >= 2:\n model = nn.DataParallel(model)\n\n return model\n","sub_path":"semseg/networks/segmentation/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"398369735","text":"import AutoSummary as ausu\n\ncontent = 'issue1.txt' \nwith open(content, 'r', encoding='utf8') as f: #讀取原始文章\n text = f.read()\n\nstops = []\nwith open('dictionary/stopWord_summar.txt','r', encoding='utf8') as f: #停用詞庫\n for line in f.readlines():\n stops.append(line.strip())\n\nsentences,indexs = ausu.split_sentence(text) #按標點分割句子\ntfidf = ausu.get_tfidf_matrix(sentences,stops) #移除停用詞並轉換為矩陣\nword_weight = ausu.get_sentence_with_words_weight(tfidf) #計算句子關鍵詞權重\nposi_weight = ausu.get_sentence_with_position_weight(sentences) #計算位置權重\nscores = ausu.get_similarity_weight(tfidf) #計算相似度權重\nsort_weight = ausu.ranking_base_on_weigth(word_weight, posi_weight, scores, feature_weight = [1,1,1]) #按句子權重排序\nsummar = ausu.get_summarization(indexs,sort_weight,topK_ratio = 0.1) #取得摘要\nprint('原文:\\n', text)\nprint('==========================================================')\nprint('摘要:\\n',summar)\n ","sub_path":"NLP/Chinese_Jieba/summary1.py","file_name":"summary1.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"651262732","text":"from . import languageUtils\nfrom . import features\nfrom tqdm import tqdm\nimport nltk\nimport sys\nimport getopt\nimport json\nimport time\n# from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n# import pandas as pd\nfrom pprint import pprint\n\n# This implements the NLP pipeline\n\ndef main(argv):\n\n # Usage\n try:\n opts, args = getopt.getopt(argv,\"hi:j:a:c:\",[\"dbfile=\", \"jsonString=\", \"asin=\", \"count=\"])\n except getopt.GetoptError:\n print ('insights.py -i -j -a -c ')\n sys.exit(2)\n\n # File with the reviews DB\n file = \"\"\n js = \"\"\n asin = \"\"\n count = 0\n count_a = 0\n # Strings with reviews\n reviews_str = \"\"\n reviews_pos_str = \"\"\n reviews_neg_str = \"\"\n\n for opt, arg in opts:\n if opt == '-h':\n print ('insights.py -i -j -a ')\n sys.exit()\n elif opt in (\"-i\", \"--dbfile\"):\n file = arg\n elif opt in (\"-j\", \"--jsonString\"):\n js = arg\n elif opt in (\"-a\", \"--asin\"):\n asin = arg\n elif opt in (\"-c\", \"--count\"):\n count = int(arg)\n\n # ASIN corresponding to the Iron Skillet\n # asin = ['B00006JSUA']\n\n # if asin and count, we load all reviews from the DB and filter while creating a string\n if asin and count:\n count_a = count\n count = 0\n\n # Load reviews to a dictionary\n if file:\n print('loading reviews from: ' + file)\n file_d = features.loadFromDb(file, count)\n # print(len(file_d))\n # print(file_d[0])\n elif js:\n print('loading reviews from the JSON String')\n file_d = features.loadFromJsonString(js, count)\n # print(len(file_d))\n # print(file_d[0])\n else:\n file = '/Users/gkhanna/Downloads/reviews_Home_and_Kitchen_5.json'\n print('loading reviews from: ' + file)\n file_d = features.loadFromDb(file, count)\n # print(len(file_d))\n # print(file_d[0])\n\n # Extract all reviews into lists\n reviews_sent, reviews_pos_sent, reviews_neg_sent = features.loadTolistsAndClassify(file_d, filter_l = asin,\n count = count_a )\n # print(len(reviews_str))\n\n # Convert to strings\n reviews_str = features.loadToString(reviews_sent)\n reviews_pos_str = features.loadToString(reviews_pos_sent)\n reviews_neg_str = features.loadToString(reviews_neg_sent)\n\n\n # Summarize all strings\n # Let the algorithm decide the size of the summary\n ratio = 0.5\n reviews_str = features.summarizeString(reviews_str, ratio)\n reviews_pos_str = features.summarizeString(reviews_pos_str, ratio)\n reviews_neg_str = features.summarizeString(reviews_neg_str, ratio)\n\n\n # Strings to sentences\n sent_full_review = features.stringToSentences(reviews_str)\n sent_pos_review = features.stringToSentences(reviews_pos_str)\n sent_neg_review = features.stringToSentences(reviews_neg_str)\n # print(sent_full_review[0])\n\n # Time to remove all the stop words\n # Before tokenization\n\n sent_full_review_clean = []\n for sentence in tqdm(sent_full_review):\n sent_full_review_clean.append(languageUtils.clean(sentence, remove_stopwords=True))\n\n sent_pos_review_clean = []\n for sentence in tqdm(sent_pos_review):\n sent_pos_review_clean.append(languageUtils.clean(sentence, remove_stopwords=True))\n\n sent_neg_review_clean = []\n for sentence in tqdm(sent_neg_review):\n sent_neg_review_clean.append(languageUtils.clean(sentence, remove_stopwords=True))\n\n print(\"Cleaned : \" + str(len(sent_full_review_clean)) + \" all sentences\")\n print(\"Cleaned : \" + str(len(sent_pos_review_clean)) + \" positive sentences\")\n print(\"Cleaned : \" + str(len(sent_neg_review_clean)) + \" negative sentences\")\n\n\n # Getting the most relevant items from the reviews\n items = []\n rules = []\n minSupport = .1\n minConfidence = .6\n\n items, rules = languageUtils.getItems(sent_full_review_clean, minSupport, minConfidence)\n print('Found ' + str(len(items)) + ' significant items/nouns from the reviews')\n print(items)\n\n # # Good time to TFIDF\n # # On clean sentences\n # vectorizer_pos = TfidfVectorizer(ngram_range=(2,3))\n # tf_pos = vectorizer_pos.fit_transform(sent_pos_review_clean)\n # feature_names_pos = vectorizer_pos.get_feature_names()\n # phrase_scores_pos = vectorizer_pos.idf_\n # names_scores_df_pos = pd.DataFrame({'feature_names':feature_names_pos})\n # names_scores_df_pos['phrase_scores'] = pd.DataFrame(phrase_scores_pos)\n # print('TFIDF Data Frame size: ' + str(names_scores_df_pos.size) + ' For positive sentences')\n #\n # vectorizer_neg = TfidfVectorizer(ngram_range=(2,3))\n # tf_neg = vectorizer_neg.fit_transform(sent_neg_review_clean)\n # feature_names_neg = vectorizer_neg.get_feature_names()\n # phrase_scores_neg = vectorizer_neg.idf_\n # names_scores_df_neg = pd.DataFrame({'feature_names':feature_names_neg})\n # names_scores_df_neg['phrase_scores'] = pd.DataFrame(phrase_scores_neg)\n # print('TFIDF Data Frame size: ' + str(names_scores_df_neg.size) + ' For negative sentences')\n\n # Patterns that we want to extract\n # We think these are the ones that contain features\n feature_patterns = r\"\"\"\n P1:{}\n P2:{}\n P3:{}\n P4:{}\n P5:{}\n P6:{}\n P7:{}\n P8:{}\n \"\"\"\n\n extracted_pos = []\n extracted_neg = []\n extracted_neutral = []\n\n positive_review = []\n negative_review = []\n neutral_review = []\n\n # extracted_neutral, extracted_pos, extracted_neg = features.extractFeaturePhrases(sent_pos_review, sent_neg_review, feature_patterns, items)\n extracted_neutral, extracted_pos, extracted_neg, neutral_review, positive_review, negative_review = features.extractFeaturePhrasesStrict(sent_pos_review, sent_neg_review, feature_patterns, items)\n\n # Convert all phrases to real words\n extracted_pos_real = languageUtils.getRealWordsAll(extracted_pos)\n extracted_neg_real = languageUtils.getRealWordsAll(extracted_neg)\n\n\n # # Frequency distribution\n # freqdist_pos = nltk.FreqDist(word for word in extracted_pos_real)\n # most_common_pos = freqdist_pos.most_common()\n # freqdist_neg = nltk.FreqDist(word for word in extracted_neg_real)\n # most_common_neg = freqdist_neg.most_common()\n\n # Frequency distribution\n freqdist_pos = nltk.FreqDist(word for word in extracted_pos)\n most_common_pos = freqdist_pos.most_common(20)\n print('Most common RAW phrases from the positive reviews: ')\n pprint(most_common_pos)\n\n # if there's one entry with freq > 1, remove others with freq == 1\n if freqdist_pos[freqdist_pos.max()] > 1:\n most_common_pos = [t for t in most_common_pos if t[1] > 1]\n\n # print('Most common RAW phrases from the positive reviews: ')\n # pprint(most_common_pos)\n\n freqdist_neg = nltk.FreqDist(word for word in extracted_neg)\n most_common_neg = freqdist_neg.most_common(20)\n print('Most common RAW phrases from the negative reviews: ')\n pprint(most_common_neg)\n\n if freqdist_neg[freqdist_neg.max()] > 1:\n most_common_neg = [t for t in most_common_neg if t[1] > 1]\n\n # print('Most common RAW phrases from the negative reviews: ')\n # pprint(most_common_neg)\n\n # Convert most common phrases to real words\n most_common_pos_real = languageUtils.getRealWords(most_common_pos)\n print('Most common phrases from the positive reviews: ')\n pprint(most_common_pos_real)\n most_common_neg_real = languageUtils.getRealWords(most_common_neg)\n print('Most common phrases from the negative reviews: ')\n pprint(most_common_neg_real)\n\n # # bi-gram and tri-gram features that are also our extracted phrases\n # extracted_df_pos = names_scores_df_pos[names_scores_df_pos.feature_names.isin(extracted_pos_real)]\n # # print(extracted_df_pos.size)\n # print('Reduced TFIDF Data Frame size: ' + str(extracted_df_pos.size) + ' For positive sentences')\n # extracted_df_pos['freq'] = extracted_df_pos.apply(lambda row: freqdist_pos[row.feature_names], axis=1)\n #\n # extracted_df_neg = names_scores_df_neg[names_scores_df_neg.feature_names.isin(extracted_neg_real)]\n # # print(extracted_df_neg.size)\n # print('Reduced TFIDF Data Frame size: ' + str(extracted_df_neg.size) + ' For negative sentences')\n # extracted_df_neg['freq'] = extracted_df_neg.apply(lambda row: freqdist_neg[row.feature_names], axis=1)\n\n # Sort the items by support\n items.sort(key=lambda tup: tup[1], reverse=True)\n print('Sorted significant nouns/items list: ')\n print(items)\n\n # Latest time in a string\n timestr = time.strftime(\"%Y%m%d-%H%M%S\")\n # Outputfile\n print(\"Files created at: \" + timestr)\n output_file_pos = \"o_\" + \"pos_\" + timestr + \".json\"\n output_file_neg = \"o_\" + \"neg_\" + timestr + \".json\"\n\n # featuresAndContext(item_arr, opinion_phrases, sentence_arr, phrase_count, sentence_count )\n # Getting sentences with the positive phrases\n out_json_s_pos = features.featuresAndContext(items, most_common_pos_real, positive_review, 10, 10)\n with open(output_file_pos, 'w') as jf:\n jf.write(out_json_s_pos)\n print(\"Positive phrases written to: \" + output_file_pos)\n\n # Getting sentences with the negative phrases\n out_json_s_neg = features.featuresAndContext(items, most_common_neg_real, negative_review, 10, 10)\n with open(output_file_neg, 'w') as jfn:\n jfn.write(out_json_s_neg)\n print(\"Negative phrases written to: \" + output_file_neg)\n\n return out_json_s_pos, out_json_s_neg\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"app/ai/insights/insights.py","file_name":"insights.py","file_ext":"py","file_size_in_byte":9813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"308794982","text":"import csv\nimport datetime\nimport pandas as pd\nimport joblib\nfrom lightgbm import LGBMClassifier\nfrom sklearn.metrics import classification_report\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom skopt import BayesSearchCV\nfrom skopt.callbacks import DeltaXStopper\nfrom data_process_v7 import processing\n\ndef predict(clf2, test_set):\n uid = pd.DataFrame()\n # test_set = processing(trainSpan=(1, 30), label=False)\n uid[\"user_id\"] = test_set[\"user_id\"]\n test_set = test_set.drop(labels=[\"user_id\"], axis=1)\n print(\"begin to make predictions\")\n res = clf2.predict_proba(test_set.values)\n uid[\"proba1\"] = pd.Series(res[:, 1])\n uid[\"score\"] = uid.groupby(by=[\"user_id\"])[\"proba1\"].transform(lambda x: sum(x) / float(len(x)))\n uid.drop_duplicates(subset=[\"user_id\"],inplace=True)\n uid.sort_values(by=[\"score\"],axis=0,ascending=False,inplace=True)\n str_time = str(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\n uid_file = \"result/uid_\" + str_time + \".csv\"\n uid.to_csv(uid_file,header=True,index=False)\n active_users = uid.loc[uid[\"score\"]>0.5][\"user_id\"].unique().tolist()\n print(len(active_users))\n print(active_users)\n str_time = str(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\"))\n submission_file = \"result/submission_lgb_\" + str_time + \".csv\"\n with open(submission_file, \"a\", newline=\"\") as f:\n writer = csv.writer(f)\n for i in active_users:\n writer.writerow([i])\n# using this module ,one needs to deconstruct some of the features in data_process\ndef run():\n use_feature = [\n \"user_id\",\"label\",\n \"register_day_type_rate\",\n \"register_day_type_ratio\",\n \"register_day_device_ratio\",\n \"register_type_ratio\",\n \"register_type_device\",\n \"register_type_device_ratio\",\n \"device_type_register_ratio\",\n \"register_day_register_type_device_ratio\",\n\n \"user_app_launch_rate\",\n \"user_app_launch_ratio\",\n \"user_app_launch_gap\",\n \"user_app_launch_var\",\n\n \"user_app_launch_count_b1\",\n \"user_app_launch_count_b2\",\n \"user_app_launch_count_b3\",\n \"user_app_launch_count_b4\",\n \"user_app_launch_count_b5\",\n \"user_app_launch_count_b6\",\n \"user_app_launch_count_b7\",\n \"user_app_launch_count_b8\",\n \"user_app_launch_count_b9\",\n \"user_app_launch_count_b10\",\n\n \"user_app_launch_count_rb1\",\n \"user_app_launch_count_rb2\",\n \"user_app_launch_count_rb3\",\n \"user_app_launch_count_rb4\",\n \"user_app_launch_count_rb5\",\n \"user_app_launch_count_rb6\",\n \"user_app_launch_count_rb7\",\n \"user_app_launch_count_rb8\",\n \"user_app_launch_count_rb9\",\n \"user_app_launch_count_rb10\",\n\n \"user_app_launch_count_f1\",\n \"user_app_launch_count_f2\",\n \"user_app_launch_count_f3\",\n \"user_app_launch_count_f4\",\n \"user_app_launch_count_f5\",\n \"user_app_launch_count_f6\",\n \"user_app_launch_count_f7\",\n\n \"user_app_launch_count_rf1\",\n \"user_app_launch_count_rf2\",\n \"user_app_launch_count_rf3\",\n \"user_app_launch_count_rf4\",\n \"user_app_launch_count_rf5\",\n \"user_app_launch_count_rf6\",\n \"user_app_launch_count_rf7\",\n\n \"user_video_create_rate\",\n \"user_video_create_ratio\",\n \"user_video_create_day\",\n \"user_video_create_day_ratio\",\n \"user_video_create_frequency\",\n \"user_video_create_gap\",\n \"user_video_create_day_var\",\n \"user_video_create_var\",\n\n \"user_video_create_count_b1\",\n \"user_video_create_count_b2\",\n \"user_video_create_count_b3\",\n \"user_video_create_count_b4\",\n \"user_video_create_count_b5\",\n \"user_video_create_count_b6\",\n \"user_video_create_count_b7\",\n\n \"user_video_create_count_rb1\",\n \"user_video_create_count_rb2\",\n \"user_video_create_count_rb3\",\n \"user_video_create_count_rb4\",\n \"user_video_create_count_rb5\",\n \"user_video_create_count_rb6\",\n \"user_video_create_count_rb7\",\n\n \"user_video_create_count_f1\",\n \"user_video_create_count_f2\",\n \"user_video_create_count_f3\",\n \"user_video_create_count_f4\",\n \"user_video_create_count_f5\",\n\n \"user_video_create_count_rf1\",\n \"user_video_create_count_rf2\",\n \"user_video_create_count_rf3\",\n \"user_video_create_count_rf4\",\n \"user_video_create_count_rf5\",\n\n \"user_activity_rate\",\n \"user_activity_ratio\",\n \"user_activity_var\",\n \"user_activity_day_rate\",\n \"user_activity_day_ratio\",\n \"user_activity_frequency\",\n \"user_activity_gap\",\n \"user_activity_day_var\",\n \"user_page_num\",\n \"user_page_day_ratio\",\n \"user_video_num\",\n \"user_video_num_ratio\",\n \"user_author_num\",\n \"user_author_num_ratio\",\n \"user_action_type_num\",\n\n \"user_activity_count_b1\",\n \"user_activity_count_b2\",\n \"user_activity_count_b3\",\n \"user_activity_count_b4\",\n \"user_activity_count_b5\",\n \"user_activity_count_b6\",\n \"user_activity_count_b7\",\n \"user_activity_count_b8\",\n \"user_activity_count_b9\",\n \"user_activity_count_b10\",\n\n \"user_activity_count_rb1\",\n \"user_activity_count_rb2\",\n \"user_activity_count_rb3\",\n \"user_activity_count_rb4\",\n \"user_activity_count_rb5\",\n \"user_activity_count_rb6\",\n \"user_activity_count_rb7\",\n \"user_activity_count_rb8\",\n \"user_activity_count_rb9\",\n \"user_activity_count_rb10\",\n\n \"user_activity_count_f1\",\n \"user_activity_count_f2\",\n \"user_activity_count_f3\",\n \"user_activity_count_f4\",\n \"user_activity_count_f5\",\n \"user_activity_count_f6\",\n \"user_activity_count_f7\",\n\n \"user_activity_count_rf1\",\n \"user_activity_count_rf2\",\n \"user_activity_count_rf3\",\n \"user_activity_count_rf4\",\n \"user_activity_count_rf5\",\n \"user_activity_count_rf6\",\n \"user_activity_count_rf7\"\n ]\n print(\"begin to load the trainset1\")\n # train_set1 = processing(trainSpan=(1,22),label=True)\n # train_set1.to_csv(\"data/training_ld1-22.csv\", header=True, index=False)\n train_set1 = pd.read_csv(\"data/training_eld1-22.csv\", header=0, index_col=None, usecols=use_feature)\n print(train_set1.describe())\n print(\"begin to load the trainset2\")\n # train_set2 = processing(trainSpan=(1,20),label=True)\n # train_set2.to_csv(\"data/training_ld1-20.csv\", header=True, index=False)\n train_set2 = pd.read_csv(\"data/training_eld1-20.csv\", header=0, index_col=None, usecols=use_feature)\n print(train_set2.describe())\n print(\"begin to load the trainset3\")\n # train_set3 = processing(trainSpan=(1,18),label=True)\n # train_set3.to_csv(\"data/training_ld1-18.csv\", header=True, index=False)\n # train_set3 = pd.read_csv(\"data/training_ld1-17.csv\", header=0, index_col=None, usecols=use_feature)\n # train_set3 = pd.read_csv(\"data/training_eld1-18.csv\", header=0, index_col=None, usecols=use_feature)\n # print(train_set3.describe())\n print(\"begin to load the trainset4\")\n # train_set4 = processing(trainSpan=(1,19),label=True)\n # train_set4.to_csv(\"data/training_ld1-19.csv\", header=True, index=False)\n # train_set4 = pd.read_csv(\"data/training_eld1-19.csv\", header=0, index_col=None, usecols=use_feature)\n # print(train_set4.describe())\n print(\"begin to load the trainset5\")\n # train_set5 = processing(trainSpan=(1,21),label=True)\n # train_set5.to_csv(\"data/training_ld1-21.csv\", header=True, index=False)\n train_set5 = pd.read_csv(\"data/training_eld1-21.csv\", header=0, index_col=None, usecols=use_feature)\n print(train_set5.describe())\n print(\"begin to load the validation set\")\n # val_set = processing(trainSpan=(1,23),label=True)\n # val_set.to_csv(\"data/training_ld1-23.csv\", header=True, index=False)\n val_set = pd.read_csv(\"data/training_eld1-23.csv\", header=0, index_col=None, usecols=use_feature)\n # val_set = pd.read_csv(\"data/training_ld1-21.csv\", header=0, index_col=None, usecols=use_feature)\n print(val_set.describe())\n train_set = pd.concat([train_set1,train_set2,train_set5 ], axis=0)\n # train_set = pd.concat([ train_set2, train_set3, train_set4, train_set5], axis=0)\n # train_set = pd.concat([ train_set5], axis=0)\n ds = train_set.describe()\n print(ds)\n # train_set = pd.concat([train_set1], axis=0)\n # train_set = pd.concat([train_set1,train_set2],axis=0)\n # train_set.to_csv(\"data/training_lm1-11_12-23.csv\", header=True, index=False)\n # train_set = pd.read_csv(\"data/training_m1-23.csv\", header=0, index_col=None)\n # del train_set1,train_set2\n # gc.collect()\n print(train_set.describe())\n keep_feature = list(set(train_set.columns.values.tolist()) - set([\"user_id\", \"label\"]))\n\n print(\"begin to drop the duplicates\")\n train_set.drop_duplicates(subset=keep_feature, inplace=True)\n val_set.drop_duplicates(subset=keep_feature,inplace=True)\n print(train_set.describe())\n print(val_set.describe())\n train_label = train_set[\"label\"]\n val_label = val_set[\"label\"]\n train_set = train_set.drop(labels=[\"label\", \"user_id\"], axis=1)\n val_set = val_set.drop(labels=[\"label\",\"user_id\"], axis=1)\n # keep_feature = []\n # train_x, val_x,train_y,val_y = train_test_split(train_set.values,train_label.values,test_size=0.25,random_state=42,shuffle=False)\n # train_set = train_set[keep_feature]\n # feature_names = train_set.columns\n for fea in keep_feature:\n train_set[fea] = (train_set[fea]-train_set[fea].min())/(train_set[fea].max()-train_set[fea].min())\n val_set[fea] = (val_set[fea]-val_set[fea].min())/(val_set[fea].max()-val_set[fea].min())\n # train_x, val_set,train_label,val_label = train_test_split(train_set.values,train_label.values,test_size=0.25,random_state=42,shuffle=False)\n # train_x, val_x,train_y,val_y = train_test_split(train_set.values,train_label.values,test_size=0.33,random_state=42,shuffle=True)\n print(\"begin to make prediction with plain features and without tuning parameters\")\n\n initial_params = {\n \"colsample_bytree\": 0.9310971383709499,\n \"learning_rate\": 0.01952000072830969,\n \"max_bin\": 215,\n # \"max_depth\":7,\n \"min_child_samples\": 64,\n \"min_child_weight\":0.001371129038729715,\n \"min_split_gain\": 0.0017264713898581718,\n \"n_estimators\":231,\n \"num_leaves\": 10,\n \"reg_alpha\": 673.9667614029386,\n \"reg_lambda\": 0.07753855735553884,\n \"scale_pos_weight\": 0.9914246775102074,\n \"subsample\": 0.9022953065931087,\n }\n # train_data = lightgbm.Dataset(train_set.values, label=train_label.values, feature_name=list(train_set.columns))\n\n scoring = {'f1': \"f1\"}\n clf1 = GridSearchCV(LGBMClassifier(),\n param_grid={\"n_estimators\":[800,1000,1200],\"num_leaves\": [4,6,8],\"boosting_type\":[\"dart\"]},\n scoring=scoring, cv=4, refit='f1',n_jobs=-1,verbose=1)\n clf1.fit(train_set.values, train_label.values)\n # clf1.fit(train_set.values, train_label.values,eval_set=(val_set.values,val_label.values),early_stopping_rounds=30)\n # cv_results = cv(initial_params,train_data,num_boost_round=800,nfold=4,early_stopping_rounds=30,verbose_eval=True)\n # bst = lgb.cv(initial_params, train_data, num_boost_round=1000, nfold=3, early_stopping_rounds=30)\n bs = clf1.best_score_\n print(bs)\n bp = clf1.best_params_\n print(bp)\n print(\"load the test dataset\")\n yhat = clf1.predict(val_set.values)\n print(classification_report(y_pred=yhat, y_true=val_label.values,digits=4))\n\n str_time = str(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M\"))\n print(\"begin to get important features\")\n feature_names = train_set.columns\n feature_importances = clf1.best_estimator_.feature_importances_\n # print(feature_importances)\n # print(feature_names)\n feature_score_name = sorted(zip(feature_importances, feature_names), reverse=True)\n for score, name in feature_score_name:\n print('{}: {}'.format(name, score))\n sorted_feature_name = [name for score, name in feature_score_name]\n print(sorted_feature_name)\n\n with open(\"kuaishou_stats.csv\", 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([\"feature importance of lr for kuaishou \", str_time])\n writer.writerow([\"best score\", bs, \"best params\"])\n for key, value in bp.items():\n writer.writerow([key, value])\n # writer.writerow(eval_metrics)\n feature_score_name = sorted(zip(feature_importances, feature_names), reverse=True)\n for score, name in feature_score_name:\n # print('{}: {}'.format(name, score))\n writer.writerow([name, score])\n sorted_feature_name = [name for score, name in feature_score_name]\n # print(sorted_feature_name)\n #\n clf1 = LGBMClassifier(**bp)\n train_set[\"label\"] = train_label\n val_set[\"label\"] = val_label\n train_set = pd.concat([train_set, val_set], axis=0)\n train_set.drop_duplicates(inplace=True)\n train_label = train_set[\"label\"]\n train_set = train_set.drop(labels=[\"label\"], axis=1)\n clf1.fit(train_set, train_label)\n print(\"load the test dataset\")\n # # test_set = processing(trainSpan=(1, 30), label=False)\n # # test_set.to_csv(\"data/testing_ld1-30.csv\",header=True,index=False)\n test_set = pd.read_csv(\"data/testing_eld1-30.csv\",header=0,index_col=None,usecols=keep_feature+[\"user_id\"])\n for fea in keep_feature:\n test_set[fea] = (test_set[fea]-test_set[fea].min())/(test_set[fea].max()-test_set[fea].min())\n # # test_set = processing(trainSpan=(21, 30), label=False)\n # # test_set.to_csv(\"data/testing_ld21-30.csv\",header=True,index=False)\n # # test_set = pd.read_csv(\"data/testing_ld15-30.csv\",header=0,index_col=None)\n print(\"begin to make prediction\")\n predict(clf1,test_set)\n # str_time = str(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M\"))\n # # model_name = \"lightgbm_\" + str_time + \".pkl\"\n # # joblib.dump(clf1, model_name)\n print(\"begin to tune the parameters\")\n paramsSpace = {\n \"n_estimators\": (200, 800),\n # \"boosting_type\":Categorical([\"dart\", \"rf\",\"gbdt\"]),\n # \"max_depth\": (3, 8),\n # \"max_bin\": (200, 250),\n \"num_leaves\": (3, 12),\n # \"min_child_weight\": (1e-5, 1.0, 'log-uniform'),\n # \"min_child_samples\": (50, 80),\n # \"min_split_gain\": (1e-5, 1.0, 'log-uniform'),\n \"learning_rate\": (1e-4, 0.1, 'log-uniform'),\n \"colsample_bytree\": (0.9, 1.0, 'uniform'),\n \"subsample\": (0.8, 1.0, 'uniform'),\n # 'reg_alpha': (1.0, 1e4, 'log-uniform'),\n # 'reg_lambda': (1e-4, 1.0, 'log-uniform'),\n \"scale_pos_weight\": (0.96, 1.0, 'uniform'),\n }\n def tune_parameter(X, y, clf, params):\n # X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n gs = BayesSearchCV(\n estimator=clf, search_spaces=params,\n # fit_params={\"eval_set\":(val_set.values,val_label.values),\"early_stopping_rounds\":30},\n scoring=\"f1\", n_iter=60,optimizer_kwargs={\"base_estimator\":\"GBRT\"},\n verbose=0, n_jobs=-1, cv=4, refit=True, random_state=1234\n )\n gs.fit(X, y,callback=DeltaXStopper(0.000001))\n best_params = gs.best_params_\n best_score = gs.best_score_\n print(best_params)\n print(best_score)\n str_time = str(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M\"))\n with open(\"kuaishou_stats.csv\", 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([\"the best params for lightgbm: \"])\n for key, value in best_params.items():\n writer.writerow([key, value])\n writer.writerow([\"the best score for lightgbm: \", best_score,str_time])\n return gs\n\n model = LGBMClassifier(**bp)\n clf2 = tune_parameter(train_set.values,train_label.values,model,paramsSpace)\n print(\"parameter tuning over, begin to save the model!\")\n str_time = str(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M\"))\n\n # model_name = \"lightgbm_\" + str_time + \".pkl\"\n # joblib.dump(clf2, model_name)\n\n print(\"begin to process the whole dataset and ready to feed into the fitted model\")\n predict(clf2,test_set)\n # predict(clf2,test_set2)\n str_time = str(datetime.datetime.now().strftime(\"%Y-%m-%d_%H-%M\"))\n print(\"begin to get important features\")\n feature_names = train_set.columns\n feature_importances = clf2.best_estimator_.feature_importances_\n # print(feature_importances)\n # print(feature_names)\n\n with open(\"kuaishou_stats.csv\", 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerow([\"feature importance of lgb for tencent-crt\", str_time])\n # writer.writerow(eval_metrics)\n feature_score_name = sorted(zip(feature_importances, feature_names), reverse=True)\n for score, name in feature_score_name:\n print('{}: {}'.format(name, score))\n writer.writerow([name, score])\n sorted_feature_name = [name for score, name in feature_score_name]\n print(sorted_feature_name)\n\nif __name__==\"__main__\":\n run()","sub_path":"lgbpy/lgb_v10.py","file_name":"lgb_v10.py","file_ext":"py","file_size_in_byte":17386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"491286363","text":"import sys\nimport codecs\n\nfrom ._compat import PY2, text_type\n\n\ndef safecall(func):\n \"\"\"Wraps a function so that it swallows exceptions.\"\"\"\n def wrapper(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except Exception:\n pass\n return wrapper\n\n\ndef is_ascii_encoding(encoding):\n \"\"\"Checks if a given encoding is ascii.\"\"\"\n try:\n return codecs.lookup(encoding).name == 'ascii'\n except LookupError:\n return False\n\n\ndef get_best_encoding(stream):\n \"\"\"Returns the best encoding that should be used for a stream.\"\"\"\n enc = getattr(stream, 'encoding', None)\n if enc is None or is_ascii_encoding(enc):\n return 'utf-8'\n return enc\n\n\ndef make_str(value):\n \"\"\"Converts a value into a valid string.\"\"\"\n if isinstance(value, bytes):\n try:\n return value.decode(sys.getfilesystemencoding())\n except UnicodeError:\n return value.decode('utf-8', 'replace')\n return text_type(value)\n\n\ndef make_default_short_help(help, max_length=45):\n words = help.split()\n total_length = 0\n result = []\n done = False\n\n for word in words:\n if '.' in word:\n word = word.split('.', 1)[0] + '.'\n done = True\n new_length = result and 1 + len(word) or len(word)\n if total_length + new_length > max_length:\n result.append('...')\n done = True\n else:\n if result:\n result.append(' ')\n result.append(word)\n if done:\n break\n total_length += new_length\n\n return ''.join(result)\n","sub_path":"click/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"158842024","text":"from users.models import *\n\n\n# Create your models here.\n\nclass FictionType(models.Model):\n name = models.CharField(max_length=20, verbose_name=\"小说类型\")\n\n\n# class Users(models.Model):\n# sex_type = (\n# (0, '男'),\n# (1, '女'),\n# (2, '保密')\n# )\n# name = models.CharField(max_length=20, unique=True, verbose_name=\"用户账号\")\n# passwd = models.CharField(max_length=20, verbose_name=\"用户密码\")\n# email = models.CharField(max_length=20, unique=True, verbose_name=\"用户邮箱\")\n# phone = models.CharField(max_length=13, unique=True, verbose_name=\"电话\")\n# sex = models.IntegerField(choices=sex_type, default=1)\n# head_img = models.ImageField(upload_to=\"photos\", verbose_name=\"用户头像\")\n# create_time = models.DateTimeField(auto_now_add=True, verbose_name=\"创建时间\")\n# login_time = models.DateTimeField(auto_now=True, verbose_name=\"登录时间\")\n#\n# @property\n# def sex_name(self):\n# return self.sex_type[self.sex][1]\n\n\nclass Fition(models.Model):\n name = models.CharField(max_length=50, unique=True, verbose_name=\"小说名\")\n intro = models.TextField(max_length=200, verbose_name=\"作品简介\")\n cover = models.CharField(max_length=300, verbose_name=\"封面图片\")\n put_time = models.DateTimeField(auto_now_add=True, verbose_name=\"上架时间\")\n click = models.PositiveIntegerField(default=0, verbose_name=\"作品点击数\")\n author = models.CharField(max_length=20, unique=True, verbose_name=\"作者名\")\n fictionType = models.ForeignKey(FictionType, on_delete=models.CASCADE, null=True)\n users = models.ForeignKey(User, on_delete=models.CASCADE, null=True)\n\n def increase_click(self):\n self.click += 1\n self.save(update_fields=['click'])\n\n def __str__(self):\n return self.name\n\n\nclass Chapter(models.Model):\n name = models.CharField(max_length=50, verbose_name='章节名')\n content = models.TextField(verbose_name=\"小说内容\")\n updata_time = models.DateTimeField(auto_now=True, verbose_name=\"章节更新时间\")\n fiction = models.ForeignKey(Fition, on_delete=models.CASCADE)\n\n def __str__(self):\n return self.name\n","sub_path":"qw_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"1456727","text":"#!/usr/bin/env python\n#\n# Copyright 2012, Julius Seporaitis\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n__author__ = \"Julius Seporaitis\"\n__email__ = \"julius@seporaitis.net\"\n__copyright__ = \"Copyright 2012, Julius Seporaitis\"\n__license__ = \"Apache 2.0\"\n__version__ = \"2.0.0\"\n\n#\n# See http://yum.baseurl.org/wiki/WritingYumPlugins for moar info.\n#\n\nimport urllib2\nimport urlparse\nimport time\nimport hashlib\nimport hmac\nimport json\nimport io\nimport posixpath\nimport os\nimport contextlib\n\nfrom yum import config\nfrom yum.plugins import TYPE_CORE, PluginYumExit\nfrom yum.yumRepo import YumRepository\nfrom urlgrabber.grabber import URLGrabError\n\n__all__ = ['requires_api_version', 'plugin_type', 'CONDUIT',\n 'config_hook', 'prereposetup_hook']\n\nrequires_api_version = '2.5'\nplugin_type = (TYPE_CORE,)\n\nCONDUIT = None\n\n\ndef config_hook(conduit):\n config.RepoConf.key_id = config.Option(default=conduit.confString('main', 'aws_access_key_id'))\n config.RepoConf.secret_key = config.Option(default=conduit.confString('main', 'aws_secret_access_key'))\n config.RepoConf.region = config.Option()\n config.RepoConf.baseurl = config.UrlListOption(schemes=('http', 'ftp', 'file', 'https', 's3'))\n\n\ndef prereposetup_hook(conduit):\n \"\"\"Plugin initialization hook. Setup the S3 repositories.\"\"\"\n\n #\n # While s3:// is easier to grasp, it confuses some yum plugins e.g. fastestmirror\n # as they expect to have ftp, http[s] or file urls. So we better switch back to\n # basic schemas.\n #\n # TODO Detect virtual-hosted-style URL & convert to path-style\n #\n # http://{bucket}.s3.amazonaws.com\n # http://{bucket}.s3-{region}.amazonaws.com\n #\n # TODO Detect path-style URL\n #\n # http://s3.amazonaws.com/{bucket}\n # http://s3-{region}.amazonaws.com/{bucket}\n #\n def is_s3_schema(url_or_urls):\n if isinstance(url_or_urls, basestring):\n (schema, _, _, _, _) = urlparse.urlsplit(url_or_urls)\n return schema == 's3'\n else:\n return False\n\n repos = conduit.getRepos()\n for repo in repos.listEnabled():\n if not isinstance(repo, YumRepository):\n continue\n\n if not is_s3_schema(repo.baseurl):\n continue\n\n for attr in ['mirrorlist', 'proxy']:\n if getattr(repo, attr):\n msg = \"%s: Unsupported attribute: %s.\" % (__file__, attr)\n raise PluginYumExit(msg)\n\n new_repo = S3Repository(repo.id,\n baseurl=repo.baseurl,\n key_id=repo.key_id,\n secret_key=repo.secret_key,\n region=repo.region)\n new_repo.name = repo.name\n new_repo.basecachedir = repo.basecachedir\n new_repo.gpgcheck = repo.gpgcheck\n new_repo.gpgkey = repo.gpgkey\n new_repo.enablegroups = repo.enablegroups\n\n if hasattr(repo, 'priority'):\n new_repo.priority = repo.priority\n if hasattr(repo, 'base_persistdir'):\n new_repo.base_persistdir = repo.base_persistdir\n if hasattr(repo, 'metadata_expire'):\n new_repo.metadata_expire = repo.metadata_expire\n if hasattr(repo, 'skip_if_unavailable'):\n new_repo.skip_if_unavailable = repo.skip_if_unavailable\n if hasattr(repo, 'priority'):\n new_repo.priority = repo.priority\n if hasattr(repo, 'keepcache'):\n new_repo.keepcache = repo.keepcache\n\n new_repo.enable()\n repos.delete(repo.id)\n repos.add(new_repo)\n\n\n@contextlib.contextmanager\ndef urlopen(request, *args, **kwargs):\n #\n # 1. Autoclose response\n # 2. Wrap exceptions as URLGrabError so that YumRepository catches it\n #\n try:\n with contextlib.closing(urllib2.urlopen(request, *args, **kwargs)) as response:\n yield response\n except urllib2.HTTPError as e:\n #\n # http://urlgrabber.baseurl.org/help/urlgrabber.grabber.html#URLGrabError\n # 14 - HTTPError (includes .code and .exception attributes)\n #\n url = request.get_full_url()\n new_e = URLGrabError(14, '%s on %s' % (e, url))\n new_e.code = e.code\n new_e.exception = e\n new_e.url = url\n raise new_e\n except urllib2.URLError as e:\n\n #\n # http://urlgrabber.baseurl.org/help/urlgrabber.grabber.html#URLGrabError\n # 4 - IOError on fetch\n #\n url = request.get_full_url()\n new_e = URLGrabError(4, '%s on %s' % (e, url))\n new_e.exception = e\n new_e.url = url\n raise new_e\n\n\nclass S3Repository(YumRepository):\n \"\"\"Repository object for Amazon S3 using IAM Roles.\"\"\"\n\n def __init__(self, repoid, baseurl, key_id=None, secret_key=None, region=None):\n super(S3Repository, self).__init__(repoid)\n\n if isinstance(baseurl, basestring):\n pass\n elif len(baseurl) == 1:\n baseurl = baseurl[0]\n else:\n raise PluginYumExit('s3-iam does\\'t support multiple baseurl\\'s')\n\n if region == 'auto':\n placement = Placement()\n placement.get_availability_zone()\n region = placement.availability_zone\n\n (_, bucket, path, _, _) = urlparse.urlsplit(baseurl)\n if not region or region == 'us-east-1':\n self.baseurl = 'https://s3.amazonaws.com/{bucket}'.format(bucket=bucket)\n self.baseurl = posixpath.join(self.baseurl, path)\n else:\n self.baseurl = 'https://s3-{region}.amazonaws.com/{bucket}'.format(region=region, bucket=bucket)\n self.baseurl = posixpath.join(self.baseurl, path)\n\n self.region = region\n self.key_id = key_id\n self.secret_key = secret_key\n self.grabber = None\n\n @property\n def grabfunc(self):\n raise NotImplementedError(\"grabfunc called, when it shouldn't be!\")\n\n @property\n def grab(self):\n if not self.grabber:\n if self.key_id and self.secret_key:\n creds = AWSCredentials(key_id=self.key_id,\n secret_key=self.secret_key,\n token=None)\n elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY'):\n creds = AWSCredentials(key_id=os.environ.get('AWS_ACCESS_KEY_ID'),\n secret_key=os.environ.get('AWS_SECRET_ACCESS_KEY'),\n token=os.environ.get('AWS_SESSION_TOKEN'))\n else:\n iam = IAMSecurityCredentials()\n creds = iam.get_credentials()\n\n self.grabber = S3Grabber(self.baseurl, creds)\n return self.grabber\n\n\nclass Placement(object):\n def __init__(self):\n self.availability_zone = None\n\n def get_availability_zone(self):\n \"\"\"Read region from AWS metadata store.\"\"\"\n\n request = urllib2.Request(\n urlparse.urljoin(\n \"http://169.254.169.254\",\n \"/latest/meta-data/placement/availability-zone\"\n ))\n\n with urlopen(request) as response:\n self.availability_zone = response.read()[:-1]\n\n\nclass AWSCredentials(object):\n def __init__(self, key_id, secret_key, token=None):\n self.key_id = key_id\n self.secret_key = secret_key\n self.token = token\n\n def sign(self, request, date=None):\n \"\"\"Attach a valid S3 signature to request.\n request - instance of Request\n \"\"\"\n if date is None:\n date = time.strftime(\"%a, %d %b %Y %H:%M:%S GMT\", time.gmtime())\n request.add_header('Date', date)\n\n if self.token:\n request.add_header('x-amz-security-token', self.token)\n\n #\n # http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html\n #\n string_to_sign = (\"{http_verb}\\n\"\n \"{content_md5}\\n\"\n \"{content_type}\\n\"\n \"{date}\\n\"\n \"{canonicalized_amzn_headers}\"\n \"{canonicalized_resource}\").format(\n http_verb=request.get_method(),\n content_md5='',\n content_type='',\n date=request.get_header('Date'),\n canonicalized_amzn_headers='\\n'.join(\n '%s:%s' for k_v in request.headers.items() if k_v[0].startswith('x-amz-')),\n canonicalized_resource=request.get_selector() # We use path-style URL so bucket is already in selector\n )\n digest = hmac.new(\n key=str(self.secret_key),\n msg=string_to_sign,\n digestmod=hashlib.sha1).digest()\n signature = digest.encode('base64').strip()\n\n request.add_header('Authorization', \"AWS {aws_access_key_id}:{signature}\".format(\n aws_access_key_id=self.key_id,\n signature=signature))\n\n\nclass IAMSecurityCredentials(object):\n def _get_iam_role(self):\n \"\"\"Read IAM role from AWS metadata store.\"\"\"\n request = urllib2.Request(\n urlparse.urljoin(\n \"http://169.254.169.254\",\n \"/latest/meta-data/iam/security-credentials/\"\n ))\n\n with urlopen(request) as response:\n iam_role = response.read()\n return iam_role\n\n def get_credentials(self):\n \"\"\"Read IAM credentials from AWS metadata store.\"\"\"\n iam_role = self._get_iam_role()\n url = urlparse.urljoin(\n urlparse.urljoin(\n \"http://169.254.169.254/\",\n \"latest/meta-data/iam/security-credentials/\",\n ), iam_role)\n request = urllib2.Request(url)\n\n with urlopen(request) as response:\n data = json.loads(response.read())\n\n return AWSCredentials(\n key_id=data['AccessKeyId'],\n secret_key=data['SecretAccessKey'],\n token=data['Token']\n )\n\n\nclass S3Grabber(object):\n def __init__(self, baseurl, credentials):\n \"\"\"Initialize file grabber.\"\"\"\n\n self.baseurl = baseurl\n\n # Ensure urljoin doesn't ignore base path:\n if not self.baseurl.endswith('/'):\n self.baseurl += '/'\n\n self.credentials = credentials\n\n def _signed_request(self, path, date=None):\n url = urlparse.urljoin(self.baseurl, urllib2.quote(path))\n request = urllib2.Request(url)\n self.credentials.sign(request, date=date)\n return request\n\n def urlgrab(self, url, filename=None, **kwargs):\n \"\"\"urlgrab(url) copy the file to the local filesystem.\"\"\"\n\n if filename is None:\n (scheme, netloc, path, query, frag) = urlparse.urlsplit(url)\n filename = posixpath.basename(urllib2.unquote(path))\n\n request = self._signed_request(url)\n with urlopen(request) as response:\n with open(filename, 'w+') as out:\n buff = response.read(io.DEFAULT_BUFFER_SIZE)\n while buff:\n out.write(buff)\n buff = response.read(io.DEFAULT_BUFFER_SIZE)\n\n return filename\n\n def urlopen(self, url, **kwargs):\n \"\"\"urlopen(url) open the remote file and return a file object.\"\"\"\n return urllib2.urlopen(self._signed_request(url))\n\n def urlread(self, url, limit=None, **kwargs):\n \"\"\"urlread(url) return the contents of the file as a string.\"\"\"\n return urllib2.urlopen(self._signed_request(url)).read()\n","sub_path":"s3-iam.py","file_name":"s3-iam.py","file_ext":"py","file_size_in_byte":11997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"574634498","text":"'''\nApplication : Envision\nFile name : world.py\nAuthors : Jacob Summerville and Safwan Elmadani\nDescription : This file contains the main node of the .world file\n'''\n\n# Copyright (c) April 26, 2021 Jacob Summerville and Safwan Elmadani\n# All rights reserved.\n#\n# The license below extends only to copyright in the software and shall\n# not be construed as granting a license to any other intellectual\n# property including but not limited to intellectual property relating\n# to a hardware implementation of the functionality of the software\n# licensed hereunder. You may use the software subject to the license\n# terms below provided that you ensure that this notice is replicated\n# unmodified and in its entirety in all distributions of the software,\n# modified or unmodified, in source code or in binary form.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met: redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer;\n# redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution;\n# neither the name of the copyright holders nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom xml.dom import minidom \nfrom pathlib import Path\nimport os, sys, logging\n\nfrom src.config.settings import settings, config\n\nfrom src.nodehandler import node_handler\nfrom src.model import Model\nfrom src.defaultscene import DefaultScene\n \nclass World:\n \"\"\" This class is the top level for the world file creation \"\"\" \n\n def __init__(self, world_name):\n self.world_name = world_name\n self.CreateXML()\n self.Nodes()\n self.Scene()\n self.Models()\n self.FormatXML()\n self.SaveWorld()\n \n def CreateXML(self):\n \"\"\" Creates the world (XML) file \"\"\"\n\n logging.info('Creating World File')\n\n self.root = minidom.Document() \n sdf = self.root.createElement('sdf') \n sdf.setAttribute('version', '1.7')\n self.root.appendChild(sdf) \n \n self.world = self.root.createElement('world') \n self.world.setAttribute('name', 'default')\n sdf.appendChild(self.world) \n\n # Set the global variables\n config.root = self.root\n config.world = self.world\n\n def Nodes(self):\n \"\"\" Add the top level nodes \"\"\"\n\n logging.info('')\n logging.info('')\n logging.info('--- Adding Top Level Nodes ---')\n\n #node_handler.Light()\n node_handler.Gui()\n node_handler.Physics()\n node_handler.Scene()\n node_handler.Coordinates()\n\n def Scene(self):\n \"\"\" Setup the user requested default scene \"\"\"\n\n logging.info('')\n logging.info('')\n logging.info('--- Setting Default Scene ---')\n\n DefaultScene()\n\n def Models(self):\n \"\"\" Add the user requested models \"\"\"\n\n logging.info('')\n logging.info('')\n logging.info('--- Adding Requested Models ---')\n\n model = Model()\n\n for user_model in settings['Models']:\n if 'pose' in user_model.keys() and 'name' in user_model.keys():\n model.AddModel(model=user_model['model'], pose=user_model['pose'], name=user_model['name'])\n elif 'pose' in user_model.keys():\n model.AddModel(model=user_model['model'], pose=user_model['pose'])\n elif 'name' in user_model.keys():\n model.AddModel(model=user_model['model'], name=user_model['name'])\n else:\n model.AddModel(model=user_model['model'])\n\n def FormatXML(self):\n \"\"\" Format the world file output \"\"\"\n self.xml_str = self.root.toprettyxml(indent =\"\\t\", newl=\"\\n\") \n \n def SaveWorld(self):\n \"\"\" Save the world file \"\"\"\n\n logging.info('')\n logging.info('')\n logging.info('Saving World file')\n\n absPath = Path(__file__).parent.parent\n with open(str(absPath) +'/worlds/' + self.world_name, \"w\") as f: \n f.write(self.xml_str) \n\n\nif __name__ == '__main__':\n\n env_world = World('test.world')","sub_path":"src/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":5194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"324521100","text":"\"\"\"This sample program will use the kel103 to test a batteries capacity and \nshow this information in matplotlib. This method is an aproximation and its resolution\ncan be increase with sampling rate. \n\"\"\"\nimport socket\nimport time\nimport re\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom korad import kel103\n\n#test proporties\ncutOffVoltage = 2.0\ndischargeRate = 5.0\n\n# setup the device (the IP of your ethernet/wifi interface, the IP of the Korad device)\nkel = kel103.kel103(\"192.168.8.126\", \"192.168.8.128\", 18190)\nkel.checkDevice()\n\n# a quick battery test\nkel.setOutput(False) \nvoltage = kel.measureVolt()\nkel.setCurrent(dischargeRate)\nvoltageData = []\ntimeData = []\ncurrent = 0\ncapacity = 0\nkel.setOutput(True)\n\n# run the test\nstartTime = time.time()\nwhile voltage > cutOffVoltage:\n timeData.append(time.time()- startTime)\n voltage = kel.measureVolt()\n voltageData.append(voltage)\n\n #solve the current stuff as a running acumulation\n current = kel.measureCurrent()\n capacity = ((startTime - time.time())/60/60) * current\n\n print (\"Voltage: \" + str(voltage) + \" V DC, Capacity: \" + str(capacity) + \" Ah\")\n time.sleep(0.5)\n\n# disable the output\nkel.setOutput(False)\nkel.endComm()\n\n# plot the finished data\nfig, ax = plt.subplots()\nax.plot(timeData, voltageData)\n\nax.set(xlabel='time (s)', ylabel='voltage (V DC)',\n title='Battery Discharge Test 4A')\nax.grid()\n\nfig.savefig(\"test_\" + str(time.time()) + \".png\")\nplt.show()","sub_path":"examples/batteryCurve.py","file_name":"batteryCurve.py","file_ext":"py","file_size_in_byte":1483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"623191283","text":"import os\nimport re\n\n\ndef regroup_documents(corpus_path, target_file):\n \"\"\"\n Regroup corpus part into one document\n :param corpus_path: path to the corpus part\n :param target_file: target file path\n :return: nothing\n \"\"\"\n\n all_sequences = list()\n\n for root, dirs, files in os.walk(os.path.abspath(corpus_path)):\n for filename in files:\n if re.match(\"^.*\\.conll\", filename):\n current_sequence = list()\n\n with open(os.path.join(root, filename), \"r\", encoding=\"UTF-8\") as input_file:\n for line in input_file:\n\n if re.match(\"^$\", line):\n if len(current_sequence) > 0:\n all_sequences.append(\"\".join(current_sequence))\n current_sequence.clear()\n\n continue\n\n current_sequence.append(line)\n\n if len(current_sequence) > 0:\n all_sequences.append(\"\".join(current_sequence))\n\n with open(os.path.abspath(target_file), \"w\", encoding=\"UTF-8\") as output_file:\n output_file.write(\n \"{}\".format(\"\\n\".join(all_sequences))\n )\n\n\ndef lower_and_replace(source_file, target_file):\n \"\"\"\n Lowercasing tokens and replacing digits by 0\n :param source_file: input file path\n :param target_file: output file path\n :return:\n \"\"\"\n\n with open(os.path.abspath(source_file), \"r\", encoding=\"UTF-8\") as input_file:\n with open(os.path.abspath(target_file), \"w\", encoding=\"UTF-8\") as output_file:\n for line in input_file:\n if re.match(\"^$\", line):\n output_file.write(\"\\n\")\n continue\n\n parts = line.rstrip(\"\\n\").split('\\t')\n parts[0] = parts[0].lower()\n parts[0] = re.sub(\"\\d\", \"0\", parts[0])\n\n output_file.write(\"{}\\n\".format(\"\\t\".join(parts)))\n\n\ndef convert_to_one_class(source_file, target_file):\n \"\"\"\n Convert multi-class IOB scheme into one-class IOB scheme\n :param source_file: input file path\n :param target_file: target file path\n :return:\n \"\"\"\n\n with open(os.path.abspath(source_file), \"r\", encoding=\"UTF-8\") as input_file:\n with open(os.path.abspath(target_file), \"w\", encoding=\"UTF-8\") as output_file:\n for line in input_file:\n if re.match(\"^$\", line):\n output_file.write(\"\\n\")\n continue\n\n parts = line.rstrip(\"\\n\").split('\\t')\n if parts[1].startswith(\"B\"):\n parts[1] = \"B\"\n elif parts[1].startswith(\"I\"):\n parts[1] = \"I\"\n\n output_file.write(\"{}\\n\".format(\"\\t\".join(parts)))\n","sub_path":"anatem/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"23507182","text":"from flask_restful import Resource, reqparse\nfrom resources.__init__ import dbengine, managemeutil\n\n# zaiter reqparse patch\nfrom resources.__init__ import zaiterClass\nreqparse.RequestParser = zaiterClass\n\n\npost_parser = reqparse.RequestParser(bundle_errors=True)\n\npost_parser.add_argument(\n 'token', dest='token',\n location='json', required=True,\n type=managemeutil.verify_request_token,\n help='The user\\'s token {error_msg}',\n)\n\npost_parser.add_argument(\n 'project_name', dest='project_name',\n location='json', required=True,\n type=managemeutil.verify_projectNotExist,\n help='The project\\'s name {error_msg}',\n)\npost_parser.add_argument(\n 'project_desc', dest='project_desc',\n location='json', required=True,\n type=str,\n help='The project\\'s description {error_msg}',\n)\n\npost_parser.add_argument(\n 'team_id', dest='team_id',\n location='json', required=True,\n type=str,\n help='The project\\'s description {error_msg}',\n)\n\nclass createproject(Resource):\n def post(self):\n args = post_parser.parse_args()\n return dbengine.createProject(args)\n\n\n","sub_path":"api/src/resources/createproject.py","file_name":"createproject.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"125296851","text":"__author__ = 'Danny Nguyen'\r\n__website__ = 'http://dannyn.xyz'\r\n__email__= 'dpnguye2@uci.edu'\r\n\r\n\r\nimport apibase\r\nimport time\r\nimport datetime\r\n\r\nTEST_URL = 'bit.ly/1rdcOF2'\r\n\r\ndef bitlydata():\r\n _url = input('Paste bitly URL: ')\r\n data = apibase.return_json(apibase.build_expand(_url))\r\n print()\r\n for key, value in data['data']['expand'][0].items(): print('{:13}: {}'.format(key, value))\r\n v3info = apibase.return_json(apibase.build_info(_url))\r\n access = v3info['data']['info'][0]\r\n created_at = datetime.datetime.fromtimestamp(access['created_at']).strftime('%Y-%m-%d %H:%M:%S')\r\n print('{:13}: {} \\n{:13}: {} \\n{:13}: {}'.format(\r\n 'created at', created_at, \r\n 'created by', access['created_by'], \r\n 'title', access['title']))\r\n print()\r\n\r\ndef bitlyshrt():\r\n _url = input('Original URL: ')\r\n data = apibase.return_json(apibase.build_shorten(_url))\r\n print() \r\n for key, value in data['data'].items(): print('{:13}: {}'.format(key, value))\r\n print('{:13}: {}'.format('created at', time.strftime(\"%c\")))\r\n print()\r\n\r\ndef main(user_choice):\r\n if user_choice == 'B': bitlydata()\r\n elif user_choice == 'S': bitlyshrt()\r\n else: print('Invalid Preference\\n')\r\n \r\n \r\nif __name__ == '__main__':\r\n print('Bitly API Module \\n')\r\n while True:\r\n print('[B] Grab bitly data \\n[S] Shorten URL \\n[Q] Quit Program\\n' + '-' * 20)\r\n user_choice = input('Preference: ').upper()\r\n if user_choice == 'Q': break\r\n else: main(user_choice)\r\n \r\n","sub_path":"bitly.py","file_name":"bitly.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"608943039","text":"# Extracts a collection of birth dates from the user and determines\n# if each individual is at least 21 years of age.\nfrom datetime import date\nfrom linearbag import Bag\n\ndef main():\n a =5\n print(type(a))\n # Date before which a person must have been born to be 21 or older.\n bornBefore = date(1988, 1, 6)\n bag1 = Bag()\n \n # Extract birth dates from the user and determine if 21 or older.\n date1 = promptAndExtractDate()\n # print date1\n # print type(date1)\n while date1 is not None :\n bag1.add(date1)\n date1 = promptAndExtractDate()\n \n #print type(bag1)\n print(bag1.__len__())\n \n \n for date1 in bag1:\n if date1<=bornBefore:\n print(\"Is at least 21 years of age: \", date1)\n# Prompts for and extracts the Gregorian date components. Returns a\n# Date object or None when the user has finished entering dates.\ndef promptAndExtractDate():\n print( \"Enter a birth date.\" )\n month = int( input(\"month (0 to quit): \") )\n if month == 0 :\n return None\n else:\n day = int( input(\"day: \") )\n year = int( input(\"year: \") )\n return date( year, month, day)\n# Call the main routine.\nmain()\n\n","sub_path":"listing1_1_2.py","file_name":"listing1_1_2.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"597160361","text":"#_*_ coding utf-8_\r\n\"\"\"\r\n\"\r\n\"@ date: 29 d'agost del 2019\r\n\"@ file: PinPon.py\r\n\"@ description: joc d'agilitat, de parar la pilota més cops que el teu adversari\r\n\"@ author: Gilbert Viader\r\n\"\r\n\" importarem les llibreries per usar els seus mètodes de pygame principalment\r\n\"\r\n\"\"\"\r\nimport pygame, random, time\r\nfrom pygame.locals import *\r\nfrom datetime import datetime\r\n\r\n\r\n#---------- definició de sortida del programa\r\ndef final() :\r\n pygame.quit()\r\n quit()\r\n\r\n#--------------- definició de la funció de parada\r\ndef parada(pause) :\r\n pygame.mixer.music.pause()\r\n while pause:\r\n for e in pygame.event.get() :\r\n if e.type == QUIT :\r\n final()\r\n elif e.type == KEYDOWN :\r\n if e.key == K_ESCAPE :\r\n final()\r\n if e.key == K_UP or e.key == K_DOWN or e.key == 119 or e.key == 115 :\r\n pause = False\r\n pygame.mixer.music.unpause()\r\n tipo = pygame.font.SysFont(None, int(amplada/5))\r\n para = tipo.render(\"PAUSA\", 1, (255, 255, 255))\r\n fines.blit(para, (amplada/4, alsada/3))\r\n pygame.display.flip()\r\n return pause\r\n#-------- definició de la funció esdeveniments\r\ndef events() :\r\n global moviment, moviment0, pause\r\n for events in pygame.event.get() :\r\n if events.type == QUIT :\r\n final()\r\n elif events.type == KEYDOWN :\r\n if events.key == K_ESCAPE :\r\n final()\r\n if events.key == K_UP :\r\n moviment -= 5\r\n if events.key == K_DOWN :\r\n moviment += 5\r\n if events.key == 119 :\r\n moviment0 -= 5\r\n if events.key == 115 :\r\n moviment0 += 5\r\n if events.key == 112 :\r\n pause = True\r\n pause = parada(pause)\r\n elif events.type == KEYUP :\r\n if events.key == K_UP or events.key == K_DOWN :\r\n moviment = 0\r\n if events.key == 119 or events.key == 115 :\r\n moviment0 = 0\r\n \r\n#------- definició de variables gobals\r\namplada, alsada = 900, 750\r\ncentre_x, centre_y = amplada/2, alsada/2\r\narea = amplada*alsada\r\nrun, pause = True, False\r\n#-------- colors principals\r\ngroc, negre, verd, roig = (225, 225, 1), (1, 1, 1), (1, 125, 1), (125, 1, 1)\r\n\r\n#--------- posicions del dos jugadors\r\njuga1_x = amplada/100+amplada/180\r\njuga1_y = centre_y-alsada/20\r\njuga2_x = amplada-amplada*3/100-amplada/180\r\njuga2_y = centre_y-alsada/20\r\nbola_x = centre_x\r\nbola_y = centre_y\r\nvelocitatBola_x, velocitatBola_y, score1, score2 = 3, 3, 0, 0\r\nmoviment, moviment0 = 0, 0\r\ndireccio = random.randint(1,2)\r\nif direccio == 1 :\r\n velocitatBola_y = -velocitatBola_y\r\n# comença el programa\r\npygame.init()\r\n#--------------- conversió d'imatges\r\nball = \"ball.png\"\r\nping_bl = pygame.image.load(ball)\r\nping_bl = pygame.transform.scale(ping_bl, (int(amplada/35), int(amplada/35)))\r\n#--------------- so del ping pong\r\nping_so = pygame.mixer.Sound(\"ping.wav\")\r\nhora = pygame.time.Clock()\r\nfines = pygame.display.set_mode((amplada, alsada))\r\npygame.mixer.music.load(\"TwoSteps.mp3\")\r\npygame.mixer.music.play(-1)\r\n# bucle principal\r\nwhile run :\r\n change_color1, change_color2 = verd, verd\r\n if pause == False :\r\n events()\r\n # moviment de la bola\r\n bola_x += velocitatBola_x\r\n bola_y += velocitatBola_y\r\n if bola_y > alsada/10*9 - amplada/50 or bola_y < alsada/10 + amplada/50 :\r\n velocitatBola_y = -velocitatBola_y\r\n pygame.mixer.Sound.play(ping_so)\r\n if bola_x > amplada - amplada/50 + amplada/50 or bola_x < amplada/100 - amplada/50 :\r\n if bola_x < centre_x :\r\n score2 += 1\r\n else :\r\n score1 += 1\r\n bola_x = centre_x\r\n bola_y = centre_y\r\n velocitatBola_x = -velocitatBola_x\r\n direccio = random.randint(1,2)\r\n if direccio == 1 :\r\n velocitatBola_y = -velocitatBola_y\r\n\r\n # moviment dels jugadors\r\n juga2_y += moviment\r\n if juga2_y < alsada/10 :\r\n juga2_y = alsada/10\r\n if juga2_y > alsada/10*9-alsada/10 :\r\n juga2_y = alsada*9/10-alsada/10\r\n juga1_y += moviment0\r\n if juga1_y < alsada/10 :\r\n juga1_y = alsada/10\r\n if juga1_y > alsada/10*9-alsada/10 :\r\n juga1_y = alsada/10*9-alsada/10\r\n # coalicions de la bola amb els jugadors\r\n if bola_x +amplada/100 > juga2_x and juga2_y < bola_y +amplada/100 < juga2_y+alsada/10 :\r\n change_color2 = roig\r\n direccio = random.randint(1,2)\r\n if direccio == 1 :\r\n velocitatBola_y = -velocitatBola_y\r\n velocitatBola_x = -velocitatBola_x\r\n if bola_x - amplada/50 < juga1_x+amplada/50 and juga1_y< bola_y - amplada/50 < juga1_y+alsada/10+amplada/50 :\r\n change_color1 = roig\r\n direccio = random.randint(1,2)\r\n if direccio == 1 :\r\n velocitatBola_y = -velocitatBola_y\r\n velocitatBola_x = -velocitatBola_x\r\n fines.fill(groc)\r\n tipograf = pygame.font.SysFont(None, int(amplada/10))\r\n marcador = tipograf.render(\"JugadorA: {} <> JugadorB: {}\".format(score1, score2), 1, roig)\r\n fines.blit(marcador, (amplada/50, 0))\r\n pygame.draw.rect(fines, verd, (amplada/100, alsada/10, amplada-amplada/50, alsada/5*4), int(alsada/100))\r\n pygame.draw.line(fines, verd, [amplada/2, alsada/10], [amplada/2, alsada/10*9], int(alsada/180))\r\n pygame.draw.circle(fines, verd, (int(centre_x), int(centre_y)), int(amplada/25), int(amplada/220))\r\n pygame.draw.rect(fines, change_color1, (juga1_x, juga1_y, amplada/50, alsada/10), 0)\r\n pygame.draw.rect(fines, change_color2, (juga2_x, juga2_y, amplada/50, alsada/10), 0)\r\n #pygame.draw.circle(fines, roig, (int(bola_x), int(bola_y)), int(amplada/50), 0)\r\n fines.blit(ping_bl, (bola_x - int(amplada/50), bola_y - int(amplada/50)))\r\n if (score1 >= 11 and score1-1>score2) or (score2 >= 11 and score2-1>score1) :\r\n run = False\r\n pygame.mixer.music.stop()\r\n if score1 > score2 :\r\n final = tipograf.render(\"Guanyador jugadorA: {} - {}\".format(score1, score2), 1, roig)\r\n fines.blit(final, (amplada/20, alsada/3))\r\n else :\r\n final = tipograf.render(\"Guanyador jugadorB: {} - {}\".format(score2, score1), 1, roig)\r\n fines.blit(final, (amplada/20, alsada/3)) \r\n pygame.display.flip()\r\n pygame.display.update()\r\n hora.tick(350)\r\n if change_color1 == roig or change_color2 == roig :\r\n time.sleep(0.5)\r\n if (score1 >= 11 and score1-1>score2) or (score2 >= 11 and score2-1>score1) :\r\n time.sleep(2)\r\n \r\n#sortir del programa\r\npygame.quit()\r\nquit()\r\n","sub_path":"PingPong.py","file_name":"PingPong.py","file_ext":"py","file_size_in_byte":6813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"549225299","text":"#!/usr/bin/python3\n\nimport urllib.request , re , time , sys\n\ndef GetPages(TheURL , TheURL2 , NumberOfPages):\n\t'''Finds the URLs of all the pages in an Instagram account'''\n\tPages = list()\n\tPages.append(TheURL)\n\tfor repeat in range(NumberOfPages):\n\t\ttry:\n\t\t\tpage = urllib.request.urlopen(TheURL2)\n\n\t\t\tfor line in page:\n\t\t\t\tline = line.decode()\n\t\t\t\tload = re.findall('\"GraphImage\", \"id\": \"([0-9]*)\"' , line)\n\t\t\t\tif load == []:\n\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\tTheURL2 = TheURL + '/?max_id=' + load[0]\n\t\t\t\t\tPages.append(TheURL2)\n\t\texcept Exception as TheError:\n\t\t\tprint('[-] Error in getting account pages')\n\t\t\tprint(TheError)\n\t\t\tcontinue\n\treturn(Pages)\n\ndef GetImages(URL):\n\t'''Takes the URL of an Instagram page and finds all the .mp4 video links in it and returns a list of all these video links'''\n\tinstagram = urllib.request.urlopen(URL)\n\tvideos = list()\n\tfor line in instagram:\n\t\tline = line.decode()\n\t\tlink = re.findall('\"code\":\\s\"(.*?)\"' , line)\n\t\tif link == []:\n\t\t\tcontinue\n\t\telse:\n\t\t\tfor code in link:\n\t\t\t\ttry:\n\t\t\t\t\tposturl = 'https://www.instagram.com/p/' + code\n\t\t\t\t\tinstagram2 = urllib.request.urlopen(posturl)\n\t\t\t\t\tfor line in instagram2:\n\t\t\t\t\t\tline = line.decode()\n\t\t\t\t\t\tlink = re.findall('\"(https:\\/\\/scontent-frt3-2\\.cdninstagram\\.com\\/[^\"]+)\"' , line)\n\t\t\t\t\t\tif link == []:\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tinstalink = link[0]\n\t\t\t\t\t\t\tvideos.append(instalink)\n\t\t\t\t\t\t\tbreak\n\t\t\t\texcept Exception as TheError:\n\t\t\t\t\tprint('[-] Error in getting video links')\n\t\t\t\t\tprint(TheError)\n\t\t\t\t\ttime.sleep(1)\n\t\t\t\t\tcontinue\n\treturn(videos)\n#----------------------------------------------------------------------------------------------------------------------------------\nURL = sys.argv[1]\nListOfPages = GetPages(URL , URL , int(sys.argv[2]))\ncount=0\nfor page in ListOfPages:\n\tListOfVideos = GetImages(page)\n\tcount +=1\n\tprint('Finished Page', count)\n\tfor URLs in ListOfVideos:\n\t\tTheFile = open('Images' , 'a')\n\t\tTheFile.write('Hello, this is a tweet title' + '\\n') #<-- Optional: Adds a text string before each URL (can be used with a twitter bot to tweet the string as title and the link as the media)\n\t\tTheFile.write(URLs + '\\n')\n\t\tTheFile.close()\n","sub_path":"InstaImageGET.py","file_name":"InstaImageGET.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"2627220","text":"class ContentFilter:\n def __init__(self, filename): \n exists = False\n while not exists:\n try:\n with open(filename, 'r') as readfile:\n exists = True\n self.filename = filename\n self.content = readfile.read()\n self.numlines = len(readfile.readlines())\n except:\n filename = input(\"Please enter a valid file name: \")\n self.numchars = len(self.content)\n self.numalphas = sum(c.isalpha() for c in self.content)\n self.numdigits = sum(c.isdigit() for c in self.content)\n self.numspaces = sum(c.isspace() for c in self.content)\n\n def uniform(self, writefile, mode='w', case='upper'):\n valid = ['w', 'x', 'a']\n if mode not in valid:\n raise ValueError(\"This is not a valid mode. Change to 'x', 'w' or 'a'\")\n if case == 'upper':\n writethis = self.content.upper()\n elif case == 'lower':\n writethis = self.content.lower()\n else:\n raise ValueError(\"This is not a valid case. Use upper or lower\")\n with open(writefile, mode) as outfile:\n outfile.write(writethis + '\\n')\n\n def reverse(self, writefile, mode='w', unit='line'):\n valid = {'w', 'x', 'a'}\n valid.add(mode)\n if len(valid) != 3:\n raise ValueError(\"This is not a valid mode. Change to 'x', 'w' or 'a'\")\n if unit == 'line':\n wordlist = self.content.split('\\n')\n newwordlist = wordlist[::-1]\n writethis = \"\\n\".join(newwordlist)\n elif unit == 'word':\n wordlist = self.content.split('\\n')\n newwordlist = wordlist\n for i in range(len(wordlist)):\n newwordlist[i] = wordlist[i][::-1]\n writethis = \"\\n\".join(newwordlist)\n else:\n raise ValueError(\"This is not a valid unit. Use line or word\")\n with open(writefile, mode) as outfile:\n outfile.write(writethis + '\\n')\n\n def transpose(self, writefile, mode='w'):\n valid = {'w', 'x', 'a'}\n valid.add(mode)\n if len(valid) != 3:\n raise ValueError(\"This is not a valid mode. Change to 'x', 'w' or 'a'\")\n lines = self.content.split('\\n')\n matrix = []\n for i in range(len(lines)):\n matrix.append(lines[i].split(' '))\n matrix = [*zip(*matrix)]\n for j in range(len(matrix)):\n matrix[j] = \" \".join(matrix[j])\n writethis = \"\\n\".join(matrix)\n with open(writefile, mode) as outfile:\n outfile.write(writethis + '\\n')\n\n def __str__(self):\n string = str(\"Source File:\\t\\t\\t\" + str(self.filename) +\n \"\\nTotal characters:\\t\\t\" + str(self.numchars) + \"\\nAlphabetic characters:\\t\\t\" +\n str(self.numalphas) + \"\\nNumerical characters:\\t\\t\" + str(self.numdigits) +\n \"\\nWhitespace characters:\\t\\t\" + str(self.numspaces) +\n \"\\nNumber of lines:\\t\\t\" + str(self.numlines))\n return string","sub_path":"ProbSets/Comp/ProbSet1/ContentFilter.py","file_name":"ContentFilter.py","file_ext":"py","file_size_in_byte":3054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"33215150","text":"# stdlib imports\nimport json\nimport re\nimport copy\nimport warnings\nimport logging\nimport os\n\n# third party imports\nimport pyasdf\nimport prov.model\nimport numpy as np\nimport scipy.interpolate as spint\nfrom obspy.core.utcdatetime import UTCDateTime\nimport pandas as pd\nfrom h5py.h5py_warnings import H5pyDeprecationWarning\nfrom impactutils.rupture.factory import get_rupture\nfrom impactutils.rupture.origin import Origin\nfrom mapio.gmt import GMTGrid\n\n# local imports\nfrom gmprocess.core.stationtrace import (\n StationTrace,\n TIMEFMT_MS,\n NS_SEIS,\n _get_person_agent,\n _get_software_agent,\n)\nfrom gmprocess.core.stationstream import StationStream\nfrom gmprocess.core.streamcollection import StreamCollection\nfrom gmprocess.metrics.station_summary import StationSummary, XML_UNITS\nfrom gmprocess.utils.event import ScalarEvent\nfrom gmprocess.utils.tables import _get_table_row\nfrom gmprocess.utils.config import get_config\n\n\nTIMEPAT = \"[0-9]{4}-[0-9]{2}-[0-9]{2}T\"\nEVENT_TABLE_COLUMNS = [\n \"id\",\n \"time\",\n \"latitude\",\n \"longitude\",\n \"depth\",\n \"magnitude\",\n \"magnitude_type\",\n]\n\n# List of columns in the flatfile, along with their descriptions for the README\nFLATFILE_COLUMNS = {\n \"EarthquakeId\": \"Event ID from Comcat\",\n \"EarthquakeTime\": \"Earthquake origin time (UTC)\",\n \"EarthquakeLatitude\": \"Earthquake latitude (decimal degrees)\",\n \"EarthquakeLongitude\": \"Earthquake longitude (decimal degrees)\",\n \"EarthquakeDepth\": \"Earthquake depth (km)\",\n \"EarthquakeMagnitude\": \"Earthquake magnitude\",\n \"EarthquakeMagnitudeType\": \"Earthquake magnitude type\",\n \"Network\": \"Network code\",\n \"DataProvider\": \"Data source provider\",\n \"StationCode\": \"Station code\",\n \"StationID\": \"Concatenated network, station, and instrument codes\",\n \"StationDescription\": \"Station description\",\n \"StationLatitude\": \"Station latitude (decimal degrees)\",\n \"StationLongitude\": \"Station longitude (decimal degrees)\",\n \"StationElevation\": \"Station elevation (m)\",\n \"SamplingRate\": \"Record sampling rate (Hz)\",\n \"BackAzimuth\": \"Site-to-source azimuth (decimal degrees)\",\n \"EpicentralDistance\": \"Epicentral distance (km)\",\n \"HypocentralDistance\": \"Hypocentral distance (km)\",\n \"RuptureDistance\": \"Closest distance to the rupture plane (km)\",\n \"RuptureDistanceVar\": \"Variance of rupture distance estimate (km^2)\",\n \"JoynerBooreDistance\": \"Joyner-Boore distance (km)\",\n \"JoynerBooreDistanceVar\": \"Variance of Joyner-Boore distance estimate (km^2)\",\n \"GC2_rx\": (\n \"Distance measured perpendicular to the fault strike from the surface\"\n \" projection of the up-dip edge of the fault plane (km)\"\n ),\n \"GC2_ry\": (\n \"Distance measured parallel to the fault strike from the midpoint of \"\n \"the surface projection of the fault plane (km)\"\n ),\n \"GC2_ry0\": (\n \"Horizontal distance off the end of the rupture measured parallel to \"\n \"strike (km)\"\n ),\n \"GC2_U\": (\n \"Strike-normal (U) coordinate, defined by Spudich and Chiou (2015; \"\n \"https://doi.org/10.3133/ofr20151028) (km)\"\n ),\n \"GC2_T\": (\n \"Strike-parallel (T) coordinate, defined by Spudich and Chiou \"\n \"(2015; https://doi.org/10.3133/ofr20151028) (km)\"\n ),\n \"H1Lowpass\": \"H1 channel lowpass frequency (Hz)\",\n \"H1Highpass\": \"H1 channel highpass frequency (Hz)\",\n \"H2Lowpass\": \"H2 channel lowpass frequency (Hz)\",\n \"H2Highpass\": \"H2 channel highpass frequency (Hz)\",\n \"ZLowpass\": \"Vertical channel lowpass frequency (Hz)\",\n \"ZHighpass\": \"Vertical channel highpass frequency (Hz)\",\n \"SourceFile\": \"Source file\",\n}\n\nFLATFILE_IMT_COLUMNS = {\n \"PGA\": f\"Peak ground acceleration ({XML_UNITS['pga']})\",\n \"PGV\": f\"Peak ground velocity ({XML_UNITS['pgv']})\",\n \"SA(X)\": f\"Pseudo-spectral acceleration ({XML_UNITS['sa']}) at X seconds\",\n \"FAS(X)\": f\"Fourier amplitude spectrum value ({XML_UNITS['fas']}) at X seconds\",\n \"DURATIONp-q\": f\"p-q percent significant duration ({XML_UNITS['duration']})\",\n \"SORTED_DURATION\": f\"Sorted significant duration ({XML_UNITS['duration']})\",\n \"ARIAS\": f\"Arias intensity ({XML_UNITS['arias']})\",\n}\n\n# List of columns in the fit_spectra_parameters file, along README descriptions\nFIT_SPECTRA_COLUMNS = {\n \"EarthquakeId\": \"Event ID from Comcat\",\n \"EarthquakeTime\": \"Earthquake origin time (UTC)\",\n \"EarthquakeLatitude\": \"Earthquake latitude (decimal degrees)\",\n \"EarthquakeLongitude\": \"Earthquake longitude (decimal degrees)\",\n \"EarthquakeDepth\": \"Earthquake depth (km)\",\n \"EarthquakeMagnitude\": \"Earthquake magnitude\",\n \"EarthquakeMagnitudeType\": \"Earthquake magnitude type\",\n \"TraceID\": \"NET.STA.LOC.CHA\",\n \"StationLatitude\": \"Station latitude (decimal degrees)\",\n \"StationLongitude\": \"Station longitude (decimal degrees)\",\n \"StationElevation\": \"Station elevation (m)\",\n \"fmin\": \"Record highpass filter frequency (Hz)\",\n \"fmax\": \"Record lowpass filter frequency (Hz)\",\n \"epi_dist\": \"Epicentral distance (km)\",\n \"f0\": \"Brune corner frequency (Hz)\",\n \"kappa\": \"Site diminution factor (sec)\",\n \"magnitude\": \"Magnitude from optimized moment\",\n \"minimize_message\": \"Output message from scipy.optimize.minimize\",\n \"minimize_success\": \"Boolean flag indicating if the optimizer exited successfully\",\n \"moment\": \"Moment fit (dyne-cm)\",\n \"moment_lnsd\": \"Natural log standard deviation of the moment fit\",\n \"stress_drop\": \"Stress drop fit (bars)\",\n \"stress_drop_lnsd\": \"Natural log standard deviation of the stress drop fit\",\n \"R2\": (\"Coefficient of determination between fitted and observed spectra\"),\n \"mean_squared_error\": (\"Mean squared error between fitted and observed spectra\"),\n}\n\n# List of columns in the fit_spectra_parameters file, along README descriptions\nSNR_COLUMNS = {\n \"EarthquakeId\": \"Event ID from Comcat\",\n \"EarthquakeTime\": \"Earthquake origin time (UTC)\",\n \"EarthquakeLatitude\": \"Earthquake latitude (decimal degrees)\",\n \"EarthquakeLongitude\": \"Earthquake longitude (decimal degrees)\",\n \"EarthquakeDepth\": \"Earthquake depth (km)\",\n \"EarthquakeMagnitude\": \"Earthquake magnitude\",\n \"EarthquakeMagnitudeType\": \"Earthquake magnitude type\",\n \"TraceID\": \"NET.STA.LOC.CHA\",\n \"StationLatitude\": \"Station latitude (decimal degrees)\",\n \"StationLongitude\": \"Station longitude (decimal degrees)\",\n \"StationElevation\": \"Station elevation (m)\",\n}\n\nSNR_FREQ_COLUMNS = {\"SNR(X)\": \"Signa-to-noise ratio at frequency X.\"}\n\nM_PER_KM = 1000\n\nFORMAT_VERSION = \"1.0\"\n\n\ndef format_netsta(stats):\n return \"{st.network}.{st.station}\".format(st=stats)\n\n\ndef format_nslc(stats):\n # loc = '' if stats.location == '--' else stats.location\n return \"{st.network}.{st.station}.{st.location}.{st.channel}\".format(st=stats)\n\n\ndef format_nslct(stats, tag):\n return format_nslc(stats) + \"_\" + tag\n\n\ndef format_nslit(stats, inst, tag):\n # loc = '' if stats.location == '--' else stats.location\n return \"{st.network}.{st.station}.{st.location}.{inst}_{tag}\".format(\n st=stats, inst=inst, tag=tag\n )\n\n\nclass StreamWorkspace(object):\n def __init__(self, filename, compression=None):\n \"\"\"Create an ASDF file given an Event and list of StationStreams.\n\n Args:\n filename (str):\n Path to ASDF file to create.\n compression (str):\n Any value supported by pyasdf.asdf_data_set.ASDFDataSet.\n \"\"\"\n if os.path.exists(filename):\n self.dataset = pyasdf.ASDFDataSet(filename)\n else:\n self.dataset = pyasdf.ASDFDataSet(filename, compression=compression)\n self.FORMAT_VERSION = FORMAT_VERSION\n\n # Add the config data as workspace attribute if it is present\n group_name = f\"{'config'}/{'config'}\"\n config_exists = group_name in self.dataset._auxiliary_data_group\n if config_exists:\n self.setConfig()\n\n @classmethod\n def create(cls, filename, compression=None):\n \"\"\"Load from existing ASDF file.\n\n Args:\n filename (str):\n Path to existing ASDF file.\n compression (str):\n Any value supported by pyasdf.asdf_data_set.ASDFDataSet.\n\n Returns:\n StreamWorkspace: Object containing ASDF file.\n \"\"\"\n if os.path.exists(filename):\n raise IOError(f\"File {filename} already exists.\")\n return cls(filename)\n\n @classmethod\n def open(cls, filename):\n \"\"\"Load from existing ASDF file.\n\n Args:\n filename (str):\n Path to existing ASDF file.\n\n Returns:\n StreamWorkspace: Object containing ASDF file.\n \"\"\"\n if not os.path.exists(filename):\n raise IOError(f\"File {filename} does not exist.\")\n return cls(filename)\n\n def close(self):\n \"\"\"Close the workspace.\"\"\"\n del self.dataset\n\n def __repr__(self):\n \"\"\"Provide summary string representation of the file.\n\n Returns:\n str: Summary string representation of the file.\n \"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\", category=H5pyDeprecationWarning)\n fmt = \"Events: %i Stations: %i Streams: %i\"\n nevents = len(self.dataset.events)\n stations = []\n nstreams = 0\n for waveform in self.dataset.waveforms:\n inventory = waveform[\"StationXML\"]\n nstreams += len(waveform.get_waveform_tags())\n for station in inventory.networks[0].stations:\n stations.append(station.code)\n stations = set(stations)\n nstations = len(stations)\n return fmt % (nevents, nstations, nstreams)\n\n def addEvent(self, event):\n \"\"\"Add event object to file.\n\n Args:\n event (Event): Obspy event object.\n \"\"\"\n self.dataset.add_quakeml(event)\n\n def addConfig(self, config=None):\n \"\"\"Add config to an ASDF dataset and workspace attribute.\"\"\"\n if config is None:\n config = get_config()\n self.config = config\n config_bytes = json.dumps(config).encode(\"utf-8\")\n config_array = np.frombuffer(config_bytes, dtype=np.uint8)\n self.dataset.add_auxiliary_data(\n config_array, data_type=\"config\", path=\"config\", parameters={}\n )\n\n def setConfig(self):\n \"\"\"Get config from ASDF dataset and set as a workspace attribute.\"\"\"\n group_name = f\"{'config'}/{'config'}\"\n data_exists = group_name in self.dataset._auxiliary_data_group\n if not data_exists:\n logging.error(\"No config found in auxiliary data.\")\n bytelist = self.dataset._auxiliary_data_group[group_name][()].tolist()\n conf_str = \"\".join([chr(b) for b in bytelist])\n self.config = json.loads(conf_str)\n\n def addGmprocessVersion(self, version):\n \"\"\"Add gmprocess version to an ASDF file.\"\"\"\n self.insert_aux(version, data_name=\"gmprocess_version\", path=\"version\")\n\n def getGmprocessVersion(self):\n \"\"\"Get gmprocess version from ASDF file.\"\"\"\n group_name = f\"{'gmprocess_version'}/{'version'}\"\n data_exists = group_name in self.dataset._auxiliary_data_group\n if not data_exists:\n logging.error(\"No version for gmprocess found.\")\n bytelist = self.dataset._auxiliary_data_group[group_name][()].tolist()\n gmprocess_version = \"\".join([chr(b) for b in bytelist])\n return gmprocess_version\n\n def addStreams(self, event, streams, label=None, gmprocess_version=\"unknown\"):\n \"\"\"Add a sequence of StationStream objects to an ASDF file.\n\n Args:\n event (Event):\n Obspy event object.\n streams (list):\n List of StationStream objects.\n label (str):\n Label to attach to stream sequence. Cannot contain an\n underscore.\n gmprocess_version (str):\n gmprocess version.\n \"\"\"\n if label is not None:\n if \"_\" in label:\n raise ValueError(\"Stream label cannot contain an underscore.\")\n\n # To allow for multiple processed versions of the same Stream\n # let's keep a dictionary of stations and sequence number.\n eventid = _get_id(event)\n if not self.hasEvent(eventid):\n self.addEvent(event)\n\n # Creating a new provenance document and filling in the software\n # information for every trace can be slow, so here we create a\n # base provenance document that will be copied and used as a template\n base_prov = prov.model.ProvDocument()\n base_prov.add_namespace(*NS_SEIS)\n if hasattr(self, \"config\"):\n config = self.config\n else:\n config = get_config()\n base_prov = _get_person_agent(base_prov, config)\n base_prov = _get_software_agent(base_prov, gmprocess_version)\n\n logging.debug(streams)\n for stream in streams:\n station = stream[0].stats[\"station\"]\n logging.info(f\"Adding waveforms for station {station}\")\n # is this a raw file? Check the trace for provenance info.\n is_raw = not len(stream[0].getProvenanceKeys())\n\n if label is None:\n tfmt = \"%Y%m%d%H%M%S\"\n tnow = UTCDateTime.now().strftime(tfmt)\n label = f\"processed{tnow}\"\n tag = f\"{eventid}_{label}\"\n if is_raw:\n level = \"raw\"\n else:\n level = \"processed\"\n self.dataset.add_waveforms(stream, tag=tag, event_id=event)\n\n # add processing provenance info from traces\n if level == \"processed\":\n provdocs = stream.getProvenanceDocuments(base_prov)\n for provdoc, trace in zip(provdocs, stream):\n provname = format_nslct(trace.stats, tag)\n self.dataset.add_provenance_document(provdoc, name=provname)\n\n # add processing parameters from streams\n jdict = {}\n for key in stream.getStreamParamKeys():\n value = stream.getStreamParam(key)\n jdict[key] = value\n\n if len(jdict):\n # NOTE: We would store this dictionary just as\n # the parameters dictionary, but HDF cannot handle\n # nested dictionaries.\n # Also, this seems like a lot of effort\n # just to store a string in HDF, but other\n # approaches failed. Suggestions are welcome.\n jdict = _stringify_dict(jdict)\n jsonbytes = json.dumps(jdict).encode(\"utf-8\")\n jsonarray = np.frombuffer(jsonbytes, dtype=np.uint8)\n dtype = \"StreamProcessingParameters\"\n parampath = \"/\".join(\n [\n format_netsta(stream[0].stats),\n format_nslit(stream[0].stats, stream.get_inst(), tag),\n ]\n )\n self.dataset.add_auxiliary_data(\n jsonarray, data_type=dtype, path=parampath, parameters={}\n )\n\n # add processing parameters from traces\n for trace in stream:\n procname = \"/\".join(\n [\n format_netsta(trace.stats),\n format_nslct(trace.stats, tag),\n ]\n )\n jdict = {}\n for key in trace.getParameterKeys():\n value = trace.getParameter(key)\n jdict[key] = value\n if len(jdict):\n # NOTE: We would store this dictionary just as\n # the parameters dictionary, but HDF cannot handle\n # nested dictionaries.\n # Also, this seems like a lot of effort\n # just to store a string in HDF, but other\n # approached failed. Suggestions are welcome.\n jdict = _stringify_dict(jdict)\n jsonbytes = json.dumps(jdict).encode(\"utf-8\")\n jsonarray = np.frombuffer(jsonbytes, dtype=np.uint8)\n dtype = \"TraceProcessingParameters\"\n self.dataset.add_auxiliary_data(\n jsonarray, data_type=dtype, path=procname, parameters={}\n )\n\n # Some processing data is computationally intensive to\n # compute, so we store it in the 'Cache' group.\n for specname in trace.getCachedNames():\n spectrum = trace.getCached(specname)\n # we expect many of these specnames to\n # be joined with underscores.\n name_parts = specname.split(\"_\")\n base_dtype = \"\".join([part.capitalize() for part in name_parts])\n for array_name, array in spectrum.items():\n path = base_dtype + array_name.capitalize() + \"/\" + procname\n try:\n self.dataset.add_auxiliary_data(\n array, data_type=\"Cache\", path=path, parameters={}\n )\n except BaseException:\n pass\n\n inventory = stream.getInventory()\n self.dataset.add_stationxml(inventory)\n\n def getEventIds(self):\n \"\"\"Return list of event IDs for events in ASDF file.\n\n Returns:\n list: List of eventid strings.\n \"\"\"\n idlist = []\n for event in self.dataset.events:\n eid = event.resource_id.id.replace(\"smi:local/\", \"\")\n idlist.append(eid)\n return idlist\n\n def getLabels(self):\n \"\"\"Return all of the processing labels.\n\n Returns:\n list: List of processing labels.\n \"\"\"\n all_tags = []\n for w in self.dataset.waveforms:\n all_tags.extend(w.get_waveform_tags())\n all_labels = list(set([at.split(\"_\")[-1] for at in all_tags]))\n labels = list(set(all_labels))\n return labels\n\n def getStreams(self, eventid, stations=None, labels=None, config=None):\n \"\"\"Get Stream from ASDF file given event id and input tags.\n\n Args:\n eventid (str):\n Event ID corresponding to an Event in the workspace.\n stations (list):\n List of stations (.) to search for.\n labels (list):\n List of processing labels to search for.\n config (dict):\n Configuration options.\n\n Returns:\n StreamCollection: Object containing list of organized\n StationStreams.\n \"\"\"\n trace_auxholder = []\n stream_auxholder = []\n auxdata = self.dataset.auxiliary_data\n if \"TraceProcessingParameters\" in auxdata:\n trace_auxholder = auxdata.TraceProcessingParameters\n if \"StreamProcessingParameters\" in auxdata:\n stream_auxholder = auxdata.StreamProcessingParameters\n streams = []\n\n if stations is None:\n stations = self.getStations()\n if labels is None:\n labels = self.getLabels()\n\n net_codes = [st.split(\".\")[0] for st in stations]\n sta_codes = [st.split(\".\")[1] for st in stations]\n tag = [f\"{eventid}_{label}\" for label in labels]\n\n for waveform in self.dataset.ifilter(\n self.dataset.q.network == net_codes,\n self.dataset.q.station == sta_codes,\n self.dataset.q.tag == tag,\n ):\n tags = waveform.get_waveform_tags()\n for tag in tags:\n tstream = waveform[tag]\n\n inventory = waveform[\"StationXML\"]\n for ttrace in tstream:\n if isinstance(ttrace.data[0], np.floating):\n if ttrace.data[0].nbytes == 4:\n ttrace.data = ttrace.data.astype(\"float32\")\n else:\n ttrace.data = ttrace.data.astype(\"float64\")\n else:\n if ttrace.data[0].nbytes == 2:\n ttrace.data = ttrace.data.astype(\"int16\")\n elif ttrace.data[0].nbytes == 4:\n ttrace.data = ttrace.data.astype(\"int32\")\n else:\n ttrace.data = ttrace.data.astype(\"int64\")\n trace = StationTrace(\n data=ttrace.data,\n header=ttrace.stats,\n inventory=inventory,\n config=config,\n )\n\n # get the provenance information\n provname = format_nslct(trace.stats, tag)\n if provname in self.dataset.provenance.list():\n provdoc = self.dataset.provenance[provname]\n trace.setProvenanceDocument(provdoc)\n\n # get the trace processing parameters\n top = format_netsta(trace.stats)\n trace_path = format_nslct(trace.stats, tag)\n if top in trace_auxholder:\n root_auxholder = trace_auxholder[top]\n if trace_path in root_auxholder:\n bytelist = root_auxholder[trace_path].data[:].tolist()\n jsonstr = \"\".join([chr(b) for b in bytelist])\n jdict = json.loads(jsonstr)\n for key, value in jdict.items():\n trace.setParameter(key, value)\n\n # get the trace spectra arrays from auxiliary,\n # repack into stationtrace object\n spectra = {}\n\n if \"Cache\" in auxdata:\n for aux in auxdata[\"Cache\"].list():\n auxarray = auxdata[\"Cache\"][aux]\n if top not in auxarray.list():\n continue\n auxarray_top = auxarray[top]\n if trace_path in auxarray_top:\n specparts = camel_case_split(aux)\n array_name = specparts[-1].lower()\n specname = \"_\".join(specparts[:-1]).lower()\n specarray = auxarray_top[trace_path].data[()]\n if specname in spectra:\n spectra[specname][array_name] = specarray\n else:\n spectra[specname] = {array_name: specarray}\n for key, value in spectra.items():\n trace.setCached(key, value)\n\n stream = StationStream(traces=[trace])\n stream.tag = tag # testing this out\n\n # get the stream processing parameters\n stream_path = format_nslit(trace.stats, stream.get_inst(), tag)\n if top in stream_auxholder:\n top_auxholder = stream_auxholder[top]\n if stream_path in top_auxholder:\n auxarray = top_auxholder[stream_path]\n bytelist = auxarray.data[:].tolist()\n jsonstr = \"\".join([chr(b) for b in bytelist])\n jdict = json.loads(jsonstr)\n for key, value in jdict.items():\n stream.setStreamParam(key, value)\n\n streams.append(stream)\n # No need to handle duplicates when retrieving stations from the\n # workspace file because it must have been handled before putting them\n # into the workspace file.\n streams = StreamCollection(streams, handle_duplicates=False, config=config)\n return streams\n\n def getStations(self):\n \"\"\"Get list of station codes within the file.\n\n Returns:\n list: List of station codes contained in workspace.\n \"\"\"\n stations = self.dataset.waveforms.list()\n return stations\n\n def insert_aux(self, datastr, data_name, path, overwrite=False):\n \"\"\"Insert a string (usually json or xml) into Auxilliary array.\n\n Args:\n datastr (str):\n String containing data to insert into Aux array.\n data_name (str):\n What this data should be called in the ASDF file.\n path (str):\n The aux path where this data should be stored.\n overwrite (bool):\n Should the data be overwritten if it already exists?\n \"\"\"\n # this seems like a lot of effort\n # just to store a string in HDF, but other\n # approaches failed. Suggestions are welcome.\n\n group_name = f\"{data_name}/{path}\"\n data_exists = group_name in self.dataset._auxiliary_data_group\n if overwrite and data_exists:\n del self.dataset._auxiliary_data_group[group_name]\n\n databuf = datastr.encode(\"utf-8\")\n data_array = np.frombuffer(databuf, dtype=np.uint8)\n dtype = data_name\n self.dataset.add_auxiliary_data(\n data_array, data_type=dtype, path=path, parameters={}\n )\n\n def calcMetrics(\n self,\n eventid,\n stations=None,\n labels=None,\n config=None,\n streams=None,\n stream_label=None,\n rupture_file=None,\n calc_station_metrics=True,\n calc_waveform_metrics=True,\n ):\n \"\"\"\n Calculate waveform and/or station metrics for a set of waveforms.\n\n Args:\n eventid (str):\n ID of event to search for in ASDF file.\n stations (list):\n List of stations to create metrics for.\n labels (list):\n List of processing labels to create metrics for.\n config (dict):\n Configuration dictionary.\n streams (StreamCollection):\n Optional StreamCollection object to create metrics for.\n stream_label (str):\n Label to be used in the metrics path when providing a\n StreamCollection.\n rupture_file (str):\n Path pointing to the rupture file.\n calc_station_metrics (bool):\n Whether to calculate station metrics. Default is True.\n calc_waveform_metrics (bool):\n Whether to calculate waveform metrics. Default is True.\n \"\"\"\n if not self.hasEvent(eventid):\n fmt = \"No event matching %s found in workspace.\"\n raise KeyError(fmt % eventid)\n\n if streams is None:\n streams = self.getStreams(eventid, stations=stations, labels=labels)\n\n event = self.getEvent(eventid)\n\n # Load the rupture file\n origin = Origin(\n {\n \"id\": event.resource_id.id.replace(\"smi:local/\", \"\"),\n \"netid\": \"\",\n \"network\": \"\",\n \"lat\": event.latitude,\n \"lon\": event.longitude,\n \"depth\": event.depth_km,\n \"locstring\": \"\",\n \"mag\": event.magnitude,\n \"time\": event.time,\n }\n )\n rupture = get_rupture(origin, rupture_file)\n\n vs30_grids = None\n if config is not None:\n if \"vs30\" in config[\"metrics\"]:\n vs30_grids = config[\"metrics\"][\"vs30\"]\n for vs30_name in vs30_grids:\n vs30_grids[vs30_name][\"grid_object\"] = GMTGrid.load(\n vs30_grids[vs30_name][\"file\"]\n )\n\n for stream in streams:\n instrument = stream.get_id()\n logging.info(f\"Calculating stream metrics for {instrument}...\")\n\n try:\n summary = StationSummary.from_config(\n stream,\n event=event,\n config=config,\n calc_waveform_metrics=calc_waveform_metrics,\n calc_station_metrics=calc_station_metrics,\n rupture=rupture,\n vs30_grids=vs30_grids,\n )\n except BaseException as pgme:\n fmt = (\n \"Could not create stream metrics for event %s,\"\n 'instrument %s: \"%s\"'\n )\n logging.warning(fmt % (eventid, instrument, str(pgme)))\n continue\n\n if calc_waveform_metrics and stream.passed:\n xmlstr = summary.get_metric_xml()\n if stream_label is not None:\n tag = f\"{eventid}_{stream_label}\"\n else:\n tag = stream.tag\n metricpath = \"/\".join(\n [\n format_netsta(stream[0].stats),\n format_nslit(stream[0].stats, stream.get_inst(), tag),\n ]\n )\n self.insert_aux(xmlstr, \"WaveFormMetrics\", metricpath)\n\n if calc_station_metrics:\n xmlstr = summary.get_station_xml()\n metricpath = \"/\".join(\n [\n format_netsta(stream[0].stats),\n format_nslit(stream[0].stats, stream.get_inst(), eventid),\n ]\n )\n self.insert_aux(xmlstr, \"StationMetrics\", metricpath)\n\n def getTables(self, label, config):\n \"\"\"Retrieve dataframes containing event information and IMC/IMT\n metrics.\n\n Args:\n label (str):\n Calculate metrics only for the given label.\n config (dict):\n Config options.\n\n Returns:\n tuple: Elements are:\n - pandas DataFrame containing event information:\n - id Event ID\n - time Time of origin\n - latitude Latitude of origin\n - longitude Longitude of origin\n - depth Depth of origin (km)\n - magnitude Magnitude at origin (km)\n - magnitude_type Magnitude type at origin\n - dictionary of DataFrames, where keys are IMCs and\n values are DataFrames with columns:\n - EarthquakeId Earthquake id from event table\n - Network Network code\n - StationCode Station code\n - StationDescription Long form description of station\n location (may be blank)\n - StationLatitude Station latitude\n - StationLongitude Station longitude\n - StationElevation Station elevation\n - SamplingRate Data sampling rate in Hz\n - EpicentralDistance Distance from origin epicenter\n (surface) to station\n - HypocentralDistance Distance from origin hypocenter\n (depth) to station\n - H1Lowpass Low pass filter corner frequency for first\n horizontal channel\n - H1Highpass High pass filter corner frequency for first\n horizontal channel\n - H2Lowpass Low pass filter corner frequency for second\n horizontal channel\n - H2Highpass High pass filter corner frequency for\n second horizontal channel\n - ...desired IMTs (PGA, PGV, SA(0.3), etc.)\n - dictionary of README DataFrames, where keys are IMCs\n and values are DataFrames with columns:\n - Column header\n - Description\n \"\"\"\n event_info = []\n imc_tables = {}\n readme_tables = {}\n for eventid in self.getEventIds():\n event = self.getEvent(eventid)\n event_info.append(\n {\n \"id\": event.resource_id.id.replace(\"smi:local/\", \"\"),\n \"time\": event.time,\n \"latitude\": event.latitude,\n \"longitude\": event.longitude,\n \"depth\": event.depth_km,\n \"magnitude\": event.magnitude,\n \"magnitude_type\": event.magnitude_type,\n }\n )\n\n station_list = self.dataset.waveforms.list()\n\n for station_id in station_list:\n streams = self.getStreams(\n event.resource_id.id.replace(\"smi:local/\", \"\"),\n stations=[station_id],\n labels=[label],\n config=config,\n )\n if not len(streams):\n raise ValueError(\"No matching streams found.\")\n\n for stream in streams:\n if not stream.passed:\n continue\n\n station = stream[0].stats.station\n network = stream[0].stats.network\n summary = self.getStreamMetrics(\n eventid,\n network,\n station,\n label,\n streams=[stream],\n stream_label=label,\n )\n\n if summary is None:\n continue\n\n pgms = summary.pgms\n imclist = pgms.index.get_level_values(\"IMC\").unique().tolist()\n imtlist = pgms.index.get_level_values(\"IMT\").unique().tolist()\n imtlist.sort(key=_natural_keys)\n\n # Add any Vs30 columns to the list of FLATFILE_COLUMNS\n for vs30_dict in summary._vs30.values():\n FLATFILE_COLUMNS[vs30_dict[\"column_header\"]] = vs30_dict[\n \"readme_entry\"\n ]\n\n for imc in imclist:\n if imc not in imc_tables:\n row = _get_table_row(stream, summary, event, imc)\n if not len(row):\n continue\n imc_tables[imc] = [row]\n else:\n row = _get_table_row(stream, summary, event, imc)\n if not len(row):\n continue\n imc_tables[imc].append(row)\n\n # Remove any empty IMT columns from the IMC tables\n for key, table in imc_tables.items():\n table = pd.DataFrame.from_dict(table)\n imt_cols = list(set(table.columns) & set(imtlist))\n\n # Remove FAS?\n fas_cols = [c for c in imt_cols if c.startswith(\"FAS(\")]\n fas_df = table[fas_cols]\n if pd.isna(fas_df).all(axis=None):\n imt_cols = [x for x in imt_cols if x not in fas_cols]\n imt_cols.sort(key=_natural_keys)\n\n non_imt_cols = [col for col in table.columns if col not in imtlist]\n table = table[non_imt_cols + imt_cols]\n imc_tables[key] = table\n readme_dict = {}\n for col in table.columns:\n if col in FLATFILE_COLUMNS:\n readme_dict[col] = FLATFILE_COLUMNS[col]\n else:\n imt = col.upper()\n if imt.startswith(\"SA\"):\n readme_dict[\"SA(X)\"] = FLATFILE_IMT_COLUMNS[\"SA(X)\"]\n elif imt.startswith(\"FAS\"):\n readme_dict[\"FAS(X)\"] = FLATFILE_IMT_COLUMNS[\"FAS(X)\"]\n elif imt.startswith(\"DURATION\"):\n readme_dict[\"DURATIONp-q\"] = FLATFILE_IMT_COLUMNS[\"DURATIONp-q\"]\n else:\n readme_dict[imt] = FLATFILE_IMT_COLUMNS[imt]\n df_readme = pd.DataFrame.from_dict(readme_dict, orient=\"index\")\n df_readme.reset_index(level=0, inplace=True)\n df_readme.columns = [\"Column header\", \"Description\"]\n readme_tables[key] = df_readme\n\n event_table = pd.DataFrame.from_dict(event_info)\n return (event_table, imc_tables, readme_tables)\n\n def getFitSpectraTable(self, eventid, label, config):\n \"\"\"\n Returns a tuple of two pandas DataFrames. The first contains the\n fit_spectra parameters for each trace in the workspace matching\n eventid and label. The second is a README describing each column\n in the first DataFrame.\n\n Args:\n eventid (str):\n Return parameters only for the given eventid.\n label (str):\n Return parameters only for the given label.\n config (dict):\n Dictionary of config options.\n\n Returns:\n pandas.DataFrame:\n A DataFrame containing the fit_spectra parameters on a trace-\n by-trace basis.\n \"\"\"\n fit_table = []\n event = self.getEvent(eventid)\n if not event:\n return (None, None)\n\n station_list = self.dataset.waveforms.list()\n for station_id in station_list:\n streams = self.getStreams(\n event.resource_id.id.replace(\"smi:local/\", \"\"),\n stations=[station_id],\n labels=[label],\n config=config,\n )\n\n for st in streams:\n if not st.passed:\n continue\n for tr in st:\n if tr.hasParameter(\"fit_spectra\"):\n fit_dict = tr.getParameter(\"fit_spectra\")\n fit_dict[\"EarthquakeId\"] = eventid\n fit_dict[\"EarthquakeTime\"] = event.time\n fit_dict[\"EarthquakeLatitude\"] = event.latitude\n fit_dict[\"EarthquakeLongitude\"] = event.longitude\n fit_dict[\"EarthquakeDepth\"] = event.depth_km\n fit_dict[\"EarthquakeMagnitude\"] = event.magnitude\n fit_dict[\"EarthquakeMagnitudeType\"] = event.magnitude_type\n fit_dict[\"TraceID\"] = tr.id\n fit_dict[\"StationLatitude\"] = tr.stats.coordinates.latitude\n fit_dict[\"StationLongitude\"] = tr.stats.coordinates.longitude\n fit_dict[\"StationElevation\"] = tr.stats.coordinates.elevation\n if tr.hasParameter(\"corner_frequencies\"):\n freq_dict = tr.getParameter(\"corner_frequencies\")\n fit_dict[\"fmin\"] = freq_dict[\"highpass\"]\n fit_dict[\"fmax\"] = freq_dict[\"lowpass\"]\n fit_table.append(fit_dict)\n\n if len(fit_table):\n df = pd.DataFrame.from_dict(fit_table)\n else:\n return (None, None)\n\n # Ensure that the DataFrame columns are ordered correctly\n df = df[FIT_SPECTRA_COLUMNS.keys()]\n\n readme = pd.DataFrame.from_dict(FIT_SPECTRA_COLUMNS, orient=\"index\")\n readme.reset_index(level=0, inplace=True)\n readme.columns = [\"Column header\", \"Description\"]\n\n return (df, readme)\n\n def getSNRTable(self, eventid, label, config):\n \"\"\"\n Returns a tuple of two pandas DataFrames. The first contains the\n fit_spectra parameters for each trace in the workspace matching\n eventid and label. The second is a README describing each column\n in the first DataFrame.\n\n Args:\n eventid (str):\n Return parameters only for the given eventid.\n label (str):\n Return parameters only for the given label.\n config (dict):\n Dictionary of config options.\n\n Returns:\n tuple of pandas DataFrames, which consists of the SNR dataframe and its\n associated readme.\n \"\"\"\n # Get list of periods in SA to interpolate SNR to.\n if \"WaveFormMetrics\" not in self.dataset.auxiliary_data:\n logging.warning(\n \"No WaveFormMetrics found. Please run \"\n \"'compute_waveform_metrics' subcommand.\"\n )\n return (None, None)\n wm = self.dataset.auxiliary_data.WaveFormMetrics\n wm_tmp = wm[wm.list()[0]]\n bytelist = wm_tmp[wm_tmp.list()[0]].data[:].tolist()\n xml_stream = \"\".join([chr(b) for b in bytelist]).encode(\"utf-8\")\n sm = self.dataset.auxiliary_data.StationMetrics\n sm_tmp = sm[sm.list()[0]]\n bytelist = sm_tmp[sm_tmp.list()[0]].data[:].tolist()\n xml_station = \"\".join([chr(b) for b in bytelist]).encode(\"utf-8\")\n summary = StationSummary.from_xml(xml_stream, xml_station)\n pgms = summary.pgms\n periods = []\n for key, _ in pgms[\"Result\"].keys():\n if key.startswith(\"SA\"):\n periods.append(float(key[3:-1]))\n periods = np.unique(periods)\n\n snr_table = []\n event = self.getEvent(eventid)\n\n station_list = self.dataset.waveforms.list()\n for station_id in station_list:\n streams = self.getStreams(\n event.resource_id.id.replace(\"smi:local/\", \"\"),\n stations=[station_id],\n labels=[label],\n config=config,\n )\n\n for st in streams:\n if not st.passed:\n continue\n for tr in st:\n if tr.hasCached(\"snr\"):\n snr_dict = self.__flatten_snr_dict(tr, periods)\n snr_dict[\"EarthquakeId\"] = eventid\n snr_dict[\"EarthquakeTime\"] = event.time\n snr_dict[\"EarthquakeLatitude\"] = event.latitude\n snr_dict[\"EarthquakeLongitude\"] = event.longitude\n snr_dict[\"EarthquakeDepth\"] = event.depth_km\n snr_dict[\"EarthquakeMagnitude\"] = event.magnitude\n snr_dict[\"EarthquakeMagnitudeType\"] = event.magnitude_type\n snr_dict[\"TraceID\"] = tr.id\n snr_dict[\"StationLatitude\"] = tr.stats.coordinates.latitude\n snr_dict[\"StationLongitude\"] = tr.stats.coordinates.longitude\n snr_dict[\"StationElevation\"] = tr.stats.coordinates.elevation\n snr_table.append(snr_dict)\n\n if len(snr_table):\n df = pd.DataFrame.from_dict(snr_table)\n else:\n df = pd.DataFrame(columns=SNR_COLUMNS.keys())\n\n # Ensure that the DataFrame columns are ordered correctly\n df1 = pd.DataFrame()\n df2 = pd.DataFrame()\n for col in df.columns:\n if col in SNR_COLUMNS:\n df1[col] = df[col]\n else:\n df2[col] = df[col]\n df1 = df1[SNR_COLUMNS.keys()]\n df_final = pd.concat([df1, df2], axis=1)\n\n readme = pd.DataFrame.from_dict(\n {**SNR_COLUMNS, **SNR_FREQ_COLUMNS}, orient=\"index\"\n )\n readme.reset_index(level=0, inplace=True)\n readme.columns = [\"Column header\", \"Description\"]\n\n return (df_final, readme)\n\n @staticmethod\n def __flatten_snr_dict(tr, periods):\n freq = np.sort(1 / periods)\n tmp_dict = tr.getCached(\"snr\")\n interp = spint.interp1d(\n tmp_dict[\"freq\"],\n np.clip(tmp_dict[\"snr\"], 0, np.inf),\n kind=\"linear\",\n copy=False,\n bounds_error=False,\n fill_value=np.nan,\n assume_sorted=True,\n )\n snr = interp(freq)\n snr_dict = {}\n for f, s in zip(freq, snr):\n key = f\"SNR({f:.4g})\"\n snr_dict[key] = s\n return snr_dict\n\n def getStreamMetrics(\n self,\n eventid,\n network,\n station,\n label,\n streams=None,\n stream_label=None,\n config=None,\n ):\n \"\"\"Extract a StationSummary object from the ASDF file for a given\n input Stream.\n\n Args:\n eventid (str):\n ID of event to search for in ASDF file.\n network (str):\n Network to return metrics from.\n station (str):\n Station to return metrics from.\n label (str):\n Processing label to return metrics from.\n streams (StreamCollection):\n Optional StreamCollection object to get metrics for.\n stream_label (str):\n Label to be used in the metrics path when providing a\n StreamCollection.\n config (dict):\n Configuration options.\n\n Returns:\n StationSummary: Object containing all stream metrics or None.\n \"\"\"\n if \"WaveFormMetrics\" not in self.dataset.auxiliary_data:\n msg = \"Waveform metrics not found in workspace, cannot get stream metrics.\"\n logging.warning(msg)\n return None\n\n auxholder = self.dataset.auxiliary_data.WaveFormMetrics\n\n # get the stream matching the eventid, station, and label\n if streams is None:\n station_id = f\"{network}.{station}\"\n streams = self.getStreams(\n eventid, stations=[station_id], labels=[label], config=config\n )\n\n # Only get streams that passed and match network\n streams = [\n st for st in streams if (st.passed and st[0].stats.network == network)\n ]\n\n if not len(streams):\n fmt = (\n \"Stream matching event ID %s, \"\n \"station ID %s.%s, and processing label %s not found in \"\n \"workspace.\"\n )\n msg = fmt % (eventid, network, station, label)\n logging.warning(msg)\n return None\n\n if stream_label is not None:\n stream_tag = f\"{eventid}_{stream_label}\"\n else:\n stream_tag = streams[0].tag\n\n metricpath = format_nslit(\n streams[0][0].stats, streams[0].get_inst(), stream_tag\n )\n top = format_netsta(streams[0][0].stats)\n if top in auxholder:\n tauxholder = auxholder[top]\n if metricpath not in tauxholder:\n fmt = (\n \"Stream metrics path (%s) not in WaveFormMetrics \" \"auxiliary_data.\"\n )\n logging.warning(fmt % metricpath)\n return None\n\n bytelist = tauxholder[metricpath].data[:].tolist()\n xml_stream = \"\".join([chr(b) for b in bytelist])\n xml_stream = xml_stream.encode(\"utf-8\")\n else:\n return\n\n if \"StationMetrics\" not in self.dataset.auxiliary_data:\n logging.warning(\"Station metrics not found in workspace.\")\n return None\n auxholder = self.dataset.auxiliary_data.StationMetrics\n station_path = format_nslit(streams[0][0].stats, streams[0].get_inst(), eventid)\n if top in auxholder:\n tauxholder = auxholder[top]\n if station_path not in tauxholder:\n logging.warning(\n \"Stream path (%s) not in StationMetrics auxiliary_data.\"\n % station_path\n )\n return\n\n bytelist = tauxholder[station_path].data[:].tolist()\n xml_station = \"\".join([chr(b) for b in bytelist])\n xml_station = xml_station.encode(\"utf-8\")\n else:\n return\n\n summary = StationSummary.from_xml(xml_stream, xml_station)\n return summary\n\n def summarizeLabels(self):\n \"\"\"\n Summarize the processing metadata associated with each label in the\n file.\n\n Returns:\n DataFrame:\n Pandas DataFrame with columns:\n - Label Processing label.\n - UserID user id (i.e., jsmith)\n - UserName Full user name (i.e., Jane Smith) (optional)\n - UserEmail Email adress (i.e., jsmith@awesome.org)\n (optional)\n - Software Name of processing software (i.e., gmprocess)\n - Version Version of software (i.e., 1.4)\n\n \"\"\"\n provtags = self.dataset.provenance.list()\n cols = [\"Label\", \"UserID\", \"UserName\", \"UserEmail\", \"Software\", \"Version\"]\n df = pd.DataFrame(columns=cols, index=None)\n labels = list(set([ptag.split(\"_\")[-1] for ptag in provtags]))\n labeldict = {}\n for label in labels:\n for ptag in provtags:\n if label in ptag:\n labeldict[label] = ptag\n for label, ptag in labeldict.items():\n row = pd.Series(index=cols, dtype=object)\n row[\"Label\"] = label\n provdoc = self.dataset.provenance[ptag]\n user, software = _get_agents(provdoc)\n row[\"UserID\"] = user[\"id\"]\n row[\"UserName\"] = user[\"name\"]\n row[\"UserEmail\"] = user[\"email\"]\n row[\"Software\"] = software[\"name\"]\n row[\"Version\"] = software[\"version\"]\n df = df.append(row, ignore_index=True)\n\n return df\n\n def getInventory(self, eventid):\n \"\"\"Get an Obspy Inventory object from the ASDF file.\n\n Args:\n eventid (str): ID of event to search for in ASDF file.\n\n Returns:\n Inventory: Obspy inventory object capturing all of the\n networks, stations, and channels contained in file.\n \"\"\"\n inventory = None\n for waveform in self.dataset.waveforms:\n tinv = waveform.StationXML\n if inventory is None:\n inventory = tinv\n else:\n net1 = inventory.networks[0]\n net2 = tinv.networks[0]\n if net1.code == net2.code:\n for sta in net2.stations:\n net1.stations.append(copy.deepcopy(sta))\n else:\n inventory.networks.append(copy.deepcopy(net2))\n\n return inventory\n\n def hasEvent(self, eventid):\n \"\"\"Verify that the workspace file contains an event matching eventid.\n\n Args:\n eventid (str):\n ID of event to search for in ASDF file.\n\n Returns:\n bool: True if event matching ID is found, False if not.\n \"\"\"\n for event in self.dataset.events:\n if event.resource_id.id.find(eventid) > -1:\n return True\n return False\n\n def getEvent(self, eventid):\n \"\"\"Get a ScalarEvent object from the ASDF file.\n\n Args:\n eventid (str):\n ID of event to search for in ASDF file.\n\n Returns:\n ScalarEvent:\n Flattened version of Obspy Event object.\n \"\"\"\n eventobj = None\n for event in self.dataset.events:\n if event.resource_id.id.find(eventid) > -1:\n eventobj = event\n break\n eventobj2 = ScalarEvent.fromEvent(eventobj) if eventobj else None\n return eventobj2\n\n def getProvenance(self, eventid, stations=None, labels=None):\n \"\"\"Return DataFrame with processing history matching input criteria.\n\n Output will look like this:\n Record Processing Step Step Attribute Attribute Value\n 0 NZ.HSES.HN1 Remove Response input_units counts\n 1 NZ.HSES.HN1 Remove Response output_units cm/s^2\n 2 NZ.HSES.HN1 Detrend detrending_method linear\n 3 NZ.HSES.HN1 Detrend detrending_method demean\n 4 NZ.HSES.HN1 Cut new_end_time 2016-11-13T11:05:44.000000Z\n 5 NZ.HSES.HN1 Cut new_start_time 2016-11-13T11:02:58.000000Z\n 6 NZ.HSES.HN1 Taper side both\n 7 NZ.HSES.HN1 Taper taper_width 0.05\n 8 NZ.HSES.HN1 Taper window_type Hann\n ...\n\n Args:\n eventid (str):\n Event ID corresponding to an Event in the workspace.\n stations (list):\n List of stations to search for.\n labels (list):\n List of processing labels to search for.\n\n Returns:\n DataFrame:\n Table of processing steps/parameters (see above).\n\n \"\"\"\n if stations is None:\n stations = self.getStations()\n if labels is None:\n labels = self.getLabels()\n cols = [\"Record\", \"Processing Step\", \"Step Attribute\", \"Attribute Value\"]\n df_dicts = []\n for provname in self.dataset.provenance.list():\n has_station = False\n for station in stations:\n if station in provname:\n has_station = True\n break\n has_label = False\n for label in labels:\n if label in provname:\n has_label = True\n break\n if not has_label or not has_station:\n continue\n\n provdoc = self.dataset.provenance[provname]\n serial = json.loads(provdoc.serialize())\n for activity, attrs in serial[\"activity\"].items():\n pstep = None\n for key, value in attrs.items():\n if key == \"prov:label\":\n pstep = value\n continue\n if key == \"prov:type\":\n continue\n if not isinstance(value, str):\n if value[\"type\"] == \"xsd:dateTime\":\n value = UTCDateTime(value[\"$\"])\n elif value[\"type\"] == \"xsd:double\":\n value = float(value[\"$\"])\n elif value[\"type\"] == \"xsd:int\":\n value = int(value[\"$\"])\n else:\n pass\n attrkey = key.replace(\"seis_prov:\", \"\")\n row = pd.Series(index=cols, dtype=object)\n row[\"Record\"] = provname\n row[\"Processing Step\"] = pstep\n row[\"Step Attribute\"] = attrkey\n row[\"Attribute Value\"] = value\n df_dicts.append(row)\n\n df = pd.DataFrame.from_dict(df_dicts)\n df = df[cols]\n\n return df\n\n\ndef _stringify_dict(indict):\n for key, value in indict.items():\n if isinstance(value, UTCDateTime):\n indict[key] = value.strftime(TIMEFMT_MS)\n elif isinstance(value, bytes):\n indict[key] = value.decode(\"utf-8\")\n elif isinstance(value, dict):\n indict[key] = _stringify_dict(value)\n return indict\n\n\ndef _get_id(event):\n eid = event.origins[0].resource_id.id\n return eid\n\n\ndef _get_agents(provdoc):\n software = {}\n person = {}\n jdict = json.loads(provdoc.serialize())\n for key, value in jdict[\"agent\"].items():\n is_person = re.search(\"sp[0-9]{3}_pp\", key) is not None\n is_software = re.search(\"sp[0-9]{3}_sa\", key) is not None\n if is_person:\n person[\"id\"] = value[\"prov:label\"]\n if \"seis_prov:email\" in value:\n person[\"email\"] = value[\"seis_prov:email\"]\n if \"seis_prov:name\" in value:\n person[\"name\"] = value[\"seis_prov:name\"]\n elif is_software:\n software[\"name\"] = value[\"seis_prov:software_name\"]\n software[\"version\"] = value[\"seis_prov:software_version\"]\n else:\n pass\n\n if \"name\" not in person:\n person[\"name\"] = \"\"\n if \"email\" not in person:\n person[\"email\"] = \"\"\n return (person, software)\n\n\ndef _natural_keys(text):\n \"\"\"\n Helper function for sorting IMT list. This is needed because using the\n plain .sort() will put SA(10.0) before SA(2.0), for example.\n \"\"\"\n return [_atof(c) for c in re.split(r\"[+-]?([0-9]+(?:[.][0-9]*)?|[.][0-9]+)\", text)]\n\n\ndef _atof(text):\n try:\n retval = float(text)\n except ValueError:\n retval = text\n return retval\n\n\ndef camel_case_split(identifier):\n matches = re.finditer(\n \".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)\", identifier\n )\n return [m.group(0) for m in matches]\n","sub_path":"gmprocess/io/asdf/stream_workspace.py","file_name":"stream_workspace.py","file_ext":"py","file_size_in_byte":57262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"482819246","text":"import os\nimport json\nfrom moto import mock_s3\n\nfrom gbdx_cloud_harness.test.conftest import my_vcr\nfrom gbdx_cloud_harness.workflow import Workflow\n\n\ndef test_json_build(TestApp, mock_auth):\n mock = mock_s3()\n mock.start()\n\n TestApp.task.run_name = 'Workflow_test'\n wf_obj = Workflow(TestApp.task, auth=mock_auth)\n wf_json = wf_obj.json\n\n tasks = wf_json['tasks']\n\n assert len(tasks) == 2\n\n custom_task_name = None\n custom_task_output_name = None\n\n for task in tasks:\n\n if task['taskType'] == 'CloudHarness_Anonymous_Task':\n inputs = task['inputs']\n outputs = task['outputs']\n assert len(inputs), 3\n assert len(outputs), 1\n custom_task_name = task['name']\n custom_task_output_name = [p['name'] for p in task['outputs']][0]\n elif task['taskType'] == 'StageDataToS3':\n inputs = task['inputs']\n assert len(inputs), 2\n\n parsed_s3_loc = [x['value'].split('/')[2:] for x in inputs if x['name'] == 'destination'][0]\n exp_names = ['bckt_not_provided', 'pre_not_provided', 'Workflow_test', 'output_port']\n assert exp_names == parsed_s3_loc\n\n parsed_source = [x['source'].split(':') for x in inputs if x['name'] == 'data'][0]\n assert parsed_source[0] == custom_task_name\n assert custom_task_output_name.endswith(parsed_source[1])\n else:\n assert False # Fail test\n\n mock.stop()\n\n\n@my_vcr.use_cassette('gbdx_cloud_harness/test/vcr_cassettes/workflow.yaml', filter_headers=['authorization'])\ndef test_execute_workflow(TestApp, test_path, mock_auth):\n mock = mock_s3()\n mock.start()\n\n test_wf_file = os.path.join(test_path, 'test_valid_wf.json')\n\n vcr_filename = os.path.join(\n test_path, 'vcr_cassettes', 'workflow.yaml'\n )\n\n if os.path.isfile(vcr_filename):\n wf_obj = Workflow(TestApp.task, auth=mock_auth)\n else:\n wf_obj = Workflow(TestApp.task)\n\n with open(test_wf_file, 'r') as f:\n wf_json = f.read()\n print(wf_json)\n wf_obj.execute(override_wf_json=json.loads(wf_json))\n\n assert wf_obj.id is not None\n assert isinstance(int(wf_obj.id), int)\n assert wf_obj.status['state'] == 'pending'\n assert wf_obj.status['event'] == 'submitted'\n\n assert wf_obj.succeeded is False\n assert wf_obj.complete is False\n\n wf_obj.id = '4392617339332738708' # A completed workflow\n wf_obj._refresh_status()\n\n assert wf_obj.succeeded is True\n assert wf_obj.complete is True\n\n mock.stop()\n","sub_path":"gbdx_cloud_harness/test/test_workflow.py","file_name":"test_workflow.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"529946242","text":"# ski_math/urls.py\nfrom django.urls import path\n\nfrom . import views\nfrom django.views.generic.base import TemplateView\n\n\nurlpatterns = [\n path('signup/', views.SignUp.as_view(), name='signup'),\n path('game/', views.GameView.as_view(), name='game'),\n path('stats/', views.Stats.as_view(), name='stats'),\n path('studentsignup/', views.studentSignUp.as_view(), name='studentsignup'),\n path('teacherstats', views.TeacherStats.as_view(), name='teacherstats'),\n path('game/playerhistory/', views.PlayerHistory, name='playerhistory'),\n path('game/ski_math/writeplayer', views.WriteHistory, name='writeplayer'),\n path('certificate/', views.Certificate, name='certificate')\n]","sub_path":"ski_math/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"622518604","text":"from __future__ import unicode_literals\nfrom django import template\n\nfrom django.contrib.admin.views.main import SEARCH_VAR\n\nregister = template.Library()\n\n\ndef advanced_search_form(context, cl):\n \"\"\"\n Displays a search form for searching the list.\n \"\"\"\n form = context.get('asf')\n form = form(data=context.get('my_request_get'))\n return {\n 'asf': form,\n 'cl': cl,\n 'request': context.get('request', ''),\n 'panel': context.get('panel', ''),\n 'show_result_count': cl.result_count != cl.full_result_count,\n 'search_var': SEARCH_VAR\n }\n\n\n@register.inclusion_tag('admin/presupuestos/presupuesto/presupuesto_search_form.html', takes_context=True)\ndef presupuesto_search_form(context, cl):\n return advanced_search_form(context, cl)\n\n\n@register.filter\ndef eliminar_separador_miles(numero):\n numero_str = str(numero)\n return numero_str","sub_path":"presupuestos/templatetags/presupuesto_tags.py","file_name":"presupuesto_tags.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"429206819","text":"from pyramid.decorator import reify\nfrom pyramid_sockjs import json\nfrom pyramid_jca import protocol, handler, Form, Component\n\nimport ptah\nfrom ptah.settings import ID_SETTINGS_GROUP, SettingRecord\n\nimport ptah_ws\n\n\n@protocol('settings')\nclass SettingsComponent(Component):\n\n def get_info(self, name):\n group = ptah.get_cfg_storage(ID_SETTINGS_GROUP, self.registry)[name]\n\n schema = []\n for field in group.__fields__.values():\n if getattr(field, 'tint', False):\n value = '* * * * * * *'\n else:\n value = field.dumps(group[field.name])\n\n schema.append(\n ({'name': '{0}.{1}'.format(name, field.name),\n 'type': field.__class__.__name__,\n 'value': value,\n 'title': field.title,\n 'description': field.description,\n 'default': field.dumps(field.default)}))\n\n return {'title': group.__title__ or name,\n 'description': group.__description__,\n 'schema': schema,\n 'name': group.__name__,\n 'ttw': group.__ttw__}\n\n def msg_init(self, data):\n self.send('list', {'settings': {'ptah-ws':self.get_info('ptah-ws'),\n 'ptah_crowd': self.get_info('ptah_crowd'),\n }})\n\n@handler('group_edit', SettingsComponent)\nclass GroupEditForm(Form):\n\n @property\n def label(self):\n return 'Modify settings: %s'%self.title\n\n def form_content(self):\n return self.context\n\n def update(self):\n grp = ptah.get_settings(self.params['__group__'], self.request.registry)\n\n self.context = grp\n self.title = grp.__title__\n self.description = grp.__description__\n self.fields = grp.__fields__.omit(*grp.__ttw_skip_fields__)\n\n super(GroupEditForm, self).update()\n\n @ptah.form.button('Cancel', name='close')\n def on_cancel(self):\n pass\n\n @ptah.form.button('change settings', name='submit', actype=ptah.form.AC_PRIMARY)\n def modify_handler(self):\n data, errors = self.extract()\n if errors:\n self.errors = errors\n return\n\n with ptah_ws.get_session():\n self.context.updatedb(**data)\n\n self.close(\"Settings have been modified.\")\n self.component.broadcast(\n 'updated', self.component.get_info(self.context.__name__))\n","sub_path":"ptah_ws/ptah_ws/jssettings.py","file_name":"jssettings.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"344610944","text":"import pytest\nimport os.path\nimport requests\nimport json\nfrom click.testing import CliRunner\nfrom unittest.mock import MagicMock\nfrom tokens import InvalidCredentialsError\n\nfrom lizzy_client.cli import main, fetch_token\nfrom lizzy_client.version import VERSION, MAJOR_VERSION, MINOR_VERSION\n\ntest_dir = os.path.dirname(__file__)\nconfig_path = os.path.join(test_dir, 'test_config.yaml')\n\nFAKE_ENV = {'OAUTH2_ACCESS_TOKEN_URL': 'oauth.example.com',\n 'LIZZY_URL': 'lizzy.example.com'}\n\n\nclass FakeLizzy:\n final_state = 'CF:CREATE_COMPLETE'\n raise_exception = False\n\n def __init__(self, base_url: str, access_token: str):\n ...\n\n @classmethod\n def reset(cls):\n cls.final_state = 'CF:CREATE_COMPLETE'\n cls.raise_exception = False\n\n def delete(self, stack_id):\n ...\n\n def new_stack(self, image_version, keep_stacks, traffic, definition,\n stack_version, app_version, disable_rollback, parameters):\n assert isinstance(traffic, int)\n if self.raise_exception:\n raise requests.HTTPError('404 Not Found')\n else:\n return '57ACC1D'\n\n def traffic(self, stack_id, percentage):\n ...\n\n def wait_for_deployment(self, stack_id: str) -> [str]:\n return ['CF:WAITING', self.final_state]\n\n def get_stacks(self) -> list:\n stack1 = {'stack_name': 'stack1',\n 'stack_version': '42',\n 'image_version': 'd42',\n 'status': 'CF:CREATE_COMPLETE',\n 'creation_time': '2016-01-01T12:00:00Z'}\n\n stack2 = {'stack_name': 'stack2',\n 'stack_version': '42',\n 'image_version': 'd42',\n 'status': 'CF:TEST',\n 'creation_time': '2015-12-01T12:00:00Z'}\n\n stack3 = {'stack_name': 'stack2',\n 'stack_version': '42',\n 'image_version': 'd42',\n 'status': 'LIZZY:REMOVED',\n 'creation_time': '2015-12-01T12:00:00Z'}\n if self.raise_exception:\n raise requests.HTTPError('404 Not Found')\n else:\n return [stack1, stack2, stack3]\n\n\n@pytest.fixture\ndef mock_get_token(monkeypatch):\n mock = MagicMock()\n mock.return_value = '4CC3557OCC3N'\n monkeypatch.setattr('lizzy_client.cli.get_token', mock)\n return mock\n\n\n@pytest.fixture\ndef mock_fake_lizzy(monkeypatch):\n FakeLizzy.reset()\n monkeypatch.setattr('lizzy_client.cli.Lizzy', FakeLizzy)\n return FakeLizzy\n\n\ndef test_fetch_token(mock_get_token):\n token = fetch_token('https://example.com', ['scope'], credentials_dir='/meta/credentials')\n\n assert token == '4CC3557OCC3N'\n\n mock_get_token.side_effect = InvalidCredentialsError('Error')\n\n with pytest.raises(SystemExit) as exc_info: # type: py.code.ExceptionInfo\n fetch_token('https://example.com', ['scope'], credentials_dir='/meta/credentials')\n\n exception = exc_info.value\n assert repr(exception) == 'SystemExit(1,)'\n\n\ndef test_create(mock_get_token, mock_fake_lizzy):\n runner = CliRunner()\n result = runner.invoke(main, ['create', config_path, '1.0'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Fetching authentication token.. . OK' in result.output\n assert 'Requesting new stack.. OK' in result.output\n assert 'Stack ID: 57ACC1D' in result.output\n assert 'Waiting for new stack... . . OK' in result.output\n assert 'Deployment Successful' in result.output\n\n result = runner.invoke(main, ['create', '-v', config_path, '1.0'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Fetching authentication token.. . OK' in result.output\n assert 'Requesting new stack.. OK' in result.output\n assert 'Stack ID: 57ACC1D' in result.output\n assert 'Waiting for new stack...\\n' in result.output\n assert 'CF:WAITING' in result.output\n assert 'CF:CREATE_COMPLETE' in result.output\n assert 'Deployment Successful' in result.output\n\n FakeLizzy.final_state = 'CF:ROLLBACK_COMPLETE'\n result = runner.invoke(main, ['create', '-v', config_path, '1.0'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Stack was rollback after deployment. Check you application log for possible reasons.' in result.output\n\n FakeLizzy.final_state = 'LIZZY:REMOVED'\n result = runner.invoke(main, ['create', '-v', config_path, '1.0'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Stack was removed before deployment finished.' in result.output\n\n FakeLizzy.final_state = 'CF:CREATE_FAILED'\n result = runner.invoke(main, ['create', '-v', config_path, '1.0'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Deployment failed: CF:CREATE_FAILED' in result.output\n\n FakeLizzy.reset()\n FakeLizzy.raise_exception = True\n result = runner.invoke(main, ['create', '-v', config_path, '1.0'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Deployment failed: 404 Not Found' in result.output\n\n\ndef test_delete(mock_get_token, mock_fake_lizzy):\n runner = CliRunner()\n result = runner.invoke(main, ['delete', 'lizzy-test', '1.0'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Requesting stack deletion.. OK' in result.output\n\n\ndef test_traffic(mock_get_token, mock_fake_lizzy):\n runner = CliRunner()\n result = runner.invoke(main, ['traffic', 'lizzy-test', '1.0', '90'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Requesting traffic change.. OK' in result.output\n\n\ndef test_version():\n runner = CliRunner()\n result = runner.invoke(main, ['version'], env=FAKE_ENV, catch_exceptions=False)\n for version_segment in (VERSION, MAJOR_VERSION, MINOR_VERSION):\n assert str(version_segment) in result.output\n\n\ndef test_list(mock_get_token, mock_fake_lizzy):\n stack1 = {'stack_name': 'stack1',\n 'version': '42',\n 'image_version': 'd42',\n 'status': 'CF:CREATE_COMPLETE',\n 'creation_time': 1451649600.0}\n\n stack2 = {'stack_name': 'stack2',\n 'version': '42',\n 'image_version': 'd42',\n 'status': 'CF:TEST',\n 'creation_time': 1448971200.0}\n\n stack3 = {'stack_name': 'stack2',\n 'version': '42',\n 'image_version': 'd42',\n 'status': 'LIZZY:REMOVED',\n 'creation_time': 1448971200.0}\n\n runner = CliRunner()\n regular_list_result = runner.invoke(main, ['list', '-o', 'json'], env=FAKE_ENV, catch_exceptions=False)\n str_json = regular_list_result.output.splitlines()[-1] # type: str\n regular_list = json.loads(str_json) # type: list\n assert regular_list == [stack1, stack2]\n\n runner = CliRunner()\n all_list_result = runner.invoke(main, ['list', '--all', '-o', 'json'], env=FAKE_ENV, catch_exceptions=False)\n str_json = all_list_result.output.splitlines()[-1] # type: str\n all_list = json.loads(str_json) # type: list\n assert all_list == [stack1, stack2, stack3]\n\n runner = CliRunner()\n stack1_list_result = runner.invoke(main, ['list', '--all', '-o', 'json', 'stack1'], env=FAKE_ENV,\n catch_exceptions=False)\n str_json = stack1_list_result.output.splitlines()[-1] # type: str\n stack1_list = json.loads(str_json) # type: list\n assert stack1_list == [stack1]\n\n FakeLizzy.raise_exception = True\n result = runner.invoke(main, ['list', '-o', 'json'], env=FAKE_ENV, catch_exceptions=False)\n assert 'Failed to get stacks: 404 Not Found' in result.output\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":7442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"477658577","text":"# Copyright (C) 2017 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\n\"\"\"Contains the Assignable mixin.\n\nThis allows adding various assignee types to the object, like Verifier,\nCreator, etc.\n\"\"\"\n\nimport sqlalchemy as sa\n\nfrom ggrc import db\nfrom ggrc.models import person\nfrom ggrc.models import relationship\nfrom ggrc.models import reflection\n\n\nclass Assignable(object):\n \"\"\"Mixin for models with assignees\"\"\"\n\n ASSIGNEE_TYPES = set([\"Assignee\"])\n\n _api_attrs = reflection.ApiAttributes(\n reflection.Attribute(\"assignees\", create=False, update=False),\n )\n\n _custom_publish = {\n \"assignees\": lambda obj: obj.publish_assignees(),\n }\n\n @property\n def assignees(self):\n \"\"\"Property that returns assignees\n\n Returns:\n A set of assignees.\n \"\"\"\n assignees_map = self._get_assignees_map()\n assignees = [\n (assignees_map[r.source_id],\n tuple(set(r.attrs[\"AssigneeType\"].split(\",\"))))\n for r in self.related_sources\n if \"AssigneeType\" in r.attrs\n ]\n assignees += [\n (assignees_map[r.destination_id],\n tuple(set(r.attrs[\"AssigneeType\"].split(\",\"))))\n for r in self.related_destinations\n if \"AssigneeType\" in r.attrs\n ]\n return assignees\n\n @property\n def assignees_by_type(self):\n \"\"\"Property that returns assignees.\n\n Returns:\n a dict with keys equal to assignee types and values equal to list of\n Person objects of assignees of this type; for instance:\n {\"Creator\": [, ],\n \"Assessor\": []}\n \"\"\"\n assignees_map = self._get_assignees_map()\n\n def get_roles(rel):\n return set(rel.attrs.get(\"AssigneeType\", \"\").split(\",\"))\n\n result = {}\n result_inverse = {\n assignees_map[r.source_id]: get_roles(r)\n for r in self.related_sources\n if r.source_type == \"Person\"\n }\n result_inverse.update({\n assignees_map[r.destination_id]: get_roles(r)\n for r in self.related_destinations\n if r.destination_type == \"Person\"\n })\n\n for assignee, roles in result_inverse.items():\n for role in roles:\n result[role] = result.get(role, []) + [assignee]\n\n return result\n\n def publish_assignees(self):\n \"\"\"Serialize assignees to json.\n\n Transforms the value of assignees_by_type property to basic structures\n (lists and dicts) that are easily represented in json.\n The people lists are sorted by names or emails.\n\n Returns:\n a dict with keys equal to assignee types and values equal to list of\n serialized assignees of this type; for instance:\n {\"Creator\": [{\"id\": 1, \"name\": \"Aaron\", \"email\": \"aaron@example.com\"},\n {\"id\": 2, \"name\": None, \"email\": \"noname@example.com\"}],\n \"Assessor\": [{\"id\": 2, \"name\": None, \"email\": \"noname@example.com\"}]}\n \"\"\"\n return {\n role: [person.log_json_base() for person in\n sorted(people, key=lambda p: (p.name or p.email).lower())]\n for role, people in self.assignees_by_type.items()\n }\n\n @classmethod\n def eager_query(cls):\n query = super(Assignable, cls).eager_query()\n return query.options(\n sa.orm.subqueryload(\"_assignees\").undefer_group(\"Person_complete\"),\n )\n\n @classmethod\n def indexed_query(cls):\n query = super(Assignable, cls).indexed_query()\n return query.options(\n sa.orm.subqueryload(\n \"_assignees\"\n ).load_only(\n \"id\",\n \"name\",\n \"email\",\n ),\n sa.orm.subqueryload(\n \"related_sources\"\n ).load_only(\n \"id\",\n \"source_type\",\n \"source_id\"\n ),\n sa.orm.subqueryload(\n \"related_sources\"\n ).joinedload(\n \"relationship_attrs\"\n ).load_only(\n \"attr_value\",\n \"attr_name\",\n \"id\",\n \"relationship_id\",\n ),\n sa.orm.subqueryload(\n \"related_destinations\"\n ).load_only(\n \"id\",\n \"destination_type\",\n \"destination_id\",\n ),\n sa.orm.subqueryload(\n \"related_destinations\"\n ).joinedload(\n \"relationship_attrs\"\n ).load_only(\n \"attr_value\",\n \"attr_name\",\n \"id\",\n \"relationship_id\",\n ),\n )\n\n @sa.ext.declarative.declared_attr\n def _assignees(self):\n \"\"\"Attribute that is used to load all assigned People eagerly.\"\"\"\n rel = relationship.Relationship\n\n assignee_id = sa.case(\n [(rel.destination_type == person.Person.__name__,\n rel.destination_id)],\n else_=rel.source_id,\n )\n assignable_id = sa.case(\n [(rel.destination_type == person.Person.__name__,\n rel.source_id)],\n else_=rel.destination_id,\n )\n\n return db.relationship(\n person.Person,\n primaryjoin=lambda: self.id == assignable_id,\n secondary=rel.__table__,\n secondaryjoin=lambda: person.Person.id == assignee_id,\n viewonly=True,\n )\n\n def _get_assignees_map(self):\n \"\"\"Get a dict from Assignee id to Assignee object.\n\n This method uses eagerly-loaded _assignees property and does not result in\n additional DB calls.\n \"\"\"\n # pylint: disable=not-an-iterable\n return {person.id: person for person in self._assignees}\n\n @staticmethod\n def _validate_relationship_attr(class_, source, dest, existing, name, value):\n \"\"\"Validator that allows Assignable relationship attributes\n\n Allow relationship attribute of name \"AssigneeType\" with value that is a\n comma separated list of valid roles (as defined in target class).\n\n Args:\n class_ (class): target class of this mixin. Think of this like a class\n method.\n source (model instance): relevant relationship source\n dest (model instance): relevant relationship destinations\n existing (dict): current attributes on the relationship\n name (string): attribute name\n value (any): attribute value. Should be string for the right attribute\n\n Returns:\n New attribute value (merge with existing roles) or None if the\n attribute is not valid.\n \"\"\"\n if set([source.type, dest.type]) != set([class_.__name__, \"Person\"]):\n return None\n if name != \"AssigneeType\":\n return None\n new_roles = value.split(\",\")\n if not all(role in class_.ASSIGNEE_TYPES for role in new_roles):\n return None\n roles = set(existing.get(name, \"\").split(\",\")) | set(new_roles)\n return \",\".join(role for role in roles if role)\n\n @classmethod\n def _get_relate_filter(cls, predicate, related_type):\n \"\"\"Used for filtering by related_assignee.\n\n Returns:\n Boolean stating whether such an assignee exists.\n \"\"\"\n # pylint: disable=invalid-name\n # The upper case variables are allowed here to shorthand the class names.\n Rel = relationship.Relationship\n RelAttr = relationship.RelationshipAttr\n Person = person.Person\n return db.session.query(Rel).join(RelAttr).join(\n Person,\n sa.or_(sa.and_(\n Rel.source_id == Person.id,\n Rel.source_type == Person.__name__\n ), sa.and_(\n Rel.destination_id == Person.id,\n Rel.destination_type == Person.__name__\n ))\n ).filter(sa.and_(\n RelAttr.attr_value.contains(related_type),\n RelAttr.attr_name == \"AssigneeType\",\n sa.or_(sa.and_(\n Rel.source_type == Person.__name__,\n Rel.destination_type == cls.__name__,\n Rel.destination_id == cls.id\n ), sa.and_(\n Rel.destination_type == Person.__name__,\n Rel.source_type == cls.__name__,\n Rel.source_id == cls.id\n )),\n sa.or_(predicate(Person.name), predicate(Person.email))\n )).exists()\n","sub_path":"src/ggrc/models/mixins/assignable.py","file_name":"assignable.py","file_ext":"py","file_size_in_byte":7870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"34063410","text":"import pickle\nimport sys\nfrom classes import Item\nfrom classes import Usuario\nfrom classes import Puntuacion\nfrom classes import Item_historico\nfrom classes import Item_recomendado\nimport random\nwith open('config/config.items', 'rb') as config_dictionary_file:\n lista_items = pickle.load(config_dictionary_file)\nconfig_dictionary_file.close()\n\nwith open('config/config.puntuaciones', 'rb') as config_dictionary_file:\n lista_puntuaciones = pickle.load(config_dictionary_file)\nconfig_dictionary_file.close()\n\nwith open('config/config.usuarios', 'rb') as config_dictionary_file:\n lista_usuarios = pickle.load(config_dictionary_file)\nconfig_dictionary_file.close()\n\nprint(\"Carga de Data completada\")\n\n\n\ndef recomendador_cola(usuario):\n from poblar_datos import check_vecinos\n check_vecinos(usuario, lista_usuarios)\n vecinos = usuario.ids_vecinos\n item_historico = usuario.item_historico\n if item_historico == None:\n item_historico = []\n pref_col = usuario.preferencias_colaborativas\n\n recomendaciones = []\n for id in vecinos:\n for p in lista_puntuaciones:\n if p.id_user == id and p.ratio == 5:\n if p.id_item not in recomendaciones:\n recomendaciones.append(p.id_item)\n peliculas_vistas = []\n for i in item_historico:\n peliculas_vistas.append(i.id_item)\n\n peliculas_no_vistas = []\n for n in recomendaciones:\n if n not in peliculas_vistas:\n peliculas_no_vistas.append(n)\n\n peliculas = []\n\n for peli in peliculas_no_vistas:\n for item in lista_items:\n cont = 0\n if peli == item.id_item:\n titulo = item.titulo\n ratio = item.ratio\n ratio = [i * 100 for i in ratio]\n for i in range(len(ratio)):\n if ratio[i] != 0 and pref_col[i] != 0 and pref_col[i] >=30:\n cont += ratio[i] - pref_col[i]\n cont += 1\n if cont != 0:\n peliculas.append([titulo, cont])\n\n peliculas = sorted(peliculas, key=lambda x: x[1])\n return peliculas\n\ndef recomendador_demo(user):\n ya_vistas = user.item_historico\n if ya_vistas == None:\n ya_vistas = []\n rec = user.preferencias_demograficas\n #print(user.preferencias_demograficas)\n lista_recomendacion = []\n for pelicula in lista_items:\n titulo = pelicula.titulo\n ratio = pelicula.ratio\n aux_pelicula = [i * 100 for i in ratio]\n cont = 0\n for i in range(len(ratio)):\n if aux_pelicula[i] != 0 and rec[i] != 0:\n cont += aux_pelicula[i] - rec[i]\n cont += 1\n\n recomendado = Item_recomendado(titulo, pelicula.id_item, cont)\n lista_recomendacion.append(recomendado)\n\n recomendacion = []\n\n for x in lista_recomendacion:\n aux = True\n for i in ya_vistas:\n if x.id_item == i.id_item:\n #print(\"La pelicula + \" + str(x.titulo) + \" ya ha sido vista por el usuario\")\n aux = False\n if aux and x.ratio != 0:\n recomendacion.append([x.titulo, x.ratio])\n\n\n\n recomendacion.sort(key=lambda recomendacion : recomendacion[1])\n return recomendacion\n\ndef rec_hibrido(usuario):\n col = recomendador_cola(usuario)\n dem = recomendador_demo(usuario)\n print(col)\n print(dem)\n recomendacion = []\n\n for c in col:\n aux = True\n for d in dem:\n if c[0] == d[0]:\n recomendacion.append([c[0], c[1]+d[1]])\n aux = False\n if aux:\n recomendacion.append(c)\n\n recomendacion.sort(key=lambda re: re[1])\n\n rec_rand1 = recomendacion[random.randint(0, len(recomendacion)-1)]\n rec_rand2 = recomendacion[random.randint(0, len(recomendacion)-1)]\n\n while rec_rand1 == rec_rand2 or rec_rand1 == rec_rand2 == recomendacion[0][0] \\\n or rec_rand1 == rec_rand2 == recomendacion[1][0] or rec_rand1 == rec_rand2 == recomendacion[2][0] \\\n or rec_rand1 == rec_rand2 == recomendacion[3][0]:\n rec_rand1 = recomendacion[random.randint(0, len(recomendacion)-1)]\n rec_rand2 = recomendacion[random.randint(0, len(recomendacion)-1)]\n\n return recomendacion[0], recomendacion[1], recomendacion[2], rec_rand1, rec_rand2\n","sub_path":"Cuatrimestre3/AIWR/recomendador_conInterfaz/rec_hibrido.py","file_name":"rec_hibrido.py","file_ext":"py","file_size_in_byte":4323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"73983276","text":"# これまでの学習内容を元に、お買い物代金を計算しよう\n\n# apple_priceという変数に数値200を代入してください\napple_price = 200\n\n# countという変数に数値5を代入してください\ncount = 5\n\n# total_priceという変数に、apple_priceとcountを掛けたものを代入してください\ntotal_price = apple_price * count\n\n# 「購入するりんごの個数は○ ○ 個です」となるように出力してください(個数はどの変数に代入したでしょう?)\nprint('購入するりんごの個数は' + str(count) + '個です')\n\n# 「支払い金額は○ ○ 円です」となるように出力してください(合計金額はどの変数に代入したでしょう?)\nprint('支払い金額は' + str(total_price) + \"円です\")\n","sub_path":"src/algo-p1/task20180801_q011.py","file_name":"task20180801_q011.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"377690979","text":"# Contents subject to LICENSE.txt at project root\n\n\"\"\"\nAll metrics used in the D3M Program, mapped to their function.\n>>> from dval.metrics import apply_metric\n>>> groundtruth_file = 'test/data/185_baseball_SCORE/targets.csv'\n>>> predictions_file = 'test/data/185_baseball_SCORE/mitll_predictions.csv'\n\n>>> apply_metric('rootMeanSquaredError', groundtruth_file, predictions_file)\n0.42\n\"\"\"\n\nimport math\nfrom collections import defaultdict\n\nimport numpy as np\nimport sklearn.metrics as skm\nfrom sklearn.preprocessing import LabelBinarizer\n\nfrom dval.object_detection_ap import objectDetectionAP\n\n\ndef accuracy(ground_truth, predicted):\n return skm.accuracy_score(ground_truth, predicted)\n\n\ndef f1(ground_truth, predicted, pos_label=1):\n return skm.f1_score(ground_truth, predicted, pos_label=pos_label)\n\n\ndef f1_micro(ground_truth, predicted):\n return skm.f1_score(ground_truth, predicted, average=\"micro\")\n\n\ndef f1_macro(ground_truth, predicted):\n return skm.f1_score(ground_truth, predicted, average=\"macro\")\n\n\ndef roc_auc(ground_truth, predicted, pos_label=None):\n if pos_label is not None:\n ground_truth, predicted, _ = _binarize(ground_truth, predicted, pos_label)\n return skm.roc_auc_score(ground_truth, predicted)\n\n\ndef roc_auc_micro(ground_truth, predicted):\n ground_truth, predicted, _ = _binarize(ground_truth, predicted)\n return skm.roc_auc_score(ground_truth, predicted, average=\"micro\")\n\n\ndef roc_auc_macro(ground_truth, predicted):\n ground_truth, predicted, _ = _binarize(ground_truth, predicted)\n return skm.roc_auc_score(ground_truth, predicted, average=\"macro\")\n\n\ndef l2(ground_truth, predicted):\n return skm.mean_squared_error(ground_truth, predicted) ** 0.5\n\n\ndef avg_l2(ground_truth_l, predicted_l):\n \"\"\"\n This function takes a list of ground truth vectors and a list\n of predicted vectors and calculates the average L2 metrics between\n them.\n\n The vectors are transposed because the skm.mse(multioutputs='raw_values')\n Will compute the following:\n\n >>> import sklearn.metrics as skm\n\n >>> y_true = [[0.5, 1],[-1, 1],[7, -6]]\n >>> y_pred = [[0, 2],[-1, 2],[8, -5]]\n\n >>> skm.mean_squared_error(y_true, y_pred, multioutput='raw_values')\n array([0.41666667, 1. ])\n\n Parameters:\n -----------\n ground_truth_l: list\n List of ground truth vectors having the following shape:\n [[X1, Y1], ... , [Xn, Yn, ...]]\n\n predicted_l: list\n List of predicted vectors having the following shape:\n [[x1, y1], ... , [xn, yn, ...]]\n\n Returns:\n --------\n\n avg_l2:\n avg(sqrt(mse(X,x)), sqrt(mse(Y,y)) )\n\n \"\"\"\n\n return np.mean(\n skm.mean_squared_error(ground_truth_l, predicted_l, multioutput=\"raw_values\")\n ** 0.5\n )\n\n\ndef mean_se(ground_truth, predicted):\n return skm.mean_squared_error(ground_truth, predicted)\n\n\ndef l1(ground_truth, predicted):\n return skm.mean_absolute_error(ground_truth, predicted)\n\n\ndef r2(ground_truth, predicted):\n return skm.r2_score(ground_truth, predicted)\n\n\ndef norm_mut_info(ground_truth, predicted):\n return skm.normalized_mutual_info_score(ground_truth, predicted)\n\n\ndef jacc_sim(ground_truth, predicted):\n return skm.jaccard_similarity_score(ground_truth, predicted)\n\n\ndef _binarize(ground, pred, pos_label=None):\n \"\"\"\n Binarize a prediction according to the classes\n available in the ground truth\n\n Parameters:\n -----------\n ground: 1d array\n Array of ground truth labels.\n\n pred: 1d array\n Array of predicted labels.\n\n Returns:\n --------\n (binary_ground, binary_pred, classes): tuples\n Tuple composed of binarized ground truth, binarized predictions and associated classes.\n\n Example:\n >>> ground = [0, 1, 2, 1]\n >>> pred = [0, 0, 2, 1]\n\n binary_ground = [[1,0,0], [0,1,0], [0,0,1], [0,1,0]]\n binary_pred = [[1,0,0], [1,0,0], [0,0,1], [0,1,0]]\n classes = [0, 1, 2]\n \"\"\"\n lb = LabelBinarizer()\n binary_ground = lb.fit_transform(ground)\n classes = lb.classes_\n binary_pred = lb.transform(pred)\n\n if pos_label is not None and lb.classes_[0] == pos_label:\n return 1 - binary_ground, 1 - binary_pred, classes\n else:\n return binary_ground, binary_pred, classes\n\n\ndef precision_at_top_K_meta(gt, preds, K=20):\n def precision_at_top_K(gt, preds, K):\n \"\"\"\n This function examines the first K entries of a\n ground truth vector (gt) and predicted labels (preds)\n and determines how many values are shared between them.\n The result is then scaled by K to get the accuracy at top K.\n\n Parameters:\n -----------\n gt: 1d array-like\n Array of ground truth labels.\n\n preds: 1d array-like\n Array of predicted labels.\n\n K: int, 20 by default\n The number of samples to use when computing the accuracy.\n\n Returns:\n --------\n prec_at_top_K: float\n The number of labels shared between the ground truth and\n the predictions divided by K.\n\n\n Example:\n >>> gt = [0, 1, 2, 3, 4]\n >>> pred = [1, 3, 2, 4, 0]\n\n >>> precision_at_top_K(gt, pred, K=3)\n 0.667\n\n >>> precision_at_top_K(gt, pred, K=4)\n 0.75\n \"\"\"\n\n gt = gt[0:K]\n preds = preds[0:K]\n prec_at_top_K = np.float(len(np.intersect1d(gt, preds))) / K\n return prec_at_top_K\n\n # sort preds indice\n pred_indices = np.argsort(preds)[::-1]\n # sort gt indices\n gt_indices = np.argsort(gt)[::-1]\n\n return precision_at_top_K(gt_indices, pred_indices, K=K)\n\n\ndef precision(ground_truth, predicted):\n return skm.precision_score(ground_truth, predicted)\n\n\ndef recall(ground_truth, predicted):\n return skm.recall_score(ground_truth, predicted)\n\n\ndef mxe_non_bin(ground_truth, predicted):\n \"\"\"\n This function converts non-binarized predicted values\n and pass them to the crossEntropy function\n\n\n Parameters:\n -----------\n ground_truth: array\n Array of non-binarized vectors.\n\n predicted: array\n Array of non-binarized predicted vectors.\n\n Returns:\n --------\n cross_entropy:\n Cross entropy of the predicted values\n\n\n Example:\n >>> ground_truth = [0, 1, 2, 2, 1]\n >>> predicted = [0, 1, 2, 1, 0]\n\n bin_predicted = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 1], [0, 1, 0]]\n classes = [0, 1, 2]\n \"\"\"\n _, bin_predicted, classes = _binarize(ground_truth, predicted)\n return apply_metric(\"crossEntropy\", ground_truth, bin_predicted, classes)\n\n\ndef _normalize_ground_truth(ground_truth, classes):\n \"\"\"\n Convert the ground truth list into a list of classe indices.\n First it transforms the list of classes into a dictionary where\n the key is the class name and the value is its indice in the list.\n The order of the classes in the list is mapped to the order of the\n confidence factors in the predictions.\n Then, it replace every class value in the ground truth by its indice.\n\n Parameters:\n -----------\n ground_truth: 1d array\n Array of ground truth.\n\n classes: 1d array\n Array of the classes available in the ground truth.\n\n Return:\n -------\n ground_truth_normalized: array\n Array of class indices.\n\n Example:\n >>> ground_truth = ['val_a', 'val_c', 'val_b', 'val_c']\n >>> classes = ['val_a', 'val_b', 'val_c']\n\n ground_truth_classes = {'val_a': 0, 'val_b': 1, 'val_c': 2}\n ground_truth_normalized = [0, 2, 1, 2]\n \"\"\"\n # Build dictionary based on ground_truth classes order\n i = 0\n ground_truth_classes = {}\n for gt_class in classes:\n ground_truth_classes[gt_class] = i\n i += 1\n\n # Process the ground truth\n ground_truth_normalized = []\n for value in ground_truth:\n ground_truth_normalized.append(ground_truth_classes[value])\n return ground_truth_normalized\n\n\ndef _normalize_predicted(predicted, eps_value=2 ** -100):\n norm_predicted = []\n for trial in predicted:\n t = []\n for pd in trial:\n # Here, we convert any value less than eps_value to eps_value\n if pd == 0 or (pd < eps_value):\n pd = eps_value\n t.append(math.log(pd))\n norm_predicted.append(t)\n return norm_predicted\n\n\ndef mxe(ground_truth, predicted, classes):\n \"\"\"\n Computes the Multiclass Cross Entropy (MXE).\n\n Parameters:\n -----------\n ground_truth: 1d array\n Array of ground truth\n\n predicted: 1d array\n Array of predictions\n\n classes: 1d array\n Array of classes composing the ground truth. The order of the class values\n defines the order of prediction values.\n\n Return:\n -------\n mxe_score\n \"\"\"\n log_base = 2\n ground_truth = _normalize_ground_truth(ground_truth, classes)\n predicted = _normalize_predicted(predicted)\n class_to_trials = defaultdict(list)\n for gt, pd in zip(ground_truth, predicted):\n class_to_trials[gt].append(pd)\n numerator = 0\n for gt_cls, trials in class_to_trials.items():\n class_loss = sum(\n [\n math.log(\n sum([math.e ** (pd) for pd in trial]) / math.e ** (trial[gt_cls]),\n log_base,\n )\n for trial in trials\n ]\n )\n numerator += class_loss / len(trials)\n num_classes = len(class_to_trials)\n return numerator / num_classes\n\n\nMETRICS_DICT = {\n \"accuracy\": accuracy,\n \"f1\": f1,\n \"f1Micro\": f1_micro,\n \"f1Macro\": f1_macro,\n \"rocAuc\": roc_auc,\n \"rocAucMicro\": roc_auc_micro,\n \"rocAucMacro\": roc_auc_macro,\n \"meanSquaredError\": mean_se,\n \"rootMeanSquaredError\": l2,\n \"rootMeanSquaredErrorAvg\": avg_l2,\n \"meanAbsoluteError\": l1,\n \"rSquared\": r2,\n \"normalizedMutualInformation\": norm_mut_info,\n \"jaccardSimilarityScore\": jacc_sim,\n \"precisionAtTopK\": precision_at_top_K_meta,\n \"objectDetectionAP\": objectDetectionAP,\n \"object_detection_average_precision\": objectDetectionAP,\n \"precision\": precision,\n \"recall\": recall,\n \"crossEntropy\": mxe,\n \"crossEntropyNonBinarized\": mxe_non_bin,\n}\n\n\ndef find_metric(metric, valid_metrics=METRICS_DICT):\n def transform_string(string):\n return string.lower().replace(\"_\", \"\")\n\n reference = {transform_string(k): _ for k, _ in valid_metrics.items()}\n return reference[transform_string(metric)]\n\n\ndef valid_metric(metric):\n try:\n _ = find_metric(metric)\n except KeyError:\n return False\n return True\n\n\ndef apply_metric(metric, *args, **kwargs):\n return find_metric(metric)(*args, **kwargs)\n","sub_path":"dval/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":10759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"575431619","text":"import os\n\ntry:\n import numpy as np\n import matplotlib.pyplot as pl\n from scipy.optimize import curve_fit\nexcept ImportError:\n print(\"\"\"No module found: numpy, matplotlib and scipy modules should \n be present to run pytimbertools\"\"\")\n\nimport pytimber\nfrom .toolbox import emitnorm, exp_fit, movingaverage\n\nfrom .dataquery import set_xaxis_date\nfrom .localdate import parsedate,dumpdate\n\ndef _get_timber_data(beam,t1,t2,db=None):\n \"\"\"\n retrieve data from timber needed for\n BSRT emittance calculation\n \n Parameters:\n ----------\n db : timber database\n beam : either 'B1' or 'B2'\n t1,t2 : start and end time of extracted data in unix time\n \n Returns:\n -------\n bsrt_data: structured array with\n time = timestamp\n gate = gate delay\n sig* = beam size\n lsf* = calibration factors\n bet* = beta functions at position of BSRT\n *_time = time stamps for rarely logged \n variables, explicitly timber variables\n %LHC%BSRT%LSF_%, %LHC%BSRT%BETA% and\n LHC.BOFSU:OFC_ENERGY\n \"\"\"\n # -- some checks\n if t2 < t1:\n raise ValueError('End time smaller than start time, t2 = ' + \n '%s > %s = t1'%(t2,t1))\n # --- get data\n # timber variable names are stored in *_var variables\n # bsrt_sig and bsrt_lsf = BSRT data from timber\n # -- data extraction beam sizes + gates: \n # FIT_SIGMA_H,FIT_SIGMA_V,GATE_DELAY\n # save timber variable names\n [fit_sig_h_var, fit_sig_v_var] = db.search('%LHC%BSRT%'+beam.upper()\n +'%FIT_SIGMA_%')\n [gate_delay_var] = db.search('%LHC%BSRT%'+beam.upper()\n +'%GATE_DELAY%')\n bsrt_sig_var = [fit_sig_h_var, fit_sig_v_var, gate_delay_var]\n # extract the data from timber\n bsrt_sig = db.get(bsrt_sig_var, t1, t2)\n # check that all timestamps are the same for bsrt_sig_var\n for k in bsrt_sig_var:\n if np.any(bsrt_sig[bsrt_sig_var[0]][0] != bsrt_sig[k][0]):\n raise ValueError('Time stamps for %s and %s differ!'\n %(bsrt_sig_var[0], bsrt_sig_var[k]) + 'The data can not be' +\n ' combined')\n return\n # -- BSRT callibration factors and beam energy:\n # LSF_H,LSF_V,BETA_H,BETA_V,ENERGY\n [lsf_h_var, lsf_v_var] = db.search('%LHC%BSRT%'+beam.upper()\n +'%LSF_%')\n [beta_h_var, beta_v_var] = db.search('%LHC%BSRT%'+beam.upper()\n +'%BETA%')\n energy_var = u'LHC.BOFSU:OFC_ENERGY'\n bsrt_lsf_var = [lsf_h_var, lsf_v_var, beta_h_var, beta_v_var,\n energy_var]\n t1_lsf = t1\n bsrt_lsf = db.get(bsrt_lsf_var, t1_lsf, t2)\n # only logged rarely, loop until array is not empty, print warning\n # if time window exceeds one month\n # check that time stamp of lsf,beta,energy is before first sigma\n # timestamp\n for var in bsrt_lsf_var:\n while (bsrt_lsf[var][0].size == 0):\n if (np.abs(t1_lsf-t1) > 30*24*60*60):\n raise ValueError(('Last logging time for ' + ', %s'*5 \n + ' exceeds 1 month! Check your data!!!')%tuple(bsrt_lsf_var))\n return\n else:\n t1_lsf = t1_lsf-24*60*60\n bsrt_lsf = db.get(bsrt_lsf_var, t1_lsf, t2)\n while (bsrt_lsf[var][0][0] > bsrt_sig[bsrt_sig_var[0]][0][0]):\n if (np.abs(t1_lsf-t1) > 30*24*60*60):\n raise ValueError(('Last logging time for ' + ', %s'*5 \n + ' exceeds 1 month! Check your data!!!')%tuple(bsrt_lsf_var))\n return\n else:\n t1_lsf = t1_lsf-24*60*60\n bsrt_lsf = db.get(bsrt_lsf_var, t1_lsf, t2)\n # -- create list containing all the data (bsrt_list), then save \n # data in structured array bsrt_data\n # take timestamp from GATE_DELAY (same as for other variables)\n bsrt_list = []\n var = zip(bsrt_sig[gate_delay_var][0], bsrt_sig[gate_delay_var][1],\n bsrt_sig[fit_sig_h_var][1], bsrt_sig[fit_sig_v_var][1])\n # find closest timestamp with t_lsf=0.)[0][-1]\n lsf_time[k],lsf_value[k] = bsrt_lsf[k][0][idx],bsrt_lsf[k][1][idx]\n for i in range(len(gate)):\n bsrt_list.append(tuple([t,gate[i],sigh[i],sigv[i]]\n + [ lsf_time[k] for k in bsrt_lsf_var ]\n + [ lsf_value[k] for k in bsrt_lsf_var ]))\n ftype = [('time',float),('gate',float),('sigh',float),('sigv',float),\n ('lsfh_time',float),('lsfv_time',float),('beth_time',float),\n ('betv_time',float),('energy_time',float),('lsfh',float),\n ('lsfv',float),('beth',float),('betv',float),\n ('energy',float)]\n bsrt_data = np.array(bsrt_list,dtype=ftype)\n return bsrt_data\ndef _timber_to_emit(bsrt_array):\n \"\"\"\n returns dictionary with emittance etc. as used in BSRT.fromdb\n\n Parameters:\n -----------\n bsrt_array : data extracted from timber with _get_timber_data\n\n Returns:\n --------\n emit_dict: dictionary with emittances\n {slot: [time [s],emith [um],emitv[um],sigh[mm],sigv[mm],\n lsfh [mm], lsfv[mm], beth[mm], betv[mm],energy[GeV]]}\n \"\"\"\n # create dictionary indexed with slot number\n emit_dict = {}\n # loop over slots\n for j in set(bsrt_array['gate']):\n # data for slot j\n bsrt_slot = bsrt_array[bsrt_array['gate']==j]\n bsrt_emit = []\n # loop over all timestamps for slot j\n for tt in set(bsrt_slot['time']):\n # data for slot j and timestamp tt\n bsrt_aux = bsrt_slot[bsrt_slot['time']==tt]\n # gives back several values per timestamp -> take the mean value\n # energy [GeV]\n energy_aux = np.mean(bsrt_aux['energy'])\n sigh,lsfh,beth=bsrt_aux['sigh'],bsrt_aux['lsfh'],bsrt_aux['beth']\n sigv,lsfv,betv=bsrt_aux['sigv'],bsrt_aux['lsfv'],bsrt_aux['betv']\n # geometric emittance [um]\n emith_aux = np.mean((sigh**2-lsfh**2)/beth)\n emitv_aux = np.mean((sigv**2-lsfv**2)/betv)\n sigh,lsfh,beth = np.mean([sigh,lsfh,beth],axis=1)\n sigv,lsfv,betv = np.mean([sigv,lsfv,betv],axis=1)\n # normalized emittance\n emith = emitnorm(emith_aux, energy_aux)\n emitv = emitnorm(emitv_aux, energy_aux)\n bsrt_emit.append((tt,emith,emitv,sigh,sigv,lsfh,lsfv,\n beth,betv,energy_aux))\n # sort after the time\n emit_dict[j] = np.sort(np.array(bsrt_emit,\n dtype=[('time',float),('emith',float),('emitv',float),\n ('sigh',float),('sigv',float),\n ('lsfh',float),('lsfv',float),\n ('beth',float),('betv',float),('energy',float)]),\n axis=0)\n return emit_dict\n\nclass BSRT(object):\n \"\"\"\n class to analyze BSRT data\n Example:\n --------\n To extract the data from timber:\n\n t1=pytimber.parsedate(\"2016-08-24 00:58:00.000\")\n t2=pytimber.parsedate(\"2016-08-24 00:59:00.000\")\n bsrt=pytimber.BSRT.fromdb(t1,t2,beam='B1')\n\n Attributes:\n -----------\n timber_vars : timber variables needed to calculate\n normalized emittance\n beam : 'B1' for beam 1 or 'B2' for beam2\n t_start, t_end : start/end time of extracted data\n emit : dictionary of normalized emittances\n {slot: [time[s], emith[um], emitv[um]]}\n emitfit : dictionary of fit of normalized emittances\n between times t1 and t2\n {slot: [t1[s], t2[s], emith [um],emitv[um]]}\n\n Methods:\n --------\n get_timber_data : returns raw data from pytimber\n fromdb : create BSRT instance using the given pytimber database\n fit : make fit of BSRT emittance between timestamps t1,t2.\n Values are added to *emitfit*. \n get_fit : extract fit data for specific slot and times\n \"\"\"\n timber_vars = {}\n timber_vars['B1'] = [u'LHC.BSRT.5R4.B1:FIT_SIGMA_H', \n u'LHC.BSRT.5R4.B1:FIT_SIGMA_V', u'LHC.BSRT.5R4.B1:GATE_DELAY',\n u'LHC.BSRT.5R4.B1:LSF_H', u'LHC.BSRT.5R4.B1:LSF_V', \n u'LHC.BSRT.5R4.B1:BETA_H', u'LHC.BSRT.5R4.B1:BETA_V',\n 'LHC.BOFSU:OFC_ENERGY']\n timber_vars['B2']=[u'LHC.BSRT.5L4.B2:FIT_SIGMA_H', \n u'LHC.BSRT.5L4.B2:FIT_SIGMA_V', u'LHC.BSRT.5L4.B2:GATE_DELAY',\n u'LHC.BSRT.5L4.B2:LSF_H', u'LHC.BSRT.5L4.B2:LSF_V', \n u'LHC.BSRT.5L4.B2:BETA_H', u'LHC.BSRT.5L4.B2:BETA_V',\n 'LHC.BOFSU:OFC_ENERGY']\n def __init__(self,db=None,beam=None,emit=None,emitfit=None,t_start=None,\n t_end=None):\n self.db = db\n self.beam = beam\n self.emit = emit\n self.emitfit = emitfit\n self.t_start = t_start\n self.t_end = t_end\n @classmethod\n def fromdb(cls,t1,t2,beam='B1',db=None,verbose=False):\n \"\"\"\n retrieve data using timber and calculate normalized emittances \n from extracted values.\n Note: all values in self.emitfit are deleted\n\n Example:\n --------\n To extract the data from timber:\n\n t1=pytimber.parsedate(\"2016-08-24 00:58:00.000\")\n t2=pytimber.parsedate(\"2016-08-24 00:59:00.000\")\n bsrt=pytimber.BSRT.fromdb(t1,t2,beam='B1')\n\n Parameters:\n -----------\n db : pytimber or pagestore database\n beam : either 'B1' or 'B2'\n t1,t2 : start and end time of extracted data\n in unix time\n verbose: verbose mode, default verbose = False\n\n Returns:\n -------\n class: BSRT class instance with dictionary of normalized emittances\n stored in self.emit. self.emit is sorted after slot number\n {slot: [time [s],emith [um],emitv[um],sigh[mm],sigv[mm],\n lsfh [mm], lsfv[mm], beth[mm], betv[mm],energy[GeV]]}\n \"\"\"\n if beam not in ['B1','B2']:\n raise ValueError(\"beam = %s must be either 'B1' or 'B2'\"%beam)\n # if no database is given create dummy database to extract data\n if db is None:\n db = pytimber.LoggingDB()\n if verbose:\n print('... no database given, creating default database ' +\n 'pytimber.LoggingDB()')\n if verbose:\n print('... extracting data from timber')\n if verbose:\n print('... calculating emittance for non-empty slots')\n # -- get timber data\n bsrt_array = _get_timber_data(beam=beam,t1=t1,t2=t2,db=db)\n # -- calculate emittances, store them in \n # dictionary self.emit = emit\n emit_dict = _timber_to_emit(bsrt_array)\n return cls(db=db,emit=emit_dict,emitfit=None,\n t_start=t1,t_end=t2,beam=beam)\n def get_timber_data(self,beam,t1,t2,db=None):\n \"\"\"\n retrieve data from timber needed for\n BSRT emittance calculation\n \n Parameters:\n ----------\n db : timber database\n beam : either 'B1' or 'B2'\n t1,t2 : start and end time of extracted data in unix time\n\n Returns:\n -------\n bsrt_data: structured array with\n time = timestamp\n gate = gate delay\n sig* = beam size\n lsf* = calibration factors\n bet* = beta functions at position of BSRT\n *_time = time stamps for rarely logged \n variables, explicitly timber variables\n %LHC%BSRT%LSF_%, %LHC%BSRT%BETA% and\n LHC.BOFSU:OFC_ENERGY\n \"\"\"\n return _get_timber_data(beam=beam,t1=t1,t2=t2,db=db)\n def update_beta_lsf_energy(self,t1,t2,beth=None,betv=None,\n lsfh=None,lsfv=None,energy=None,verbose=False):\n \"\"\"\n update beta and lsf factor within t1 and t2.\n\n Parameters:\n ----------\n t1,t2: start/end time in unix time [s]\n betah,betav: hor./vert. beta function [m]\n lsfh, lsfv: hor./vert. lsf factor [mm]\n energy: beam energy [GeV]\n \"\"\"\n bsrt_array = _get_timber_data(beam=self.beam,\n t1=self.t_start,t2=self.t_end,\n db=self.db)\n # only change values between t1 and t2\n mask = np.logical_and(bsrt_array['time']>=t1,bsrt_array['time']<=t2)\n for k,v in zip(['beth','betv','lsfh','lsfv','energy'],[beth,betv,lsfh,lsfv,energy]):\n if verbose:\n print(k,'old=',bsrt_array[k][mask],'new=',v)\n if v is None:\n continue\n bsrt_array[k][mask] = v\n # -- calculate emittances, store them in \n # dictionary self.emit = emit \n self.emit = _timber_to_emit(bsrt_array)\n\n def get_fit(self,slot,t1=None,t2=None,verbose=False):\n \"\"\"\n Function to access fit values for slot *slot* between t1 and t2.\n\n Parameters:\n ----------\n slot : slot number\n t1 : start time of fit in unix time, if None start of datarange is\n used\n t2 : end time of fit in unix time, if None end of datarange is used\n verbose: verbose mode, default verbose = False\n\n Returns:\n --------\n fitdata: returns structured array with fitdata for slot *slot* and\n time interval (t1,t2) with:\n a* = amplitude ah,av [um]\n siga* = error of fit parameter ah,av [um]\n tau* = growth time tauh,tauv [s]\n sigtau* = error of growth time tauh,tauv [s]\n \"\"\"\n # -- set times\n t1,t2 = self._set_times(t1,t2,verbose)\n # -- check if values exist\n try:\n # values exist\n return self.emitfit[slot][(t1,t2)]\n except (KeyError,IndexError,TypeError):\n # values don't exist -> try to fit\n self.fit(t1=t1,t2=t2)\n try:\n return self.emitfit[slot][(t1,t2)]\n except IndexError:\n print('ERROR: Fit failed for slot %s '%slot + ' and time ' +\n 'interval (t1,t2) = (%s,%s)'%(t1,t2))\n def fit(self,t1=None,t2=None,force=False,verbose=False):\n \"\"\"\n fit the emittance between *t1* and *t2* with an exponential\n function:\n a*exp((t-t1)/tau)\n with a=initial value [um] and tau=growth time [s]\n and store values in self.emitfit. If t1=t2=None use full data \n range. Note that the fit is done with the unaveraged raw data.\n\n Parameters:\n ----------\n t1 : start time in unix time\n t2 : end time in unix time\n force : if force=True force recalculation of values\n verbose: verbose mode, default verbose = False\n\n Returns:\n --------\n self: returns class object with updated fit parameters in \n self.emitfit, where self.emitfit has the following structure:\n self.emitfit = {slot: {(t1,t2): fitdata} }\n with fitdata being a structured array with:\n a* = amplitude ah,av [um]\n siga* = error of fit parameter ah,av [um]\n tau* = growth time tauh,tauv [s]\n sigtau* = error of growth time tauh,tauv [s]\n \"\"\"\n # -- set times\n t1,t2 = self._set_times(t1,t2,verbose)\n # -- some basic checks\n # check that the data has been extracted\n if self.emit is None:\n raise StandardError(\"\"\"First extract the emittance data using \n BSRT.fromdb(beam,EGeV,t_start,t_end,db) with t_start < t1 < t2 \n < t_end.\"\"\")\n return\n # initialize self.emitfit if needed\n if self.emitfit is None:\n if verbose:\n print('... no previous fits found')\n force = True\n # initialize dictionary\n self.emitfit = {}\n for slot in self.emit.keys():\n self.emitfit[slot] = {}\n # -- start fitting \n # loop over all slots\n for slot in self.emit.keys():\n # case 1: fit data available + force = False\n try:\n if (force is False) and (self.emitfit[slot][(t1,t2)].size > 0):\n if verbose:\n print('... fit data already exists for slot %s '%(slot) + \n 'and force = False -> skip fit')\n continue\n except KeyError: # just continue and redo the fit\n if verbose:\n print('... no fit data found for slot %s '%(slot))\n pass\n # case 2: fit data not available or force = True\n try:\n if verbose:\n print('... extracting emittances for slot %s '%(slot) +\n 'from %s to %s'%(dumpdate(t1),dumpdate(t2)))\n mask = ((self.emit[slot]['time']>=t1) & \n (self.emit[slot]['time']<=t2))\n data = self.emit[slot][mask]\n # subtract initial time to make fitting easier\n data['time'] = data['time']-data['time'][0]\n # give a guess for the initial paramters\n # assume eps(t1)=a*exp(t1/tau)\n # eps(t2)=a*exp(t2/tau)\n fit_data = []\n for plane in ['h','v']:\n t2_fit = data['time'][-1]-data['time'][0]\n epst2_fit = data['emit%s'%plane][-1]\n epst1_fit = data['emit%s'%plane][0]\n if epst2_fit < 0:\n raise ValueError(\"\"\"Invalid value of BSRT emittance (eps < 0) \n for time t2=%s'%pytimber.parsedate(data['time'][-1])\"\"\")\n return\n if epst1_fit < 0:\n raise ValueError(\"\"\"Invalid value of BSRT emittance (eps < 0)\n for time t1=%s'%pytimber.parsedate(data['time'][0])\"\"\")\n return\n # initial values for fit parameters\n a_init = epst1_fit\n tau_init = t2_fit/(np.log(epst2_fit)-np.log(epst1_fit))\n if verbose:\n print('... fitting emittance %s for slot %s '%(plane,slot))\n popt,pcov = curve_fit(exp_fit,data['time'],\n data['emit%s'%plane],p0=[a_init,tau_init])\n psig = [ np.sqrt(pcov[i,i]) for i in range(len(popt)) ]\n fit_data += [popt[0],psig[0],popt[1],psig[1]]\n ftype=[('ah',float),('sigah',float),('tauh',float),\n ('sigtauh',float),('av',float),('sigav',float),\n ('tauv',float),('sigtauv',float)]\n self.emitfit[slot][(t1,t2)] = np.array([tuple(fit_data)],\n dtype=ftype)\n except IndexError:\n print(('ERROR: no data found for slot %s! ')%(slot) + \n 'Check the data in timber using BSRT.get_timber_data()!')\n return self\n def get_slots(self):\n \"\"\"\n return list of non-empty slots\n \"\"\"\n return list(self.emit.keys())\n def _set_slots(self,slots):\n \"\"\"\n set slot numbers, handles the case of slots = None and only one \n slot.\n \"\"\"\n if slots is None:\n slots=list(self.emit.keys())\n try:\n len(slots)\n except TypeError:\n slots=[slots]\n return np.sort(slots,axis=None)\n def _set_times(self,t1,t2,verbose):\n \"\"\"\n set start/end time, handles the case of t1 = None and/or t2 = None.\n For t1,t2 = None choose full data range.\n \"\"\"\n if t1 is None:\n t1 = self.t_start\n if verbose:\n print('... using start time %s'%(dumpdate(t1)))\n if t2 is None:\n t2 = self.t_end\n if verbose:\n print('... using end time %s'%(dumpdate(t2)))\n # check timestamp\n if t1 < self.t_start:\n raise ValueError('Start time t1 = ' + '%s < %s'%(t1,self.t_start) + \n ' lies outside of data range!')\n if t2 > self.t_end:\n raise ValueError('End time t2 = ' + '%s > %s'%(t1,self.t_end) + \n ' lies outside of data range!')\n if t2 < t1:\n raise ValueError('End time smaller than start time, t2 = ' + \n '%s > %s = t1'%(t2,t1))\n return t1,t2\n def plot(self,plane='h',t1=None,t2=None,slots=None,avg=10,fit=True,\n color=None,label=None,verbose=False):\n \"\"\"plot BSRT data and fit. The unaveraged raw data is used for the \n fit.\n \n Parameters:\n -----------\n t1,t2 : time interval, if t1 = t2 = None full time range is used\n slots : slot number or list of slot numbers, e.g. slot = [100,200].\n If slots = None, all slots are plotted\n avg: moving average over *avg* data points, if avg = None, the raw \n data is plotted\n fit: fit curve from exponential fit on raw data (not averaged)\n color,linestyle : set fixed color and linestyle\n label : plot label\n verbose: verbose mode, default verbose = False\n \"\"\"\n # set slots\n slots = self._set_slots(slots)\n # set time\n t1,t2 = self._set_times(t1,t2,verbose)\n # plot data\n colors=[]\n for slot in slots:\n if len(colors) == 0:\n colors = ['lime', 'indigo', 'cyan', 'pink', 'orange', 'm', 'g', 'r', 'b']\n if color is None:\n c=colors.pop()\n else: c=color\n mask = ( (self.emit[slot]['time']>=t1) & \n (self.emit[slot]['time']<=t2) )\n eps = self.emit[slot][mask]\n # raw data\n if avg is None:\n pl.plot(eps['time'],eps['emit%s'%plane],'.',color=c,label=label)\n # averaged data\n else:\n epsavg={} # use a dictionary instead of a structured array\n for k in eps.dtype.fields:\n epsavg[k] = movingaverage(eps[k],avg)\n pl.plot(epsavg['time'],epsavg['emit%s'%plane],'.',\n color=c,label=label)\n # plot fit with a black dashed line\n if fit:\n self.plot_fit(plane=plane,t1=t1,t2=t2,slots=slots,\n linestyle='--',color='k',verbose=verbose)\n else:\n set_xaxis_date()\n pl.ylabel(r'$\\epsilon_{N,%s} \\ [\\mu\\mathrm{ m}]$'%plane.upper())\n pl.grid(b=True)\n if label is not None:\n pl.legend(loc='best',fontsize=12)\n return self\n def plot_fit(self,plane='h',t1=None,t2=None,slots=None,color=None,\n linestyle=None,label=None,verbose=False):\n \"\"\"\n plot only fit of BSRT data. The raw data is not displayed.\n\n Parameters:\n -----------\n t1,t2 : time interval, if t1 = t2 = None full time range is used\n slots : slot number or list of slot numbers, e.g. slot = [100,200].\n If None, all slots are plotted\n color,linestyle : set fixed color and linestyle\n label : plot label\n verbose: verbose mode, default verbose = False\n \"\"\"\n # set slots\n slots = self._set_slots(slots)\n # set time\n t1,t2 = self._set_times(t1,t2,verbose)\n colors=[]\n for slot in slots:\n if len(colors) == 0:\n colors=['lime', 'indigo', 'cyan', 'pink', 'orange', 'm', 'g', 'r', 'b']\n if color is None: c=colors.pop()\n else: c=color\n if linestyle is None: ls = '-'\n else: ls = linestyle\n mask = ( (self.emit[slot]['time']>=t1) & \n (self.emit[slot]['time']<=t2) )\n ts = self.emit[slot][mask]['time']\n fitparam = self.get_fit(slot = slot, t1=t1,t2=t2)\n pl.plot(ts,exp_fit(ts-ts[0],fitparam['a%s'%plane],\n fitparam['tau%s'%plane]),linestyle=ls,color=c,label=label)\n set_xaxis_date()\n pl.ylabel(r'$\\epsilon_{N,%s} \\ [\\mu m]$'%plane)\n pl.grid(b=True)\n return self\n","sub_path":"pytimber/LHCBSRT.py","file_name":"LHCBSRT.py","file_ext":"py","file_size_in_byte":22160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"611462157","text":"import tensorflow as tf\r\nfrom keras.layers import Dense, Flatten\r\nfrom keras.models import Model\r\nfrom keras.applications.vgg16 import VGG16\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom glob import glob\r\nimport matplotlib.pyplot as plt\r\n\r\nIMAGE_SIZE = [224, 224]\r\n\r\ntrain_path = 'Datasets/Train'\r\nvalid_path = 'Datasets/Validate'\r\n\r\nvgg = VGG16(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)\r\n\r\nfor layer in vgg.layers:\r\n layer.trainable = False\r\n\r\nfolders = glob(train_path + '/*')\r\n\r\nx = Flatten()(vgg.output)\r\nprediction = Dense(len(folders), activation='sigmoid')(x)\r\n\r\nmodel = Model(inputs=vgg.input, outputs=prediction)\r\n\r\nmodel.compile(\r\n loss='binary_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy']\r\n)\r\n\r\n\r\ntrain_data_generator = ImageDataGenerator(rescale=1. / 255,\r\n shear_range=0.2,\r\n zoom_range=0.2,\r\n horizontal_flip=True)\r\n\r\ntest_data_generator = ImageDataGenerator(rescale=1. / 255)\r\n\r\ntraining_set = train_data_generator.flow_from_directory(train_path,\r\n target_size=(224, 224),\r\n batch_size=32,\r\n class_mode='categorical',\r\n shuffle=True)\r\n\r\ntest_set = test_data_generator.flow_from_directory(valid_path,\r\n target_size=(224, 224),\r\n batch_size=32,\r\n class_mode='categorical')\r\n\r\n\r\nr = model.fit_generator(\r\n training_set,\r\n validation_data=test_set,\r\n epochs=4,\r\n steps_per_epoch=len(training_set),\r\n validation_steps=len(test_set)\r\n)\r\n\r\n# loss\r\nplt.plot(r.history['loss'], label='train loss')\r\nplt.plot(r.history['val_loss'], label='val loss')\r\nplt.legend()\r\nplt.show()\r\nplt.savefig('LossVal_loss')\r\n\r\n\r\nmodel.save('model.h5')","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"174259045","text":"from . import views\nfrom django.urls import path\n\nurlpatterns = [\n path('', views.PostList, name='home'),\n path('/', views.PostDetail.as_view(), name='post_detail'),\n path('post//comment/base.html', views.add_comment_to_post, name='add_comment_to_post'),\n path('comment//approve/', views.comment_approve, name='comment_approve'),\n path('comment//remove/', views.comment_remove, name='comment_remove'),\n]","sub_path":"blogapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"224476337","text":"class Condicion:\r\n \r\n def __init__(self,num1=6,num2=8):\r\n self.numero1= num1\r\n self.numero2= num2\r\n numero= self.numero1+self.numero2\r\n self.numero3= numero\r\n \r\n def usoIf(self):\r\n print(self.numero3)\r\n \r\nprint(\"instancia de la clase\") \r\ncond1= Condicion(70,94)\r\ncond2= Condicion()\r\nprint(cond2.numero3)\r\ncond1.usoIf()\r\ncond2.usoIf()\r\nprint(\"Gracias por su visita\")\r\n","sub_path":"Sem2/condicion2.py","file_name":"condicion2.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"78020584","text":"import tkinter as tk\nimport threading\nimport time\nimport json\nimport serial\nimport traceback\n#Continously publishes the value of the horizontal slider on topic 'angle'\n\nMODE = 'USB' #SOCKET or USB\nINTERVAL = 0.20\nSTEP = 5\nUPDATED = True\n\nRECEIVER = 'esp32new'\n\nprevTime = 0\ncurrentMotor = 1\nprevMotor = 1\ndoReset = False\n#jsonPoses = [0, 20, 0, 0, -15, 20, 0, 0, -20, 0, 0, 0, 0, 0, 0, 0]\njsonPoses = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nprevJsonPoses = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\nstartingPoses = [90, 102, 121, 91, 80, 104, 95, 72, 73, 90]\nstartingPoses = [90, 90, 90, 90, 90, 90, 90, 90, 90, 90]\nposeOffset = [0, 12, 31, 1, -10, 0, 0, 0, 0, 0, 0, 14, 5, -18, -17, 0]\nsavedPoses = dict()\njointSliders = []\nsavedButtons = []\n\ntry:\n arduino = serial.Serial(\"COM3\", 115200, timeout=0)\nexcept:\n print('Arduino USB not found.')\n\nbuttons = []\nmessage = ''\n#positions = {}\ndef send_angles_socket():\n global prevTime, RECEIVER, jsonPoses, servoValue, INTERVAL, STEP, prevValue, master, END, currentMotor ,prevMotor, doReset, jsonPoses, prevJsonPoses, message, positions, buttons\n import socket\n import traceback\n host = ''\n port = 5555\n RECTIME = 20\n RECSIZE = 4096\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((host, port))\n RECEIVER = 'a'#socket.gethostbyname(RECEIVER)\n def savePosition():\n toSave = ['save',entry.get(),jsonPoses]\n payload = json.dumps(toSave, indent=4)\n print(payload)\n s.sendto(payload.encode(), (RECEIVER, 5555))\n getPositions()\n\n def removePosition():\n toRemove = ['remove',entry.get()]\n payload = json.dumps(toRemove, indent=4)\n print(payload)\n s.sendto(payload.encode(), (RECEIVER, 5555))\n getPositions()\n\n def getPositions():\n global message, positions, buttons\n for b in buttons:\n b.destroy()\n buttons = []\n askPositions = 'positions'\n payload = json.dumps(askPositions, indent=4)\n print(payload.encode())\n s.sendto(payload.encode(), (RECEIVER, 5555))\n\n def receive():\n global message\n message = ''\n message2, address = s.recvfrom(RECSIZE)\n message = message2.decode(\"utf-8\", \"ignore\")\n\n th = threading.Thread(target=receive)\n th.setDaemon(True)\n th.start()\n startReceive = time.time()\n while message == '':\n try:\n if(time.time()-startReceive > 6):\n raise Exception(\"timeout\")\n if message != '':\n print('Received:',message)\n message=('global positions\\n'+message)\n #positions = {'start': [0, 45, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'mid': [0, 45, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'end': [0, 30, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}\n print(exec(message))\n for key in positions: #from message\n q = tk.Button(master, text=key, command= lambda: positionButton(positions))\n q.pack()\n buttons.append(q)\n except:\n traceback.print_exc()\n print('Couldn\\'t download positions')\n break\n\n q = tk.Button(master, text=\"Download positions\", bg='yellow', command=getPositions)\n q.pack()\n tk.Label(master, text=\"Position name\").pack()\n entry = tk.Entry(master)\n entry.pack()\n q = tk.Button(master, text=\"Save new position\", bg='green', command=savePosition)\n q.pack()\n q = tk.Button(master, text=\"Remove position\", bg='red', command=removePosition)\n q.pack()\n\n #getPositions()\n\n def sitStand():\n global jsonPoses\n value = w0.get()\n value0 = value\n toChange = [1, 2, 3]\n for i in toChange:\n value = value0\n if i != 1:\n value = -value\n if i == 1:\n value += 30\n if i == 3:\n value = int(value / 2)\n jsonPoses[i] = value\n jsonPoses[15 - i] = -value\n\n def leanLeft():\n global jsonPoses\n value = w0.get()\n value0 = value\n toChange = [0]\n for i in toChange:\n #jsonPoses[i] = value\n jsonPoses[9-i] = value\n\n def allMotors():\n global jointSliders\n for i in range(10):\n if i >= 5:\n j = 15 - (9-i)\n else:\n j = i\n jsonPoses[j] = jointSliders[i].get()\n\n\n #jsonPoses = [0, 20, 0, 0, -10, 15, 0, 0, -20, 0, 0, 0, 0, 0, 0, 0]\n startup = True\n while True:\n try:\n if(END):\n print('closing')\n return\n '''if (abs(servoValue - targetPose) > STEP):\n servoValue += sign(targetPose - servoValue) * STEP\n else:\n servoValue = targetPose'''\n servoValue = targetPose\n if(time.time()-prevTime >= INTERVAL):\n #sitStand()\n #leanLeft()\n allMotors()\n #for i in range(16):\n #jsonPoses[i] = value\n '''\n jsonPoses[1] = w1.get()\n jsonPoses[2] = w2.get()\n jsonPoses[3] = w3.get()\n jsonPoses[4] = w4.get()\n '''\n\n if(jsonPoses != prevJsonPoses or startup):\n #if True:\n angleString = \"s\";\n for st in jsonPoses:\n #st = st + 90\n #st =\n s2 = str(st)\n if s2.__len__() < 3:\n for i in range(3 - s2.__len__()):\n s2 = '0' + s2\n angleString = angleString + s2\n angleString = angleString + '\\n'\n #payload = bytes(angleString, \" utf-8\")\n #s.sendto(payload, (RECEIVER, 5555))\n arduino.write(angleString.encode(encoding='utf-8'))\n response = ''\n time.sleep(0.01)\n response = arduino.readline()\n print('MESSAGE: ', angleString, 'RESPONSE: ', ('s'+response.decode()))\n arduino.flushInput()\n if (angleString == 's'+response.decode()):\n print('OK')\n startup = False\n else:\n print('ERROR')\n #print(payload)\n prevJsonPoses = list(jsonPoses)\n prevTime = time.time()\n '''elif(doReset):\n Mqtt.sendInt('reset', 0)\n doReset = False\n prevTime = time.time()'''\n except:\n traceback.print_exc()\n\n#string example \"s090102121091080000000000000000000104095072073090\\n\"\n#\"s090090090090090000000000000000000090090090090090\\n\"\ndef getAngleString(jsonAngles):\n angleString = \"s\";\n\n for st in jsonAngles:\n # st = st + 90\n # st =\n s2 = str(st)\n if s2.__len__() < 3:\n for i in range(3 - s2.__len__()):\n s2 = '0' + s2\n angleString = angleString + s2\n angleString = angleString + '\\n'\n return angleString\n\ndef sendUSB(toSend):\n arduino.write(toSend.encode(encoding='utf-8'))\n response = ''\n time.sleep(0.05)\n response = arduino.readline()\n print('MESSAGE: ', toSend, 'RESPONSE: ', ('s' + response.decode()))\n arduino.flushInput()\n if (toSend == 's' + response.decode()):\n print('OK')\n return 0\n else:\n print('ERROR')\n return 1\n\ndef allMotors():\n global jointSliders, jsonPoses\n for i in range(10):\n if i >= 5:\n j = 15 - (9-i)\n else:\n j = i\n jsonPoses[j] = jointSliders[i].get() + poseOffset[j] #GUANTO\n\nPAUSE = False\ndef sendAnglesUSB():\n global prevJsonPoses, jsonPoses\n #getPositions()\n\n '''def sitStand():\n global jsonPoses\n value0 = value\n toChange = [1, 2, 3]\n for i in toChange:\n value = value0\n if i != 1:\n value = -value\n if i == 1:\n value += 30\n if i == 3:\n value = int(value / 2)\n jsonPoses[i] = value\n jsonPoses[15 - i] = -value'''\n\n '''def leanLeft():\n global jsonPoses\n value0 = value\n toChange = [0]\n for i in toChange:\n #jsonPoses[i] = value\n jsonPoses[9-i] = value'''\n\n startup = 1\n prevTime = 0\n while True:\n try:\n servoValue = targetPose\n if(time.time()-prevTime >= INTERVAL):\n #sitStand()\n #leanLeft()\n allMotors()\n if(jsonPoses != prevJsonPoses or startup):\n if(not PAUSE):\n angleString = getAngleString(jsonPoses)\n startup = sendUSB(angleString)\n #print(payload)\n prevJsonPoses = list(jsonPoses)\n prevTime = time.time()\n except:\n traceback.print_exc()\n\n\n\ndef clicked(event):\n global CLICKED, PAUSE\n CLICKED = event.widget\n print('clicked',CLICKED)\n if CLICKED in jointSliders:\n PAUSE = False\n\ndef setPose():\n global PAUSE\n PAUSE = True\n print('set',CLICKED['text'])\n poses = savedPoses[CLICKED['text']]\n print(poses)\n for i in range(10):\n if i<5:\n j = i\n else:\n j = 16-(10-i)\n jointSliders[i].set(poses[j])\n allMotors()\n sendUSB(getAngleString(jsonPoses))\n\ndef playback():\n global PAUSE\n PAUSE = True\n print(\"REPLAY: \" + str(savedPoses))\n for n in range(13):\n time.sleep(0.3)\n poses = savedPoses[\"s\"+str(n+1)]\n print(poses)\n for i in range(10):\n if i<5:\n j = i\n else:\n j = 16-(10-i)\n jointSliders[i].set(poses[j])\n allMotors()\n sendUSB(getAngleString(jsonPoses))\n while(True):\n for n in range(10):\n time.sleep(0.3)\n poses = savedPoses[\"s\"+str(n+4)]\n print(poses)\n for i in range(10):\n if i<5:\n j = i\n else:\n j = 16-(10-i)\n jointSliders[i].set(poses[j])\n allMotors()\n sendUSB(getAngleString(jsonPoses))\n \ndef walk():\n global savedPoses\n f = open(\"narrowGaitV2\"+'.txt',\"r\")\n s = f.read()\n savedPoses = eval(s)\n print(savedPoses)\n f.close()\n global PAUSE\n PAUSE = True\n print(\"REPLAY: \" + str(savedPoses))\n for n in range(13):\n time.sleep(0.3)\n poses = savedPoses[\"s\"+str(n+1)]\n print(poses)\n for i in range(10):\n if i<5:\n j = i\n else:\n j = 16-(10-i)\n jointSliders[i].set(poses[j])\n allMotors()\n sendUSB(getAngleString(jsonPoses))\n while(True):\n for n in range(10):\n time.sleep(0.3)\n poses = savedPoses[\"s\"+str(n+4)]\n print(poses)\n for i in range(10):\n if i<5:\n j = i\n else:\n j = 16-(10-i)\n jointSliders[i].set(poses[j])\n allMotors()\n sendUSB(getAngleString(jsonPoses))\n \n \n\ndef saveFile():\n text = ENTRY.get()\n f = open(text+'.txt',\"w\")\n f.write(str(savedPoses))\n f.close()\n\ndef loadFile():\n global savedPoses\n text = ENTRY.get()\n f = open(text+'.txt',\"r\")\n s = f.read()\n savedPoses = eval(s)\n print('savedPoses = ',savedPoses)\n for i in savedPoses:\n newPose = tk.Button(master, text=i, bg='yellow', command=setPose)\n newPose.pack(side = tk.LEFT)\n savedButtons.append(newPose)\n #add playback button\n newPose = tk.Button(master, text=\"WALK\", bg='orange', command=playback)\n newPose.pack(side = tk.LEFT)\n savedButtons.append(newPose)\n f.close()\n\ndef savePose():\n global savedPoses\n text = ENTRY.get()\n newPose = tk.Button(master, text=text, bg='yellow', command=setPose)\n if(newPose['text'] not in savedPoses):\n newPose.pack(side = tk.LEFT)\n savedButtons.append(newPose)\n jsonSave = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n for i in range(16):\n jsonSave[i] = jsonPoses[i] - poseOffset[i]\n savedPoses[newPose['text']] = list(jsonSave)\n print('save',newPose['text'])\n print(savedPoses)\n\ndef removeSaved(event):\n print(\"remove\", event.widget)\n if event.widget in savedButtons:\n savedPoses.pop(event.widget['text'])\n savedButtons.remove(event.widget)\n event.widget.destroy()\n\ndef reset():\n for i in range(10):\n jointSliders[i].set(startingPoses[i])\n allMotors()\n sendUSB(getAngleString(jsonPoses))\n\ndef sign(n):\n if n > 0:\n return 1\n elif n < 0:\n return -1\n else:\n return 0\n\ntargetPose = 0\nservoValue = 0\nmaster = tk.Tk()\n#w0 = tk.Scale(master, from_=-90, to=90, orient=tk.HORIZONTAL, activebackground='white', troughcolor='blue', width= 30, length= 500, command=sliderCallback0)\n#w0.pack()\nfor i in range(10):\n if(i>=5):\n color = 'blue'\n else:\n color = 'red'\n jointSliders.append(tk.Scale(master, from_=0, to=180, orient=tk.HORIZONTAL, activebackground='white', troughcolor=color, width= 10, length= 500))\n jointSliders[i].set(startingPoses[i])\n jointSliders[i].pack()\n\nRESET = tk.Button(master, text='RESET', command=reset)\nRESET.pack()\ntk.Label(master, text=\"Position name\").pack()\nENTRY = tk.Entry(master)\nENTRY.pack()\nLOADFILE = tk.Button(master, text=\"Load file\", bg='green', command=loadFile)\nLOADFILE.pack()\nSAVEFILE = tk.Button(master, text=\"Save file\", bg='green', command=saveFile)\nSAVEFILE.pack()\nSAVE = tk.Button(master, text=\"Save pose\", bg='green', command=savePose)\nSAVE.pack()\nWALK = tk.Button(master, text=\"WALK\", bg='purple', command=walk)\nWALK.pack()\n\nmaster.bind(\"<3>\", removeSaved)\nmaster.bind(\"<1>\", clicked)\nif(MODE == 'USB'):\n th = threading.Thread(target=sendAnglesUSB)\n th.setDaemon(True)\n th.start()\nif(MODE == 'SOCKET'):\n th = threading.Thread(target=send_angles_socket)\n th.setDaemon(True)\n th.start()\ntk.mainloop()\n","sub_path":"Projects/RobotBiped/Biped_GUI_V1.py","file_name":"Biped_GUI_V1.py","file_ext":"py","file_size_in_byte":14573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"140173055","text":"from flask import Blueprint, abort, redirect, url_for\nfrom jinja2 import TemplateNotFound\nfrom . import home\nfrom .forms import ContactForm, MarkReadForm\nfrom .models import Inquiry\nfrom ..decorators import templated\nfrom .. import db\nfrom flask_login import current_user\n\n@home.route('/', methods = ['GET'])\n@templated('home.html')\ndef index():\n return dict()\n\n@home.route('/ask/', methods = ['GET'])\n@templated('ask.html')\ndef ask():\n return dict()\n\n@home.route('/contact/', methods = ['GET', 'POST'])\n@templated('contact.html')\ndef contact():\n contact_form = ContactForm(obj = current_user)\n\n if contact_form.validate_on_submit():\n inquiry = Inquiry(\n name = contact_form.name.data,\n email = contact_form.email.data,\n subject = contact_form.subject.data,\n body = contact_form.body.data,\n )\n db.session.add(inquiry)\n db.session.commit()\n\n return redirect(url_for('home.contact'))\n\n return dict(contact_form = contact_form)\n\n@home.route('/profile/', methods = ['GET'])\n@templated('profile.html')\ndef profile():\n return dict()\n\n@home.route('/inbox/', methods = ['GET', 'POST'])\n@templated('inbox.html')\ndef inbox():\n if not current_user.is_admin:\n return redirect(url_for('home.index'))\n\n inquiries = Inquiry.query.all()\n read_form = MarkReadForm()\n return dict(inquiries = inquiries, read_form = read_form)\n\n","sub_path":"onepercenteveryday/home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"442093464","text":"import unittest\nimport os\nimport numpy\nfrom server.forecasting.dataloader import DataLoader\nfrom server.settings import BASE_DIR, CYTHON_SUPPORT\nfrom server.forecasting.statistical import StatisticalForecast\nfrom server.forecasting.statistical.holt_winters import double_seasonal, multiplicative\nimport time\n\n\nsep = os.path.sep\nDATA_PATH = BASE_DIR + sep + \"server\" + sep + \\\n \"forecasting\" + sep + \"simulation\" + sep + \"demodata\"\n\n\n@unittest.skipIf(not CYTHON_SUPPORT, \"cython support not activated\")\nclass ExtensionsTest(unittest.TestCase):\n\n \"\"\" Test if cython extensions deliver the same results as their python counterparts\"\"\"\n\n @classmethod\n def setUpClass(cls):\n from server.forecasting.statistical.build_extension import build_holtwinters_extension\n # compile and link holtwinters_fast module\n build_holtwinters_extension()\n #make them accessible everywhere\n global Cdouble_seasonal, Cmultiplicative\n from server.forecasting.statistical.holtwinters_fast import double_seasonal as Cdouble_seasonal\n from server.forecasting.statistical.holtwinters_fast import multiplicative as Cmultiplicative\n\n def setUp(self):\n # dataset containing one year of data, sampled in 10 minute intervals\n # really important to reset, because other devices could have added\n # data which is unwanted\n DataLoader.cached_csv = {}\n path = DATA_PATH + sep + \"demo_electricity_2013.csv\"\n raw_dataset = DataLoader.load_from_file(\n path, \"Strom - Verbrauchertotal (Aktuell)\", \"\\t\")\n # cast to float and convert to kW\n self.dataset = StatisticalForecast.make_hourly(\n [float(val) / 1000.0 for val in raw_dataset], 6)\n\n def rmse(self, testdata, forecast):\n return sum([(m - n) ** 2 for m, n in zip(testdata, forecast)]) / len(testdata)\n\n def test_doubleseasonal(self):\n input_length = 24 * 7 * 8\n forecast = 24 * 7 * 4\n\n for a in [0.0, 0.5, 1.0]:\n for b in [0.0, 0.5, 1.0]:\n py_forecast, p, insample = double_seasonal(\n self.dataset[:-input_length], 24, 24 * 7, forecast,\n alpha=a, beta=0.0, gamma=a, delta=a, autocorrelation=b)\n cy_forecast, p, insample = Cdouble_seasonal(\n self.dataset[:-input_length], 24, 24 * 7, forecast,\n alpha=a, beta=0.0, gamma=a, delta=a, autocorrelation=b)\n\n # exclude very high values from testing, as these will have\n # floating point accuracy issues\n if abs(numpy.mean(py_forecast)) < 10 ** 9:\n self.assertTrue(self.rmse(py_forecast, cy_forecast) < 0.5,\n \"python and cython dshw-forecasts differ significantly.\")\n\n def test_multiplicative(self):\n input_length = 24 * 7 * 8\n forecast = 24 * 7 * 4\n for a in [0.0, 0.5, 1.0]:\n for b in [0.0, 0.5, 1.0]:\n py_forecast, p, insample = multiplicative(\n self.dataset[:-input_length], 24, forecast,\n alpha=a, beta=b, gamma=b)\n cy_forecast, p, insample = Cmultiplicative(\n self.dataset[:-input_length], 24, forecast,\n alpha=a, beta=b, gamma=b)\n\n # exclude very high values from testing, as these will have\n # floating point accuracy issues\n if abs(numpy.mean(py_forecast)) < 10 ** 9:\n self.assertTrue(self.rmse(py_forecast, cy_forecast) < 0.5,\n \"python and cython multiplicative-forecasts differ significantly.\")\n\n def test_performance(self):\n input_length = 24 * 7 * 8\n forecast = 24 * 7 * 4\n t = time.time()\n for i in range(100):\n double_seasonal(self.dataset[:-input_length], 24, 24 * 7, forecast,\n alpha=0.5, beta=0.0, gamma=0.5, delta=0, autocorrelation=0.2)\n py_timing = time.time() - t\n\n t2 = time.time()\n for i in range(100):\n Cdouble_seasonal(\n self.dataset[:-input_length], 24, 24 * 7, forecast,\n alpha=0.5, beta=0.0, gamma=0.5, delta=0, autocorrelation=0.2)\n cy_timing = time.time() - t2\n # print py_timing, cy_timing\n self.assertTrue(\n cy_timing < py_timing, \"cython version is slower than python. WTF?\")\n","sub_path":"server/forecasting/tests/test_extensions.py","file_name":"test_extensions.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"285376253","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom reportes.models import Estudiante\n\nfrom .models import(\n Estudiante\n\n)\n# # # Create your views here.\n\n\t\t\n\ndef reporteAlumnos(request):\n\tif request.user.is_authenticated:\n\t\talumno = Estudiante.objects.all()\n\t\t\n\t\tcontexto = {\n\t\t\t'alumnos': alumno\n\t\t}\n\n\t\treturn render(request, 'reportes/reporteAlumnos.html',contexto)\n\telse:\n\t\treturn HttpResponseRedirect(settings.FAIL_REDIRECT)\n\t\ndef DatosAlumno(request,pk):\n\tif request.user.is_authenticated:\n\t\talumno = Estudiante.objects.filter(pk=pk).values()\n\t\tcontexto = {'alumno':alumno}\n\t\treturn render(request,'reportes/ListarDatos.html', contexto)\n\telse:\n\t\treturn HttpResponseRedirect(settings.FAIL_REDIRECT)\n\n\n\t","sub_path":"Proyecto/reportes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"40355223","text":"food={\"vegetables\":[\"carrots\",\"kale\",\"cucumber\",\"tomato\"],\"desserts\":[\"cake\",\"ice cream\", \"donut\"]}\nfor hungry in food[\"vegetables\"]:\n\tprint(hungry)\nfor hungry in food[\"desserts\"]:\n\tprint(hungry)\n\ncars={\"sports\":{\"Volkswagon\":\"Porsche\",\"Dodge\":\"Viper\",\"Chevy\":\"Corvette\"},\"classic\":{\"Mercedes-Benz\":\"300SL\",\"Toyota\":\"2000GT\",\"Lincoln\":\"Continental\"}}\nfor auto in cars[\"sports\"]:\n\tprint(cars[\"sports\"][auto])\nfor auto in cars[\"classic\"]:\n\tprint(cars[\"classic\"][auto])\n\ndessert={\"iceCream\":[\"Rocky Road\",\"strawberry\",\"Pistachio Cashew\",\"Pecan Praline\"]}\nfor yummy in dessert[\"iceCream\"]:\n\tprint(yummy)\n\nsoup={\"soup\":{\"tomato 1\":\"healthy\",\"onion\":\"bleh!\",\"vegetable\":\"good for you\"}}\nfor tastey in soup[\"soup\"]:\n\tprint(soup[\"soup\"][tastey])\n","sub_path":"module00/00-prep-03-python-primer2/nested_datatypes_loops_sol.py","file_name":"nested_datatypes_loops_sol.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"576198790","text":"import os\nfrom PIL import Image\nimport numpy as np\nimport os\nimport copy\n# from color_map import make_color_map\n\n\nlabel_out_path = '../data/label_binary/'\n# clabel_out_path = './data/label_color/'\nif not os.path.exists(label_out_path):\n os.mkdir(label_out_path)\n# if not os.path.exists(clabel_out_path):\n# os.mkdir(clabel_out_path)\n\nimg_path = \"/Users/shin/work/graphen/mos2_saito/color/\"\nnb_classes = 5\ncolor_list = np.array([[255,0,255],[0,255,255],[255,0,0],[0,255,0],[0,0,255]]) # ピンク,水色,赤,青,緑\n# color_map = make_color_map()\n\nfor name in os.listdir(img_path):\n print(name)\n img = Image.open(img_path + name)\n img = np.array(img)\n h,w,_ = img.shape\n label = np.zeros((h,w,nb_classes))\n for x in range(h):\n for y in range(w):\n pixel = img[x,y]\n dist = np.sum((color_list - pixel) ** 2, axis =1)\n cl = dist.argmin()\n label[x,y,cl] = 1\n label = label.argmax(axis=2).astype(np.uint8)\n \n # 2層 & それ以外の 学習ラベルを作る場合\n label[label !=2 ] = 0\n label[label == 2] = 1\n \n label = Image.fromarray(label, mode='P')\n palette_im = Image.open('/Users/shin/Dataset/VOCdevkit/VOC2012/SegmentationClass/2007_000032.png')\n label.palette = copy.copy(palette_im.palette)\n label.save(label_out_path + name)\n\n # label_rgb= np.ones((h,w,3))\n # for i in range(nb_classes):\n # label_rgb[label==i] = color_map[i]\n # Image.fromarray(label_rgb.astype(np.uint8)).save(clabel_out_path + name)\n # Image.fromarray(label.astype(np.uint8)).save(label_out_path+ name)\n","sub_path":"graphen_work/util/image_to_label.py","file_name":"image_to_label.py","file_ext":"py","file_size_in_byte":1605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"40652338","text":"import argparse\nimport requests\nimport os\nimport re\nimport sys\nimport traceback\n\n\ndef query_api(host):\n \"\"\"Queries the ip-api site in order to check geolocation and mx record of\n the host\"\"\"\n main_api = 'http://ip-api.com/json/'\n # For every host do an API request\n try:\n for x in host:\n # Store response in 'json_data'\n json_data = requests.get(main_api + x).json()\n # Checks to see if there is a 'message' field in the json data and\n # prints the message instead of printing our formatted data.\n # This is done because messages are always an error with this api.\n if 'message' in json_data:\n print('\\nThe IP \"{}\" is {}'.format(x, json_data['message']))\n # Print out wanted JSON data formatted nicely\n else:\n print('\\nAS: {}\\n'\n 'City\\State: {}, {}\\n'\n 'Country: {}\\n'\n 'ISP: {}\\n'\n 'IP: {}\\n'\n 'MX: {}'.format(\n json_data['as'],\n json_data['city'],\n json_data['regionName'],\n json_data['country'],\n json_data['isp'],\n json_data['query'],\n x))\n # Added exception handling of key errors to help identify problems when\n # reading the json data\n except KeyError:\n traceback.print_exc(file=sys.stdout)\n print('Key Error')\n print('JSON: ')\n print(json_data)\n\n\ndef findMX(host):\n \"\"\"Looks up the MX record of a host\"\"\"\n p = os.popen('host -t MX ' + host)\n\n # initialize dicts\n std_out = []\n # Stores the standard output of p(above)\n split = []\n # Used to hold the a line in std_out that we want to split.\n MXServer = []\n # The server address that we are sending to the api. \n\n # Append terminal output to list std_out\n for line in p:\n if re.search('not found', line):\n print('No MX record found querying ' + host)\n query_api([host])\n break\n # Check to see if 'domain name pointer' is in the line and finds the\n # ip associated with the pointer to do a query on. Created for IPs that\n # do not have a easily parsed MX record return.\n elif re.search('domain name pointer', line):\n print(line)\n print('Domain name pointer found querying original host: ' + host)\n query_api([host])\n extra = re.search('.in-addr.arpa .*', str(line))\n # This finds out the 'extra' stuff I dont really care about. i only\n # need the IP that is in the line before .in-addr.arpa\n thing = line.replace(extra.group(0), '')\n # This takes the line and replaces what is stored in the 'extra'\n # variable with nothing and gives us the 'thing' we want to query,\n # an IP address.\n print('\\nDomain Name pointer Query: ' + thing)\n query_api([thing.rstrip()])\n break\n std_out.append(line)\n p.close\n\n # split line into dict and return MX servers\n i = 0\n for x in std_out:\n # When using os.popen it basically acts like a terminal allowing you to\n # run terminal commands from your Python script and use its output. We\n # are using as an example 'host -t MX google.com' the output would look\n # like:\n # google.com mail is handled by 30 alt2.aspmx.l.google.com\n # google.com mail is handled by 40 alt3.aspmx.l.google.com\n # google.com mail is handled by 10 aspmx.l.google.com\n # google.com mail is handled by 20 alt1.aspmx.l.google.com\n # google.com mail is handled by 50 alt4.aspmx.l.google.com\n split = std_out[i].split()\n i = i + 1\n # We use .split() method to split the std_out list entry by spaces\n\n MXServer.append(split[-1])\n # We take the last item in the split(aspmx.l.google.com) and append it\n # to the list 'MXServer'\n query_api(MXServer)\n # Now we send the list 'MXServer' to the query_api function\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"host\", help=\"hostname to lookip\")\n args = parser.parse_args()\n findMX(args.host)\n","sub_path":"ip-api.py","file_name":"ip-api.py","file_ext":"py","file_size_in_byte":4392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"271609051","text":"import numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nfrom UTILS.Calculus import Calculus\nfrom UTILS.SetAxisLimit import SetAxisLimit\nfrom UTILS.Tools import Tools\nfrom UTILS.Errors import Errors\n\n\n# Theoretical background https://arxiv.org/abs/1401.5176\n\n# Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field #\n# Equations in Spherical Geometry and their Application to Turbulent Stellar #\n# Convection Data #\n\nclass MomentumEquationX(Calculus, SetAxisLimit, Tools, Errors, object):\n\n def __init__(self, filename, ig, fext, intc, data_prefix):\n super(MomentumEquationX, self).__init__(ig)\n\n # load data to structured array\n eht = self.customLoad(filename)\n\n # load grid\n xzn0 = self.getRAdata(eht, 'xzn0')\n nx = self.getRAdata(eht, 'nx')\n\n # pick equation-specific Reynolds-averaged mean fields according to:\n # https://github.com/mmicromegas/ransX/blob/master/DOCS/ransXimplementationGuide.pdf\t\n\n dd = self.getRAdata(eht, 'dd')[intc]\n ux = self.getRAdata(eht, 'ux')[intc]\n pp = self.getRAdata(eht, 'pp')[intc]\n gg = self.getRAdata(eht, 'gg')[intc]\n\n ddgg = self.getRAdata(eht, 'ddgg')[intc]\n ddux = self.getRAdata(eht, 'ddux')[intc]\n\n dduxux = self.getRAdata(eht, 'dduxux')[intc]\n dduyuy = self.getRAdata(eht, 'dduyuy')[intc]\n dduzuz = self.getRAdata(eht, 'dduzuz')[intc]\n\n # store time series for time derivatives\n t_timec = self.getRAdata(eht, 'timec')\n t_ddux = self.getRAdata(eht, 'ddux')\n\n # construct equation-specific mean fields\t\t\n fht_ux = ddux / dd\n rxx = dduxux - ddux * ddux / dd\n\n #####################\n # X MOMENTUM EQUATION \n #####################\n\n # LHS -dq/dt \t\t\n self.minus_dt_ddux = -self.dt(t_ddux, xzn0, t_timec, intc)\n\n # LHS -div rho fht_ux fht_ux\n self.minus_div_eht_dd_fht_ux_fht_ux = -self.Div(dd * fht_ux * fht_ux, xzn0)\n\n # RHS -div rxx\n self.minus_div_rxx = -self.Div(rxx, xzn0)\n\n # RHS -G\n if self.ig == 1:\n self.minus_G = np.zeros(nx)\n elif self.ig == 2:\n self.minus_G = -(-dduyuy - dduzuz) / xzn0\n\n # RHS -(grad P - rho g)\n #self.minus_gradx_pp_eht_dd_eht_gg = -self.Grad(pp,xzn0) +dd*gg\n self.minus_gradx_pp_eht_dd_eht_gg = -self.Grad(pp, xzn0) + ddgg\n\n # for i in range(nx):\n # print(2.*ddgg[i],dd[i]*gg[i]\t\t\n\n # -res\n self.minus_resResXmomentumEquation = \\\n -(self.minus_dt_ddux + self.minus_div_eht_dd_fht_ux_fht_ux + self.minus_div_rxx\n + self.minus_G + self.minus_gradx_pp_eht_dd_eht_gg)\n\n #########################\n # END X MOMENTUM EQUATION \n #########################\n\n # assign global data to be shared across whole class\n self.data_prefix = data_prefix\n self.xzn0 = xzn0\n self.ddux = ddux\n self.ux = ux\n self.ig = ig\n self.fext = fext\n\n def plot_momentum_x(self, LAXIS, bconv, tconv, xbl, xbr, ybu, ybd, ilg):\n \"\"\"Plot ddux stratification in the model\"\"\"\n\n # check supported geometries\n if self.ig != 1 and self.ig != 2:\n print(\"ERROR(MomentumEquationX.py):\" + self.errorGeometry(self.ig))\n sys.exit()\n\n # load x GRID\n grd1 = self.xzn0\n\n # load DATA to plot\n plt1 = self.ddux\n # plt2 = self.ux\n # plt3 = self.vexp\n\n # create FIGURE\n plt.figure(figsize=(7, 6))\n\n # format AXIS, make sure it is exponential\n plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))\n\n # set plot boundaries \n to_plot = [plt1]\n self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot)\n\n # plot DATA and set labels\n plt.title('ddux')\n if self.ig == 1:\n plt.plot(grd1, plt1, color='brown', label=r'$\\overline{\\rho} \\widetilde{u}_x$')\n # plt.plot(grd1,plt2,color='green',label = r'$\\overline{u}_x$')\n # plt.plot(grd1,plt3,color='red',label = r'$v_{exp}$')\n elif self.ig == 2:\n plt.plot(grd1, plt1, color='brown', label=r'$\\overline{\\rho} \\widetilde{u}_r$')\n # plt.plot(grd1,plt2,color='green',label = r'$\\overline{u}_x$')\n # plt.plot(grd1,plt3,color='red',label = r'$v_{exp}$')\n\n # convective boundary markers\n plt.axvline(bconv, linestyle='--', linewidth=0.7, color='k')\n plt.axvline(tconv, linestyle='--', linewidth=0.7, color='k')\n\n # define and show x/y LABELS\n if self.ig == 1:\n setxlabel = r'x (cm)'\n setylabel = r\"$\\overline{\\rho} \\widetilde{u}_x$ (g cm$^{-2}$ s$^{-1}$)\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n elif self.ig == 2:\n setxlabel = r'r (cm)'\n setylabel = r\"$\\overline{\\rho} \\widetilde{u}_r$ (g cm$^{-2}$ s$^{-1}$)\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n\n # show LEGEND\n plt.legend(loc=ilg, prop={'size': 18})\n\n # display PLOT\n plt.show(block=False)\n\n # save PLOT\n if self.fext == \"png\":\n plt.savefig('RESULTS/' + self.data_prefix + 'mean_ddux_canuto1997.png')\n if self.fext == \"eps\":\n plt.savefig('RESULTS/' + self.data_prefix + 'mean_ddux_canuto1997.eps')\n\n def plot_momentum_equation_x(self, LAXIS, bconv, tconv, xbl, xbr, ybu, ybd, ilg):\n \"\"\"Plot momentum x equation in the model\"\"\"\n\n # check supported geometries\n if self.ig != 1 and self.ig != 2:\n print(\"ERROR(MomentumEquationX.py):\" + self.errorGeometry(self.ig))\n sys.exit()\n\n # load x GRID\n grd1 = self.xzn0\n\n lhs0 = self.minus_dt_ddux\n lhs1 = self.minus_div_eht_dd_fht_ux_fht_ux\n\n rhs0 = self.minus_div_rxx\n rhs1 = self.minus_G\n rhs2 = self.minus_gradx_pp_eht_dd_eht_gg\n\n res = self.minus_resResXmomentumEquation\n\n # create FIGURE\n plt.figure(figsize=(7, 6))\n\n # format AXIS, make sure it is exponential\n plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))\n\n # set plot boundaries \n to_plot = [lhs0, lhs1, rhs0, rhs1, rhs2, res]\n self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot)\n\n # plot DATA \n plt.title('x momentum equation')\n if self.ig == 1:\n #plt.plot(grd1, lhs0, color='c', label=r\"$-\\partial_t ( \\overline{\\rho} \\widetilde{u}_r ) $\")\n #plt.plot(grd1, lhs1, color='m', label=r\"$-\\nabla_x (\\overline{\\rho} \\widetilde{u}_x \\widetilde{u}_x ) $\")\n plt.plot(grd1,lhs0+lhs1,color='c',label=r\"$-\\overline{\\rho} D_t \\widetilde{u}_x$\")\n plt.plot(grd1, rhs0, color='b', label=r\"$-\\nabla_x (\\overline{\\rho} R_{xx})$\")\n plt.plot(grd1, rhs2, color='r', label=r\"$-(\\partial_x \\overline{p} - \\overline{\\rho} g_x)$\")\n plt.plot(grd1, res, color='k', linestyle='--', label='res')\n elif self.ig == 2:\n plt.plot(grd1, lhs0, color='c', label=r\"$-\\partial_t ( \\overline{\\rho} \\widetilde{u}_r ) $\")\n plt.plot(grd1, lhs1, color='m', label=r\"$-\\nabla_r (\\overline{\\rho} \\widetilde{u}_r \\widetilde{u}_r ) $\")\n plt.plot(grd1, rhs0, color='b', label=r\"$-\\nabla_r (\\widetilde{R}_{rr})$\")\n plt.plot(grd1, rhs1, color='g', label=r\"$-\\overline{G^{M}_r}$\")\n plt.plot(grd1, rhs2, color='r', label=r\"$-(\\partial_r \\overline{P} - \\bar{\\rho}\\tilde{g}_r)$\")\n plt.plot(grd1, res, color='k', linestyle='--', label='res')\n\n # convective boundary markers\n plt.axvline(bconv, linestyle='--', linewidth=0.7, color='k')\n plt.axvline(tconv, linestyle='--', linewidth=0.7, color='k')\n\n # define and show x/y LABELS\n setylabel = r\"g cm$^{-2}$ s$^{-2}$\"\n if self.ig == 1:\n setxlabel = r'x (cm)'\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n elif self.ig == 2:\n setxlabel = r'r (cm)'\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n\n # show LEGEND\n plt.legend(loc=ilg, prop={'size': 12})\n\n # display PLOT\n plt.show(block=False)\n\n # save PLOT\n if self.fext == \"png\":\n plt.savefig('RESULTS/' + self.data_prefix + 'momentum_x_eq_canuto1997.png')\n if self.fext == \"eps\":\n plt.savefig('RESULTS/' + self.data_prefix + 'momentum_x_eq_canuto1997.eps')\n","sub_path":"CANUTO1997/MomentumEquationX.py","file_name":"MomentumEquationX.py","file_ext":"py","file_size_in_byte":8513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"189732639","text":"import unittest\n\nfrom representor import Representor\nfrom representor.contrib.browser import BrowserAdapter\n\nclass BrowserTest(unittest.TestCase):\n\n def setUp(self):\n Representor.adapters.add(BrowserAdapter)\n self.resource = Representor()\n\n def tearDown(self):\n Representor.reset_adapters()\n\n def test_links(self):\n self.resource.links.add(\"self\", \"/example\")\n html = self.resource.translate_to(\"text/html\")\n self.assertTrue('href=\"/example\"' in html)\n\n def test_link_label_set(self):\n self.resource.links.add(\"self\", \"/example\", label=\"Test Link!\")\n html = self.resource.translate_to(\"text/html\")\n self.assertTrue('>Test Link!' in html)\n\n def test_link_not_set(self):\n self.resource.links.add(\"self\", \"/example\", label=\"Test Link!\")\n html = self.resource.translate_to(\"text/html\")\n self.assertTrue('rel=\"self\"' in html)\n\n def test_page_title_set(self):\n self.resource.meta.attributes.add(\"title\", \"Test\")\n html = self.resource.translate_to(\"text/html\")\n self.assertTrue('Test ' in html)\n self.assertTrue('Test ' in html)\n\n def test_page_title_not_set(self):\n html = self.resource.translate_to(\"text/html\")\n self.assertTrue('Hypermedia Browser ' in html)\n self.assertTrue('Hypermedia Browser ' in html)\n\n def test_attributes(self):\n self.resource.attributes.add(\"foo\", \"bar\")\n self.resource.attributes.add(\"hello\", \"world\", label=\"Hello Attr\")\n html = self.resource.translate_to(\"text/html\")\n self.assertTrue('foo ' in html)\n self.assertTrue('bar ' in html)\n self.assertTrue('Hello Attr ' in html)\n\n def test_queries(self):\n query = self.resource.queries.add(\"search\", \"/search\")\n query.params.add(\"search_key\")\n query.params.add(\"another\", \"value-given\")\n html = self.resource.translate_to(\"text/html\")\n self.assertTrue(''\n\t\tx = str1\n\n\t\tstr1 = ' '\n\n\t\tamount_total = round(total,2)\n\t\tshipping_total = shipping_charge() #---- define a function for shipping charges\n\t\tgrand_total = amount_total + shipping_total\n\t\tprint (grandtotal(user))\n\t\treturn render(request,\"cart.html\",{\"data\":x,\"a_total\":amount_total,\n\t\t\t\"s_total\":shipping_total,\"g_total\":grand_total})\n\telse:\n\t\treturn HttpResponseRedirect('/signin/')\n\n\n@csrf_exempt\ndef change_qty(request):\n\tqty_global = request.POST.get(\"qty\")\n\tprint(qty_global)\n\treturn HttpResponseRedirect('/cart/')\n\n@csrf_exempt\ndef updatecart(request,id):\n\tuser = request.user.username\n\tobj1 = cart.objects.get(user=user,prod_id=id)\n\tprint(obj1.qty)\n\tobj1.qty = request.POST.get(\"qty\")\n\tprint(obj1.qty)\n\tobj1.save()\n\treturn HttpResponseRedirect('/cart/')\n\ndef totalamt(user):\n\ttotal = float(0)\n\n\tfor o in cart.objects.all():\n\t\tif o.user == user :\n\t\t\ttemp = products.objects.get(prod_id = o.prod_id )\n\t\t\tprice = o.price\n\t\t\toffer = temp.offer\n\t\t\trate = price - (price*offer/100)\n\t\t\tprint(\"rate = \" + str(rate))\n\t\t\ttotal += float(rate*o.qty)\n\t\t\ttotal = round(total,2)\n\n\treturn total\n\ndef shipping_charge():\n\treturn (250)\n\ndef grandtotal(user):\n\treturn totalamt(user) + shipping_charge()\n\ndef checkout(request):\n\tcontext = {}\n\tcontext[\"user\"] = request.user.username\n\tobj = login_data.objects.get(user=request.user.username)\n\tcontext[\"email\"] = obj.email\n\tcontext[\"contact\"] = obj.contact\n\tcontext[\"address\"] = obj.address\n\treturn render(request,\"checkout.html\",context)\n\n\ndef topayment(request):\n\torder_delivery.objects.create(\n\t\tuser = request.POST.get(\"user\"),\n\t\t#order_id = request.POST.get(\"user\"),\n\t\temail = request.POST.get(\"email\"),\n\t\taddress = request.POST.get(\"address\"),\n\t\tlandmark = request.POST.get(\"landmark\"),\n\t\tcity = request.POST.get(\"city\"),\n\t\tstate = request.POST.get(\"state\"),\n\t\tpincode = request.POST.get(\"pincode\")\n\t\t)\n\treturn render(request,\"checkout.html\",{})\n\n# def test1(request):\n# \tMERCHANT_KEY = \"gtKFFx\"\n# \tkey=\"gtKFFx\"\n# \tSALT = \"eCwWELxi\"\n# \tPAYU_BASE_URL = \"https://test.payu.in/_payment\"\n# \taction = ''\n# \tposted={}\n# \tfor i in request.POST:\n# \t\tposted[i]=request.POST[i]\n# \t\thash_object = hashlib.sha256(b'randint(0,20)')\n# \t\ttxnid=hash_object.hexdigest()[0:20]\n# \t\thashh = ''\n# \t\tposted['txnid']=txnid\n# \t\thashSequence = \"key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10\"\n# \t\tposted['key']=key\n# \t\thash_string=''\n# \t\thashVarsSeq = ''\n# \t\thashVarsSeq=hashSequence.split('|')\n# \tfor i in hashVarsSeq:\n# \t\ttry:\n# \t\t\thash_string+=str(posted[i])\n# \t\texcept Exception:\n# \t\t\thash_string+=''\n# \t\t\thash_string+='|'\n# \t\t\thash_string+=SALT\n# \thashh=hashlib.sha512(hash_string).hexdigest().lower()\n# \taction =PAYU_BASE_URL\n# \tif(posted.get(\"key\")!=None and posted.get(\"txnid\")!=None and posted.get(\"productinfo\")!=None and posted.get(\"firstname\")!=None and posted.get(\"email\")!=None):\n# \t\treturn render_to_response('welcome.html',RequestContext(request,{\"posted\":posted,\"hashh\":hashh,\"MERCHANT_KEY\":MERCHANT_KEY,\"txnid\":txnid,\"hash_string\":hash_string,\"action\":\"https://test.payu.in/_payment\" }))\n# \telse:\n# \t\treturn render_to_response('welcome.html',RequestContext(request,{\"posted\":posted,\"hashh\":hashh,\"MERCHANT_KEY\":MERCHANT_KEY,\"txnid\":txnid,\"hash_string\":hash_string,\"action\":\".\" }))\n\n\n# def test(request):\n# \tkey=\"gtKFFx\"\n# \ttxnid = \"abc123\"\n# \tamount = 100.00\n# \tproductinfo = \"test product\"\n# \tfirstname = \"sourabh\"\n# \temail = \"sourabh.modi14@gmail.com\"\n# \tphone = \"9039189251\"\n# \tSALT = \"eCwWELxi\"\n# \tsurl = \"http://127.0.0.1:8000/welcome/\"\n# \tfurl = \"http://www.google.com/\"\n# \thashgen = ''\n# \thashgen= sha512(key|txnid|amount|productinfo|firstname|email|||||||||||SALT)\n\n# \tPAYU_BASE_URL = \"https://test.payu.in/_payment\"\n# \tPOST_DATA = [('key','')]\n\n# \treturn HttpResponse(\"DONE \")\n\n\n###########################-----action on proceed to checkout-----###########################\n\n\ndef func(request):\n\tcontext = {}\n\tusername = request.user.username\n\tobj1 = login_data.objects.get(user = username)\n\tcontext[\"user\"] = username\n\tcontext[\"productinfo\"] = \"product\"\n\tcontext[\"firstname\"] = username\n\tamount = grandtotal(username)\n\tamount = round(amount,2)\n\tcontext[\"amount\"] = amount\n\temail = str(obj1.email)\n\tcontext[\"email\"] = email\n\tcontext[\"phone\"] = obj1.contact\n\n\treturn render(request,\"checkout.html\",context)\n\n\n\n\n###########################-----HASH GENERATION PAYEMNT GATEWAY-----###########################\n\n# KEYS = ('key', 'txnid', 'amount', 'productinfo', 'firstname', 'email',\n# 'udf1', 'udf2', 'udf3', 'udf4', 'udf5', 'udf6', 'udf7', 'udf8',\n# 'udf9', 'udf10')\n\n\n# def generate_hash(data):\n# # keys = ('key', 'txnid', 'amount', 'productinfo', 'firstname', 'email','eCwWELxi')\n# # hash = sha512(''.encode('utf-8'))\n# # for key in KEYS: #key or keys - get it confirmed\n# # hash.update(\"%s%s\" % (str(data.get(key, '')).encode('utf-8'), '|'))\n# d = ''\n# for key in KEYS:\n# \td += \"%s%s\" % (str(data.get(key)),'|')\n# print(d)\n# print (\"new\")\n# hash = sha512(d.encode('utf-8'))\n# # hash.update(d.encode('utf-8'))\n# hash.update(settings.PAYU_INFO.get('merchant_salt').encode('utf-8'))\n# print (hash)\n# return hash.hexdigest().lower()\n\n\n# def verify_hash(data, SALT):\n# keys.reverse()\n# hash = sha512(settings.PAYU_INFO.get('merchant_salt'))\n# hash.update(\"%s%s\" % ('|', str(data.get('status', ''))))\n# for key in KEYS:\n# hash.update(\"%s%s\" % ('|', str(data.get(key, ''))))\n# return (hash.hexdigest().lower() == data.get('hash'))\n\n\n\n\n# hash_o = hash_o.encode('utf-8')\n\t# data = \"\"\"\n\t# Redirecting... \n\t# \n\t# \n\t# \n\t# \n\t# \n # \"\"\" % (settings.PAYU_INFO['payment_url'],\n # \tname,\n # \tsettings.PAYU_INFO['surl'],\n # \t9039189251,\n # \tsettings.PAYU_INFO['merchant_key'],\n # \thash_o,settings.PAYU_INFO['curl'],\n # \tsettings.PAYU_INFO['furl'],\n # \ttxnid,\n # \tproduct_title,\n # \tamount,\n # \temail\n # \t)\n\n\t# return HttpResponse(\"hello\")\n\n###########################-----REDIRECT FROM CHECKOUT TO THANK YOU PAGE-----###########################\n\n\n@csrf_exempt\ndef thankyou(request):\n# \ttry:\n\tusername = request.POST.get(\"user\")\n\tfor o in cart.objects.filter(user=username):\n\t\tobj = products.objects.get(prod_id=o.prod_id)\n\t\torder_content.objects.create(\n\t\t\tuser = username,\n\t\t\tprod_name = o.prod_name,\n\t\t\tprod_id = o.prod_id,\n\t\t\tprice = o.price,\n\t\t\tqty = o.qty,\n\t\t\toffer = obj.offer\n\t\t\t)\n\tprint(\"1\");\n\torder_delivery.objects.create(\n\t\tuser = request.POST.get(\"user\"),\n\t\temail = request.POST.get(\"email\"),\n\t\taddress = request.POST.get(\"address\"),\n\t\tlandmark = request.POST.get(\"landmark\"),\n\t\tcity = request.POST.get(\"city\"),\n\t\tstate = request.POST.get(\"state\"),\n\t\tpincode = request.POST.get(\"pincode\")\n\t\t)\n\n\tmsg = \"\"\"Hello Admin.\n\tThe user - %s has placed an order. Please visit the admin panel and check the order under \"Order Content\" for order details and \"Order Delivery\" for details of delivery\n\tContact details of user:\n\tName : %s\n\tContact : %s\n\tEmail : %s\n\tcity : %s\n\n\n\tFollow the link\n\tOrder Contents : http://srb1403.pythonanywhere.com/admin/orders/order_content/\n\tOrder Delivery : http://srb1403.pythonanywhere.com/admin/orders/order_delivery/\n\n\n\tThank You. Have A great Day.\n\t\"\"\"\n\tsend_mail(\n\t\t\t\"New Order from MediFudo.com\",\n\t\t\tmsg %(username,username,request.POST.get(\"contact\"),request.POST.get(\"email\"),request.POST.get(\"city\")),\n\t\t\t'sourabhrocks14@gmail.com',\n\t\t\t[str(email)],\n\t\t\tfail_silently=False,\n\t\t\t)\n\n\tcontext = {}\n\tcontext[\"message\"] = \"Thank You. You will soon be contacted by our representative.\"\n\n\treturn render(request,\"thankyou.html\",context)\n# \texcept Exception as e:\n# \t print (str(e))\n# \t context = {}\n# \t context[\"message\"] = \"Sorry. We were unale to process your request due to some internal error.Please try again\"\n# \t return render(request,\"thankyou.html\",context)\n\n\n\n\n\n# @csrf_exempt\n# def thankyou(request):\n# \ttry:\n# \t\tusername = request.POST.get(\"user\")\n# \t\tfor o in cart.objects.filter(user=username):\n# \t\t\tobj = adminpanel.objects.filter(prod_id=o.prod_id)\n# \t\t\torder_content.objects.create(\n# \t\t\t\tuser = username,\n# \t\t\t\tprod_name = o.prod_name,\n# \t\t\t\tprod_id = o.prod_id,\n# \t\t\t\tprice = o.price,\n# \t\t\t\tqty = o.qty,\n# \t\t\t\toffer = obj.offer\n# \t\t\t\t)\n# \t\torder_delivery.objects.create(\n# \t\t\tuser = request.POST.get(\"user\"),\n# \t\t\temail = request.POST.get(\"email\"),\n# \t\t\taddress = request.POST.get(\"address\"),\n# \t\t\tlandmark = request.POST.get(\"landmark\"),\n# \t\t\tcity = request.POST.get(\"city\"),\n# \t\t\tstate = request.POST.get(\"state\"),\n# \t\t\tpincode = request.POST.get(\"pincode\")\n# \t\t\t)\n\n# \t\tmsg = \"\"\"Hello Admin.\n# \t\tThe user - %s has placed an order. Please visit the admin panel and check the order under \"Order Content\" for order details and \"Order Delivery\" for details of delivery\n# \t\tContact details of user:\n# \t\tName : %s\n# \t\tContact : %s\n# \t\tEmail : %s\n# \t\tcity : %s\n\n\n# \t\tFollow the link\n# \t\tOrder Contents : http://srb1403.pythonanywhere.com/admin/orders/order_content/\n# \t\tOrder Delivery : http://srb1403.pythonanywhere.com/admin/orders/order_delivery/\n\n\n# \t\tThank You. Have A great Day.\n# \t\t\"\"\"\n# \t\tsend_mail(\n# \t\t\t\t\"New Order from MediFudo.com\",\n# \t\t\t\tmsg %(username,username,request.POST.get(\"contact\"),request.POST.get(\"email\"),request.POST.get(\"city\")),\n# \t\t\t\t'sourabhrocks14@gmail.com',\n# \t\t\t\t[str(email)],\n# \t\t\t\tfail_silently=False,\n# \t\t\t\t)\n\n# \t\tcontext = {}\n# \t\tcontext[\"message\"] = \"Thank You. You will soon be contacted by our representative.\"\n\n# \t\treturn render(request,\"thankyou.html\",context)\n# \texcept Exception as e:\n# \t\tprint(e)\n# \t\tcontext = {}\n# \t\tcontext[\"message\"] = \"Sorry. We were unale to process your request due to some internal error.Please try again Later\"\n# \t\treturn render(request,\"thankyou.html\",context)\n","sub_path":"herbal/orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"75708680","text":"# -*- coding: utf-8 -*- \n# @Time : 2021/3/16 16:07 \n# @Author : HGuoo \n# @File : search.py\nfrom test1.cal_time import *\n\n\n@cal_time\ndef linear_search(lst, val):\n for i in range(len(lst) - 1):\n if val == lst[i]:\n return val\n return None\n\n\n@cal_time\ndef binary_search(lst, val):\n left = 0\n right = len(lst) - 1\n while left <= right:\n mid = (left + right) // 2\n if lst[mid] == val:\n return mid\n elif lst[mid] > val:\n right = mid - 1\n else:\n left = mid + 1\n\n return None\n\n\nli = list(range(10000000))\nbinary_search(li, 4325521)\nlinear_search(li, 92888)\n","sub_path":"test1/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"407294802","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 25 14:19:57 2017\n\n@author: sinlight\n\"\"\"\nimport pandas as pd\n\n\ndef getNewcity(cityfrom,fromname):#原始city数据表,来源域名,\n '''\n 得到删除多余列的城市列表\n '''\n city=cityfrom.loc[:,['province', 'city', 'city_id']]\n city_id = fromname+'_id'\n city.rename(columns={'city_id':city_id}, inplace=True)\n city.drop_duplicates(inplace=True)\n return city\n\ndef getFormatedcity(cityfrom,fromname):\n city=cityfrom.loc[:,['city', 'city_id']]\n city.drop_duplicates(inplace = True)\n \n city_id = fromname+'_id'\n city_id1 = fromname+'_id1'\n city_id2 = fromname+'_id2'\n city_id3 = fromname+'_id3'\n city_id4 = fromname+'_id4'\n \n #得到空的城市id对应表\n #city1 = cityfrom.loc[:,['city']]#得到的是数据框\n city1 = cityfrom.loc[:,'city']#得到的是series\n city1 = city1.dropna()\n city1 = city1[city1 != 'None']\n city1.drop_duplicates(inplace = True) #得到的是Series\n citylist = list(city1) \n newCity = pd.DataFrame({'city':citylist})\n newCity['province'] =''\n newCity[city_id] =''\n # city_id1:'', city_id2:'', city_id3:'', city_id4:''}\n newCity[city_id1] =''\n newCity[city_id2] =''\n newCity[city_id3] =''\n newCity[city_id4] =''\n \n #将表格融合\n for j in city.index:\n for i in newCity.index:\n if city.loc[j,'city'] == newCity.loc[i,'city']:\n #合并\n if newCity.loc[i,city_id] == '':\n newCity.loc[i,city_id] = city.loc[j,'city_id']\n elif newCity.loc[i,city_id1] == '':\n newCity.loc[i,city_id1] = city.loc[j,'city_id']\n elif newCity.loc[i,city_id2] == '':\n newCity.loc[i,city_id2] = city.loc[j,'city_id']\n elif newCity.loc[i,city_id3] == '':\n newCity.loc[i,city_id3] = city.loc[j,'city_id']\n else :\n newCity.loc[i,city_id4] = city.loc[j,'city_id']\n break\n leng = len(newCity.index)\n \n if list(newCity.loc[:,city_id4]).count('')==leng:\n newCity.drop(city_id4,axis=1,inplace = True)\n if list(newCity.loc[:,city_id3]).count('')==leng:\n newCity.drop(city_id3,axis=1,inplace = True)\n if list(newCity.loc[:,city_id2]).count('')==leng:\n newCity.drop(city_id2,axis=1,inplace = True)\n if list(newCity.loc[:,city_id1]).count('')==leng:\n newCity.drop(city_id1,axis=1,inplace = True)\n \n return newCity\n \n \ndef cityUnion(dlist):#城市数据框的列表\n '''\n 将城市列表汇总到一起,得到汇总数据框\n '''\n city_union = dlist[0]\n for k in range(1,len(dlist)):\n #city_union = pd.merge(city_union,dlist[k],how='outer')\n city_union = pd.merge(city_union,dlist[k],on=['city'],how='outer')\n return city_union\n'''\n先得到所有城市列表,作为基础左连接\n\n\n'''\n\n\n\n\ndef addProvince(todata,provinces) : #要添加的数据框,省份对应表\n '''\n 对文件的城市添加对应的省份\n '''\n plist=[]\n for i in range(0,len(todata.index)): \n flag=''\n for j in range(0,len(provinces.index)):\n if todata.city[i] in provinces.city[j] or todata.city[i] in provinces.city1[j]:\n flag=provinces.province[j]\n break\n plist.append(flag)\n todata['province']=plist\n return todata","sub_path":"RuleWBC/Python/合并/房产/1/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"144105441","text":"import bpy\nimport json\n\nfrom . import exporter\nfrom . import importer\n\nbl_info = {\n 'name': 'Cycles Node IO',\n 'category': 'Material'\n}\n\ndef register():\n print(\"Hello World\")\ndef unregister():\n print(\"Goodbye World\")\n\n\n\n#serialized = serializeMaterial(bpy.data.materials['Material'])\n#json = json.dumps(serialized, indent=4)\n#f = open('mat_output.json', 'w')\n#f.write(json)\n#f.close()\n#print(json)\n#restoreMaterial(serialized)\n\n\n#from importlib.machinery import SourceFileLoader\ndef load():\n global c\n c = SourceFileLoader(\"cycles_node_io\", \"O:/Projects4-Blender/cycles-node-io/__init__.py\").load_module()\n\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"375139579","text":"# Date: 05/03/2018\r\n# Author: Pure-L0G1C\r\n# Description: Proxy scraper\r\n\r\nfrom requests import get\r\nfrom bs4 import BeautifulSoup as bs \r\n\r\nclass Queue(object):\r\n\r\n def __init__(self):\r\n self.queue = []\r\n \r\n def put(self, item):\r\n if not item in self.queue:\r\n self.queue.append(item)\r\n\r\n def get(self):\r\n if self.qsize:\r\n return self.queue.pop(0)\r\n\r\n def inQueue(self, item):\r\n return item in self.queue \r\n\r\n @property \r\n def qsize(self):\r\n return len(self.queue)\r\n\r\nclass Scraper(object):\r\n\r\n def __init__(self):\r\n self.anony_proxis = 'https://free-proxy-list.net/anonymous-proxy.html'\r\n self.new_proxies = 'https://free-proxy-list.net'\r\n self.socks_proxies = 'https://socks-proxy.net'\r\n self.ssl_proxies = 'https://sslproxies.org'\r\n self.ip_checker = 'https://ip-api.io/json/'\r\n self.isAlive = False\r\n self.protocol = None\r\n self.country = None\r\n self.proxies = None\r\n self.maxSize = None\r\n self.port = None \r\n\r\n def parse(self, proxy, ssl=False):\r\n detail = {'ip': proxy[0].string, 'port': proxy[1].string,\r\n 'protocol': 'SSL' if ssl else proxy[4].string, \r\n 'anonymity': proxy[4 if ssl else 5].string, \r\n 'country': proxy[3].string,\r\n 'updated': proxy[7].string,\r\n 'https': proxy[6].string}\r\n\r\n if all([self.protocol, self.country, self.port]):\r\n if detail['protocol'].lower() == self.protocol.lower():\r\n if detail['country'].lower() == self.country.lower():\r\n if detail['port'] == self.port:\r\n return detail\r\n elif all([self.protocol, self.country]):\r\n if detail['protocol'].lower() == self.protocol.lower():\r\n if detail['country'].lower() == self.country.lower():\r\n return detail\r\n elif all([self.protocol, self.port]):\r\n if detail['protocol'].lower() == self.protocol.lower():\r\n if detail['port'] == self.port:\r\n return detail\r\n elif all([self.country, self.port]):\r\n if detail['country'].lower() == self.country.lower():\r\n if detail['port'].lower() == self.port:\r\n return detail\r\n elif self.protocol:\r\n return None if detail['protocol'].lower() != self.protocol.lower() else detail\r\n elif self.country:\r\n return None if detail['country'].lower() != self.country.lower() else detail\r\n elif self.port:\r\n return None if detail['port'] != self.port else detail\r\n else:\r\n return detail\r\n\r\n def fetch(self, url, ssl=False):\r\n try:proxies = bs(get(url).text, 'html.parser').find('tbody').findAll('tr')\r\n except KeyboardInterrupt:self.isAlive = False;return\r\n except:return\r\n \r\n for proxy in proxies:\r\n if not self.isAlive:break\r\n data = self.parse(proxy.findAll('td'), ssl)\r\n if data:\r\n if self.maxSize:\r\n if self.proxies.qsize < self.maxSize:\r\n self.proxies.put(data)\r\n else:break\r\n else:\r\n self.proxies.put(data)\r\n \r\n def scrape(self, size=None, port=None, protocol=None, country=None):\r\n self.port = str(port) if port else None \r\n self.protocol = protocol\r\n self.country = country\r\n self.proxies = Queue()\r\n self.maxSize = None\r\n self.isAlive = True\r\n self.isAlive = True\r\n self.maxSize = size\r\n\r\n if protocol:\r\n if all([protocol.lower() != 'ssl', protocol.lower() != 'socks4', protocol.lower() != 'socks5']):\r\n print('Only Supporting SSL & Socks protocol')\r\n return \r\n\r\n if self.isAlive:self.fetch(self.new_proxies)\r\n if self.isAlive:self.fetch(self.anony_proxis)\r\n if self.isAlive:self.fetch(self.socks_proxies)\r\n if self.isAlive:self.fetch(self.ssl_proxies, True)\r\n proxies = self.proxies\r\n self.proxies = Queue()\r\n return proxies\r\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"542147275","text":"#!/usr/bin/python\n\nimport cgi\nimport datetime\nimport re\nimport urllib\nfrom xml.etree import ElementTree as etree\n\nimport bottle\nimport pymongo\n\ndb = pymongo.Connection().test.videoq\n\n\n################################################################################\n\nNICOVIDEO_ID_RE = re.compile(r'^(sm|nm)\\d+$')\n\ndef get_video_title(video_id):\n if NICOVIDEO_ID_RE.match(video_id):\n u = urllib.urlopen('http://ext.nicovideo.jp/api/getthumbinfo/%s' % video_id)\n response = u.read()\n u.close()\n doc = etree.fromstring(response)\n return doc.find('thumb/title').text\n raise ValueError('Unrecognized video_id: %s' % video_id)\n\n\n################################################################################\n\n@bottle.get('/')\ndef IndexHandler():\n queue = list(db.queue.find(\n {'processed_time': None},\n sort=[('creation_time', pymongo.ASCENDING)]))\n return bottle.template('index.html', queue=queue)\n\n\n@bottle.get('/play')\ndef PlayHandler():\n video = db.queue.find_one(\n {'processed_time': None},\n sort=[('creation_time', pymongo.ASCENDING)])\n if not video:\n return bottle.template('play_empty.html')\n video['lyrics_html'] = (\n cgi.escape(video['lyrics'], quote=True).replace('\\n', ' '))\n return bottle.template('play.html', video=video)\n\n\n@bottle.post('/queue')\ndef QueueHandler():\n video_id = bottle.request.params['video_id']\n lyrics = bottle.request.params['lyrics']\n title = get_video_title(video_id)\n db.queue.save({\n 'video_id': video_id,\n 'title': title,\n 'lyrics': lyrics,\n 'creation_time': datetime.datetime.now(),\n })\n return bottle.template('queued.html', title=title)\n\n\n@bottle.post('/next')\ndef NextHandler():\n db.queue.update(\n {'processed_time': None},\n {'$set': {'processed_time': datetime.datetime.now()}},\n sort=[('creation_time', pymongo.ASCENDING)])\n bottle.redirect('/play')\n\n\n################################################################################\n\nbottle.debug()\napp = bottle.app()\n\n\ndef main():\n bottle.run(app=app, host='0.0.0.0', port=8080, server='wsgiref',\n reloader=True, interval=1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"videoq/videoq.py","file_name":"videoq.py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"120058607","text":"import sys\n\nf1 = sys.argv[1]\nf2 = sys.argv[2]\n\nfile1 = open(f1, \"r\")\nfile2 = open(f2, \"r\")\nline1 = file1.readlines()\nline2 = file2.readlines()\n\nfor k in range(len(line1)):\n\tcon1 = line1[k].rstrip(\"\\n\").split(\" \")\n\tcon2 = line2[k].rstrip(\"\\n\").split(\" \")\n\t\n\tfor i in range(len(con1)):\n\t\tprint(\"0\"+\"\\t\"+\"0\"+\"\\t\"+con1[i]+\"\\t\"+con2[i])\nprint(\"0\")\n\t\t\n","sub_path":"uni-to-zawgyi-syllable-fst/zaw-uni.py","file_name":"zaw-uni.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"390532539","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Data structures for registries.\"\"\"\n\nfrom dataclasses import dataclass\n\n__all__ = [\n \"Registry\",\n \"miriam\",\n \"ols\",\n \"obofoundry\",\n]\n\n\n@dataclass\nclass Registry:\n \"\"\"Represents a place to look up namespaces.\"\"\"\n\n #: The name of the registry\n name: str\n\n #: The url that can be used to look up a resource.\n resolution_url: str\n\n def resolve_resource(self, resource: str) -> str:\n \"\"\"Get the URl for the given resource.\"\"\"\n return self.resolution_url + resource\n\n\nmiriam = Registry(\n name=\"miriam\",\n resolution_url=\"https://registry.identifiers.org/registry/\",\n)\n\nols = Registry(\n name=\"ols\",\n resolution_url=\"https://www.ebi.ac.uk/ols/ontologies/\",\n)\n\nobofoundry = Registry(\n name=\"obofoundry\",\n resolution_url=\"http://www.obofoundry.org/ontology/\",\n)\n","sub_path":"src/pyobo/struct/registry.py","file_name":"registry.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"652926550","text":"import FWCore.ParameterSet.Config as cms\n\nfrom RecoLocalCalo.EcalRecAlgos.ecalCleaningAlgo import cleaningAlgoConfig \n\n\nprocess = cms.Process(\"Ana\")\n\n\nprocess.load(\"Configuration.Geometry.GeometryECALHCAL_cff\")\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\nfrom RecoEcal.Configuration.RecoEcal_cff import *\n\nprocess.load(\"EventFilter.EcalRawToDigi.EcalUnpackerMapping_cfi\");\nprocess.load(\"EventFilter.EcalRawToDigi.EcalUnpackerData_cfi\");\n\n\nprocess.ecalEBunpacker.InputLabel = cms.InputTag('rawDataCollector');\n#process.ecalEBunpacker.InputLabel = cms.InputTag('source');\n\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff\")\n\n#process.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nprocess.load(\"RecoLocalCalo.EcalRecAlgos.EcalSeverityLevelESProducer_cfi\")\n\nprocess.EcalLaserCorrectionService = cms.ESProducer(\"EcalLaserCorrectionService\")\n\n\n\n\n# global tag for data\n#process.GlobalTag.globaltag = 'GR_R_53_V21A::All'\n\n# run 2\n#process.GlobalTag.globaltag = '74X_dataRun2_Prompt_v4'\n#process.GlobalTag.globaltag = '74X_dataRun2_EcalCalib_v1'\n#process.GlobalTag.globaltag = '76X_dataRun2_v15'\n#process.GlobalTag.globaltag = '76X_dataRun2_v19'\n#process.GlobalTag.globaltag = '80X_dataRun2_Prompt_v9'# PATRIZIA\nprocess.GlobalTag.globaltag = '74X_dataRun2_Prompt_v1' # Matt\n\n\n\n############# Set the number of events #############\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(-1)\n)\n############# Define the source file ###############\nprocess.source = cms.Source(\"PoolSource\",\n\n\n fileNames=cms.untracked.vstring(\n\n# Data\n\n#'file:/afs/cern.ch/user/m/mquittna/public/exo/EXOMoriond16_v6_0T/pickeventsrunC.root'\n#'file:/afs/cern.ch/work/p/pbarria/public/SingleEvent/CMSSW_8_3_0/src/JetMETCorrections/MCJet/pick1eventRUN274244.root'\n# 'file:/afs/cern.ch/user/m/mjoyce/WorkingArea/Ecal/CMSSW_8_3_0/src/JetMETCorrections/MCJet/EventCheck/pickevents_test.root'\n 'file:/afs/cern.ch/user/m/mjoyce/WorkingArea/Ecal/CMSSW_8_3_0/src/JetMETCorrections/MCJet/EventCheck/pickevents.root'\n ))\n\n\n\n############# Geometry ###############\n\nprocess.load(\"Geometry.CMSCommonData.cmsIdealGeometryXML_cfi\");\nprocess.load(\"Geometry.CaloEventSetup.CaloGeometry_cfi\");\nprocess.load(\"Geometry.CaloEventSetup.CaloTopology_cfi\");\n\n\n############# Analyser options ############################\nprocess.eventanalyser = cms.EDAnalyzer(\"EventAnalyser\",\njets = cms.string('ak5PFJets'),\nhistogramFile = cms.string('exomgg_0t_runC.root'),\ntracks = cms.string('generalTracks'),\nvertex = cms.string('offlinePrimaryVertices'),\nJetCorrectionService = cms.string('L2L3JetCorrectorAK5PF'),\nEBRecHitCollection = cms.string('ReducedEcalRecHitsEB'),\nEERecHitCollection = cms.string('ReducedEcalRecHitsEE'),\nIsMC = cms.bool(False), # set to True if using MC\ncleaningConfig = cleaningAlgoConfig,\n\n\n# bunch structure, run 200473 - 50ns\nbunchstartbx = cms.vint32(66,146,226,306,413,493,573,653,773,853,960,1040,1120,1200,1307,1387,1467,1547,1667,1747,1854,1934,2014,2094,2201,2281,2361,2441,2549,2629,2736,2816,2896,2976,3083,3163,3243,3323)\n\n# bunch structure, run 209146 - 25ns\n\n#bunchstartbx = cms.vint32(301,358,1195,1252,2089,2146,2977,3034)\n# run 203708\n#bunchstartbx = cms.vint32(1786,2680)\n\n )\nprocess.noscraping = cms.EDFilter(\"FilterOutScraping\",\n applyfilter = cms.untracked.bool(True),\n debugOn = cms.untracked.bool(False),\n numtrack = cms.untracked.uint32(10),\n thresh = cms.untracked.double(0.25)\n )\n\n\nprocess.primaryVertexFilter = cms.EDFilter(\"GoodVertexFilter\",\n vertexCollection = cms.InputTag('offlinePrimaryVertices'),\n minimumNDOF = cms.uint32(4) ,\n maxAbsZ = cms.double(24),\n maxd0 = cms.double(2)\n )\n\n\nprocess.load('CommonTools/RecoAlgos/HBHENoiseFilter_cfi')\n\n\n#process.load('RecoMET.METFilters.eeBadScFilter_cfi')\n\n############# Path ###########################\n\n\n\n# data\n\nprocess.p = cms.Path( process.eventanalyser)\n\n\n\n############# Format MessageLogger #################\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 1\n\n\n","sub_path":"test/datacheck_cfg.py","file_name":"datacheck_cfg.py","file_ext":"py","file_size_in_byte":4541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"140989394","text":"from .api import PLURK\nfrom .handler import handle_plurk,handle_response,repeat_event\nimport time\nimport json\nimport sys\nfrom datetime import datetime,timedelta\ntry:\n import readline\nexcept ImportError:\n print(\"readline module import failed. This may cause some input problem.\")\n\ndebug=False\n\nclass pyplurky():\n def __init__(self,mode,key=\"API.keys\",debug=False):\n self.__mode=mode # \"REPL\",\"BOT\"\n self.__key=key\n self.plurk = PLURK.fromfile(key)\n self.__error=\"\"\n self.status = 0\n self.__offset=0\n self.__response_handler={}\n self.__plurk_handler={}\n\n if not self.plurk.keyvalid:\n self.status = 2\n\n def addPlurkHandler(self,keyword,replyword):\n self.__plurk_handler[keyword]=replyword\n\n def addResponseHandler(self,keyword,replyword):\n self.__response_handler[keyword]=replyword\n\n\n\n def init_main(self):\n #print(\"Pass in init.\")\n if not self.plurk.is_authorized():\n try:\n print(\"打開網址以取得驗證碼:\\n\",self.plurk.get_verifier_url())\n akey=self.plurk.get_access_token(input(\"驗證碼: \"))\n with open(self.__key, 'r') as f:\n d = json.load(f)\n d[\"ACCESS_TOKEN\"]=akey['key']\n d[\"ACCESS_TOKEN_SECRET\"]=akey['secret']\n with open(self.__key, 'w') as f:\n json.dump(d, f, indent=4)\n print(\"\")\n return 1\n except KeyboardInterrupt:\n return 2\n except:\n return 99\n else:\n print(\"\")\n return 1\n\n\n\n def idle_main(self):\n if not self.plurk.is_authorized():\n return 0\n #print(\"Pass in idle.\")\n if debug:\n cmd=input(\"\\033[0;33m[pyplurky]❯ \\033[0m\")\n if cmd==\"exit\":\n return 2\n p=self.plurk\n print(eval(cmd))\n return 1\n else:\n try:\n cmd=input(\"\\033[0;33m[pyplurky]❯ \\033[0m\")\n if cmd==\"exit\":\n return 2\n elif cmd==\"\":\n return 1\n p=self.plurk\n print(eval(cmd))\n return 1\n except KeyboardInterrupt:\n print(\"\\nInput to leave.\")\n return 1\n except Exception as e:\n self.__error=e\n return 99\n\n def listening(self):\n \"\"\"Main program\"\"\"\n if debug:\n repeat_event(self.plurk)\n comet_data=self.plurk.realtime.get(self.__offset)\n self.__offset=comet_data.new_offset\n for d in comet_data.data:\n if d.type==\"new_response\":\n handle_response(d,self.plurk)\n elif d.type==\"new_plurk\":\n handle_plurk(d,self.plurk)\n return 1\n else:\n try:\n repeat_event(self.plurk)\n comet_data=self.plurk.realtime.get(self.__offset)\n self.__offset=comet_data.new_offset\n for d in comet_data.data:\n if d.type==\"new_response\":\n handle_response(d,self.plurk,self.__response_handler)\n elif d.type==\"new_plurk\":\n handle_plurk(d,self.plurk,self.__plurk_handler)\n except Exception as e:\n self.__error=e\n return 99\n\n return 1\n\n\n def error(self):\n #print(plurk.error())\n t=type(self.__error).__name__+\": \"+str(self.__error)+\"\\n\"\n sys.stderr.write(t)\n\n self.__error=\"\"\n return 1\n\n\n def state_handler(self,status):\n if self.status==0:\n return self.init_main()\n elif self.status==1:\n if self.__mode==\"REPL\":\n return self.idle_main()\n elif self.__mode==\"BOT\":\n return self.listening()\n elif self.status==99:\n return self.error()\n elif self.status==2:\n return -1\n\n\n def main(self):\n try:\n \"\"\"Main program\"\"\"\n while 1:\n self.status=self.state_handler(self.status)\n if self.status==-1:break\n except KeyboardInterrupt:\n print(\"\\rSee you again.\")\n","sub_path":"pyplurky/pyplurky.py","file_name":"pyplurky.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"86205901","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 6 15:26:45 2018\n\n@author: boutinaud\n\"\"\"\n\nimport os\nimport time\nimport re\n\nimport numpy as np\n\nimport T1.T1_dataset as t1\nfrom core.model_factory import ModelFactory\nfrom core.model import HyperP\nfrom core.loss_functions import loss_functions_map\nfrom core.metrics import metrics_functions_map\nfrom keras.models import load_model\n\nimport nibabel as nib\n\n#only one GPU used\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\n\n# For GPUGIN\n#inputDir = r'/ssd/scratch/boutinaud/SHARE/T1'\n#runDir = r'/ssd/scratch/boutinaud/SHARE/T1/Results/BasicAuto'\n#For DEEPGIN\ninputDir = r'/bigdata/SHARE/datamodif/T1/'\nrunDir = r'/bigdata/SHARE/Results/T1/BasicAuto'\n# Where the logs are for tensorboard \nlogDir = os.path.join(runDir, r'logs')\n\n#Read the Dataset\ntime0 = time.perf_counter()\ndata = t1.T1Dataset()\ndata.from_h5('/homes_unix/SHARE/datamodif/T1/T1BigFile1.h5',\n foldnumber= 0,\n testPath='/homes_unix/SHARE/datamodif/T1/annotated_T1BigFile.h5')\n\ntime1 = time.perf_counter()\nread_time = time1 - time0\nprint(f'Time reading dataset {read_time} sec.')\n#%%\n\nmodelDir = r'/bigdata/SHARE/Results/T1/BasicAuto'\n\nmodelNames = [\n# 'SWWAE_1.7.2_res.xlsx',\n# 'SWWAE_2.7.2_res.xlsx',\n# 'SWWAE_4.7.2_res.xlsx',\n 'VGG_4.1.2_res.xlsx',\n 'VGG_4.2.2_res.xlsx',\n 'VGG_4.3.2_res.xlsx',\n 'VGG_4.4.2_res.xlsx',\n 'VGG_4.5.2_res.xlsx',\n 'VGG_4.6.2_res.xlsx',\n 'VGG_4.7.2_res.xlsx'\n]\n\nlimagesid = ['0055', '0228', '0604', '0980', '1113', '1197', '1322', '1496', '1598', '1684']\n#limagesid = ['0055', '1684']\noutputdir = '/bigdata/SHARE/Results/T1/AnnotatedAE'\n\nfor modelName in modelNames :\n modelExcel = os.path.join(modelDir, modelName)\n re_type = re.search(r'(.*)_res.xlsx', modelName)\n modelType = re_type.group(1)\n # Read the hyper param file\n hyperp_list = HyperP.from_excel(modelExcel)\n hyperp = hyperp_list[0]\n \n modelObj = ModelFactory().makeModel(hyperp['Model/classname'], rundir=runDir, \n logdir=logDir, hyperp=hyperp)\n modelObj.model = load_model(hyperp['Model/modelfile'], custom_objects={**loss_functions_map, **metrics_functions_map})\n modelObj.model.load_weights(hyperp.get('Model/weightsfile'))\n \n for idimg in limagesid:\n odir = os.path.join(outputdir, idimg)\n if not os.path.exists(odir):\n os.makedirs(odir)\n # Get the image for this id in tests\n locs = data.test_ids.index[data.test_ids == idimg].tolist()\n if len(locs) == 0:\n print(f'Error : data.test_ids {idimg} no found')\n continue\n loc = locs[0]\n # Get the input image from h5\n image = data.test_images[loc]\n # Write the input image & mask\n imgPath = os.path.join(odir,f'input_{idimg}')\n if not os.path.exists(imgPath):\n niftimg = nib.Nifti1Image(image, affine=np.eye(4))\n nib.save(niftimg, imgPath)\n mskPath = os.path.join(odir,f'mask_{idimg}')\n if not os.path.exists(mskPath):\n mask = data.mask_images[loc]\n niftimg = nib.Nifti1Image(image, affine=np.eye(4))\n nib.save(niftimg, mskPath)\n\n # Get the image through the model\n decoded_image = modelObj.get_encoded_image(image) \n niftimg = nib.Nifti1Image(decoded_image, affine=np.eye(4))\n nib.save(niftimg, os.path.join(odir,f'{modelType}_{idimg}.nii'))\n \n print(f'Images written for id {idimg}')\n \n\n \n","sub_path":"T1/T1_play_model2.py","file_name":"T1_play_model2.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"98440521","text":"from tkinter import *\nfrom tkinter.colorchooser import *\nfrom tkinter.simpledialog import *\n\n\n## 함수 선언 부분 ##\ndef mouseClick(event):\n global x1, y1, x2, y2\n x1 = event.x\n y1 = event.y\n\n\ndef mouseDrop(event):\n global x1, y1, x2, y2, penWidth, penColor\n x2 = event.x\n y2 = event.y\n if curShape == LINE:\n canvas.create_line(x1, y1, x2, y2, width=penWidth, fill=penColor)\n else :\n canvas.create_oval(x1, y1, x2, y2, width=penWidth, outline=penColor, fill='white')\n\n\ndef getColor():\n global penColor\n color = askcolor()\n penColor = color[1]\n\n\ndef getWidth():\n global penWidth\n penWidth = askinteger(\"선 두께\", \"선 두께(1~10)를 입력하세요\", minvalue=1, maxvalue=10)\n\ndef changeShape(sp) :\n global curShape\n curShape = sp\n\n## 전역 변수 선언 부분 ##\nwindow = None\ncanvas = None\nx1, y1, x2, y2 = None, None, None, None # 선의 시작점과 끝점\npenColor = 'black'\npenWidth = 5\nLINE, CIRCLE= 0, 1\ncurShape = LINE\n\n## 메인 코드 부분 ##\nif __name__ == \"__main__\":\n window = Tk()\n window.title(\"그림판과 비슷한 프로그램\")\n canvas = Canvas(window, height=300, width=300)\n canvas.bind(\"\", mouseClick)\n canvas.bind(\"\", mouseDrop)\n canvas.pack()\n\n mainMenu = Menu(window)\n window.config(menu=mainMenu)\n fileMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"설정\", menu=fileMenu)\n fileMenu.add_command(label=\"선 색상 선택\", command=getColor)\n fileMenu.add_separator()\n fileMenu.add_command(label=\"선 두께 설정\", command=getWidth)\n\n shapeMenu = Menu(mainMenu)\n mainMenu.add_cascade(label=\"도형선택\", menu=shapeMenu)\n shapeMenu.add_command(label=\"선\", command=lambda : changeShape(LINE))\n shapeMenu.add_separator()\n shapeMenu.add_command(label=\"원\", command=lambda : changeShape(CIRCLE))\n\n window.mainloop()\n","sub_path":"part3-python/Bigdata/BigData(배포용,강사님)/Code05-07 미션1 그림판.py","file_name":"Code05-07 미션1 그림판.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"600141705","text":"import logging\nimport re\n\nfrom django.conf import settings\n\nlogger = logging.getLogger(__name__)\n\ndef strspn(source, allowed):\n newchrs = []\n for c in source:\n if c in allowed:\n newchrs.append(c)\n return u''.join(newchrs)\n\ndef check_cell_phone_number(number):\n cleaned_number = strspn(number, u'0123456789')\n msisdn_prefix = getattr(settings, 'SMSGATEWAY_MSISDN_PREFIX', '')\n if msisdn_prefix and not cleaned_number.startswith(msisdn_prefix):\n cleaned_number = msisdn_prefix + cleaned_number\n return str(cleaned_number)\n\ndef truncate_sms(text, max_length=160):\n text = text.strip()\n if len(text) <= max_length:\n return text\n else:\n logger.error(\"Trying to send an SMS that is too long: %s\", text)\n return text[:max_length-3] + '...'\n\ndef parse_sms(content):\n\n # work with uppercase and single spaces\n content = content.upper().strip()\n content = re.sub('\\s+', \" \", content)\n\n from smsgateway.backends.base import hook\n for keyword, subkeywords in hook.iteritems():\n if content[:len(keyword)] == unicode(keyword):\n remainder = content[len(keyword):].strip()\n if '*' in subkeywords:\n parts = remainder.split(u' ')\n subkeyword = parts[0].strip()\n if subkeyword in subkeywords:\n return [keyword] + parts\n return keyword, remainder\n else:\n for subkeyword in subkeywords:\n if remainder[:len(subkeyword)] == unicode(subkeyword):\n subremainder = remainder[len(subkeyword):].strip()\n return [keyword, subkeyword] + subremainder.split()\n return None\n","sub_path":"smsgateway/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"478481877","text":"\"\"\"\nImplementación de un analizador sintactico para el lenguaje BasicTran\n\nAutores:\nConstanza Abarca\nPedro Maldonado\n\nFecha:\n05/06/2018\n\"\"\"\n\nimport ply.yacc as yacc\nfrom Lex import tokens\nfrom sys import argv\nimport sys\nfrom arbol import *\nfrom contexto import *\nfrom evaluacion import *\n\n# Lista de precedencias \nprecedence = (\n\t('nonassoc', 'TkMayor', 'TkMenor', 'TkMayorIgual', 'TkMenorIgual'),\n\t('left', 'TkSuma', 'TkResta'),\n\t('left', 'TkMult', 'TkDiv', 'TkMod'),\n\t('right', 'uminus'),\n\t('left', 'TkConcatenacion'),\n\t('left', 'TkShift'),\n\t('left', 'TkCorcheteAbre', 'TkCorcheteCierra'),\n\t('left', 'TkPunto'),\n\t('left', 'TkSiguienteCar'),\n\t('left', 'TkAnteriorCar'),\n\t('left', 'TkValorAscii'),\n\t('left', 'TkIgual', 'TkDesigual'),\n\t('left', 'TkConjuncion', 'TkDisyuncion'),\n\t('right', 'TkNot'),\n\t('nonassoc', 'TkNum', 'TkId')\n)\n\n# Regla principal, define un bloque de instrucciones\ndef p_programa(p):\n\t'''\n\tbloque : TkBegin cuerpo TkEnd\n\t\t | TkWith declaracion TkBegin cuerpo TkEnd\n\t'''\n\tif (len(p) == 4):\n\t\tp[0] = Nodo('BLOQUE', None, [p[2]])\n\n\telse:\n\t\tp[0] = Nodo('BLOQUE', None, [p[2], p[4]])\n\n\n# Regla para declaraciones de variables y su tipo\ndef p_declaracion(p):\n\t'''\n\tdeclaracion : TkVar variables TkDosPuntos TkInt\n\t\t\t | TkVar variables TkDosPuntos TkBool\n\t\t\t | TkVar variables TkDosPuntos TkChar\n\t\t\t | TkVar variables TkDosPuntos arreglo\n\t\t\t | TkVar variables TkDosPuntos TkInt declaracion\n\t\t\t | TkVar variables TkDosPuntos TkBool declaracion\n\t\t\t | TkVar variables TkDosPuntos TkChar declaracion\n\t\t\t | TkVar variables TkDosPuntos arreglo declaracion\n\n\t'''\n\tif (len(p)==6):\n\t\tif (p[4] == 'int' or p[4] == 'char' or p[4] == 'bool'):\n\t\t\tp[0] = Nodo('DECLARACION', p[4], [p[2], p[5]])\n\t\telse:\n\t\t\tp[0] = Nodo('DECLARACION', 'arreglo', [p[4],p[2], p[5]])\n\n\telse:\n\t\tif (p[4] == 'int' or p[4] == 'char' or p[4] == 'bool'):\n\t\t\tp[0] = Nodo('DECLARACION', p[4], [p[2]])\n\t\telse:\n\t\t\tp[0] = Nodo('DECLARACION', 'arreglo', [p[4],p[2]])\n\n\n# Definicion de arreglos\ndef p_arreglo(p):\n\t'''\n\tarreglo : TkArray TkCorcheteAbre terminal TkCorcheteCierra TkOf TkChar\n\t\t | TkArray TkCorcheteAbre terminal TkCorcheteCierra TkOf TkInt\n\t\t | TkArray TkCorcheteAbre terminal TkCorcheteCierra TkOf TkBool\n\t\t | TkArray TkCorcheteAbre terminal TkCorcheteCierra TkOf arreglo\n\t\t | TkArray TkCorcheteAbre opAritm TkCorcheteCierra TkOf TkChar\n\t\t | TkArray TkCorcheteAbre opAritm TkCorcheteCierra TkOf TkInt\n\t\t | TkArray TkCorcheteAbre opAritm TkCorcheteCierra TkOf TkBool\n\t\t | TkArray TkCorcheteAbre opAritm TkCorcheteCierra TkOf arreglo\n\t\t | TkArray TkCorcheteAbre indice TkCorcheteCierra TkOf TkChar\n\t\t | TkArray TkCorcheteAbre indice TkCorcheteCierra TkOf TkInt\n\t\t | TkArray TkCorcheteAbre indice TkCorcheteCierra TkOf TkBool\n\t\t | TkArray TkCorcheteAbre indice TkCorcheteCierra TkOf arreglo\n\t'''\n\tif (p[6] == 'int' or p[6] == 'bool' or p[6] == 'char'):\n\t\tp[0] = Nodo('ARREGLO', p[6], None)\n\t\tp[0].arreglo = p[3]\n\telse:\n\t\tp[0] = Nodo('ARREGLO', None, [p[6]])\n\t\tp[0].arreglo = p[3]\n\n\n# Regla de valores terminales\ndef p_terminal(p):\n\t'''\n\tterminal : TkId\n\t\t\t | TkCaracter\n\t\t\t | TkNum\n\t\t\t | TkTrue\n\t\t\t | TkFalse\n\t\t\t | TkTab\n\t\t\t | TkSalto\n\t\t\t | TkComilla\n\t\t\t | TkBarra\n\t\t\t | TkParAbre terminal TkParCierra\n\t'''\n\tif (len(p) == 5):\n\t\t# Termnino con corchetes\n\t\tp[0] = Nodo(\"TERMINO\", p[1]+p[2]+str(p[3])+p[4], [p[3]])\n\t\t\t\t\n\t\t\t\n\n\telif(len(p)== 4):\n\n\t\t# Termino entre parentesis\n\t\tp[0] = Nodo(\"TERMINO\", p[1]+str(p[2])+p[3], [p[2]])\n\n\t\tif ((str(p[2].lexeme)).isdigit()):\n\t\t\tp[0].type = \"int\"\n\t\t\tp[0].lexeme = p[1] + str(p[2].lexeme) + p[3]\n\t\telif (p[2].lexeme == \"true\" or p[2].lexeme == \"false\"):\n\t\t\tp[0].type = \"bool\"\n\t\t\tp[0].lexeme = p[1] + p[2].lexeme + p[3]\n\t\telif (p[2].lexeme[0]==\"\\'\"):\n\t\t\tp[0].type = \"char\"\n\t\t\tp[0].lexeme = p[1] + p[2].lexeme + p[3]\t\n\t\telse:\n\t\t\tp[0].type = \"var\"\n\t\t\tp[0].lexeme = p[1] + p[2].lexeme + p[3]\t\t\n\n\telse:\n\n\t\tp[0] = Nodo('TERMINO', p[1], None)\n\n\t\tif ((str(p[1])).isdigit()):\n\t\t\tp[0].type = \"int\"\n\t\t\tp[0].lexeme = p[1]\n\t\telif (p[1] == \"true\" or p[1] == \"false\"):\n\t\t\tp[0].type = \"bool\"\n\t\t\tp[0].lexeme = p[1]\n\t\telif (p[1][0]==\"\\'\"):\n\t\t\tp[0].type = \"char\"\n\t\t\tp[0].lexeme = p[1]\n\t\telse:\n\t\t\tp[0].type = \"var\"\n\t\t\tp[0].lexeme = p[1]\n\n# Regla para definir el cuerpo de un bloque (conjunto de instrucciones)\ndef p_cuerpo(p):\n\t'''\n\tcuerpo : instruccion\n\t\t | instruccion cuerpo\n\t\t | bloque cuerpo\n\t\t | bloque\n\t'''\n\tp[0] = Nodo(\"CUERPO\", None, [p[1]])\n\tif (len(p) == 2):\n\t\tp[0] = Nodo(\"CUERPO\", None, [p[1]])\n\t\t#p[0] = (p[1])\n\telse:\n\t\tp[0] = Nodo(\"CUERPO\", None, [p[1], p[2]])\n\n\n# Definicion de una instruccion\ndef p_instruccion(p):\n\t'''\n\tinstruccion : expresion TkPuntoYComa\n\t\t\t\t| condicional\n\t\t\t\t| iterDeter\n\t\t\t\t| iterInd\n\t\t\t\t| asignacion TkPuntoYComa\n\t\t\t\t| input TkPuntoYComa\n\t\t\t\t| output TkPuntoYComa\n\n\t'''\n\t\n\tp[0] = Nodo(\"INSTRUCCION\", None, [p[1]])\n\n\n# Definicion de instrucciones condicionales\ndef p_condicional(p):\n\t'''\n\tcondicional : TkIf expresion TkHacer cuerpo TkEnd\n\t\t\t | TkIf expresion TkHacer cuerpo TkOtherwise TkHacer cuerpo TkEnd\n\n\n\t'''\n\tif (len(p) == 9):\n\t\tp[0] = Nodo(\"CONDICIONAL\", None, [p[2], p[4], p[7]])\n\telse:\n\t\tp[0] = Nodo(\"CONDICIONAL\", None, [p[2], p[4]])\n\n# Definicion de asignaciones\ndef p_asignacion(p):\n\t'''\n\tasignacion : TkId TkAsignacion expresion\n\t\t\t | indice TkAsignacion expresion\n\t\t\t \n\t'''\n\tif (len(p) == 7):\n\t\tp[0] = Nodo(\"ASIGNACION\", p[1], [p[6]])\n\t\tp[0].arreglo = p[3]\n\telse:\n\t\tp[0] = Nodo(\"ASIGNACION\", p[1], [p[3]])\n\t\tp[0].arreglo = p[3]\n\ndef p_indice(p):\n\t'''\n\tindice : TkId TkCorcheteAbre terminal TkCorcheteCierra\n\t | TkId TkCorcheteAbre opAritm TkCorcheteCierra\n\t | TkId TkCorcheteAbre indice TkCorcheteCierra\n\t | opArr TkCorcheteAbre terminal TkCorcheteCierra\n\t | opArr TkCorcheteAbre opAritm TkCorcheteCierra\n\t | opArr TkCorcheteAbre indice TkCorcheteCierra\n\t'''\n\tif (isinstance(p[1],str)):\n\t\tp[0] = Nodo(\"VAR_ARREGLO\", p[1], [p[3]])\n\telse:\n\t\tp[0] = Nodo(\"VAR_ARREGLO\", p[1].hijos[0], [p[3]])\n\tp[0].arreglo = p[1]\n\n# Entrada\ndef p_input(p):\n\t'''\n\tinput : TkRead TkId\n\t'''\n\tp[0] = Nodo(\"ENTRADA\", p[2], None)\n\n#Salida\ndef p_output(p):\n\t'''\n\toutput : TkPrint expresion\n\t'''\n\tp[0] = Nodo(\"SALIDA\", p[1], [p[2]])\n\n# Cliclos while\ndef p_iteracionind(p):\n '''\n \n iterInd : TkWhile expresion TkHacer cuerpo TkEnd\n '''\n \n p[0] = Nodo(\"ITERACION INDETERMINADA\", p[2], [p[4]])\n\n# Ciclos for\ndef p_iterDeter(p):\n\t'''\n\titerDeter : TkFor TkId TkFrom opAritm TkTo opAritm TkStep opAritm TkHacer cuerpo TkEnd\n\t\t\t | TkFor TkId TkFrom opAritm TkTo terminal TkStep opAritm TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom terminal TkTo opAritm TkStep opAritm TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom terminal TkTo terminal TkStep opAritm TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom opAritm TkTo opAritm TkStep terminal TkHacer cuerpo TkEnd\n\t\t\t | TkFor TkId TkFrom opAritm TkTo terminal TkStep terminal TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom terminal TkTo opAritm TkStep terminal TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom terminal TkTo terminal TkStep terminal TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom opAritm TkTo opAritm TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom opAritm TkTo terminal TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom terminal TkTo opAritm TkHacer cuerpo TkEnd\n\t | TkFor TkId TkFrom terminal TkTo terminal TkHacer cuerpo TkEnd\n\t'''\n\tif (len(p) == 12):\n\t\tp[0] = Nodo(\"ITERACION DETERMINADA\", [p[2], p[4], p[6], p[8]], [p[10]])\n\telse:\n\t\tp[0] = Nodo(\"ITERACION DETERMINADA\", [p[2], p[4], p[6], \"1\"], [p[8]])\n\n# Exoresiones generales\ndef p_expresion(p):\n\t'''\n\texpresion : opAritm\n | terminal\n | opRel\n | opCar\n | opBool\n | indice\n | opArr\n\n\t'''\n\n\tif (len(p) == 5):\n\t\tp[0] = Nodo(\"EXPRESION\", p[1]+p[2]+str(p[3])+p[4], [p[3]])\n\telse:\n\t\tp[0] = Nodo(\"EXPRESION\", None, [p[1]])\n\ndef p_opAritm(p):\n\t'''\n\topAritm : expresion TkResta expresion\n\t\t | expresion TkSuma expresion\n\t\t | expresion TkDiv expresion\n\t | expresion TkMult expresion\n\t | expresion TkMod expresion\n\t | expresion TkPunto expresion\n\t\t\t| TkParAbre expresion TkResta expresion TkParCierra\n\t\t | TkParAbre expresion TkSuma expresion TkParCierra\n\t\t | TkParAbre expresion TkDiv expresion TkParCierra\n\t | TkParAbre expresion TkMult expresion TkParCierra\n\t | TkParAbre expresion TkMod expresion TkParCierra\n\t | TkParAbre expresion TkPunto expresion TkParCierra\n\t | TkResta expresion %prec uminus\n\t | TkParAbre TkResta expresion TkParCierra %prec uminus\n\n\t'''\n\tif (len(p) == 6):\n\t\tp[0] = Nodo(\"BIN_ARITMETICA\", p[3], [p[2], p[4]])\n\telif (len(p) == 3):\n\t\tp[0] = Nodo(\"OPERACION UNARIA\", p[1], [p[2]])\n\telif (len(p) == 5):\n\t\tp[0] = Nodo(\"OPERACION UNARIA\", p[2], [p[3]])\n\telse:\n\t\tp[0] = Nodo(\"BIN_ARITMETICA\", p[2], [p[1], p[3]])\n\t#p[0] = (p[1], p[2], p[3])\n\ndef p_opArr(p):\n\t'''\n\topArr : TkId TkConcatenacion TkId\n | TkParAbre TkId TkConcatenacion TkId TkParCierra\n | TkShift TkId\n\t\t | TkParAbre TkShift TkId TkParCierra\n\t'''\n\tif (len(p) == 4):\n\t\tp[0] = Nodo(\"OPERACION ARREGLO\", p[2], [p[1], p[3]])\n\telif (len(p) == 6):\n\t\tp[0] = Nodo(\"OPERACION ARREGLO\", p[3], [p[2], p[4]])\n\telif (len(p) == 3):\n\t\tp[0] = Nodo(\"OPERACION ARREGLO\", p[1], [p[2]])\n\telse:\n\t\tp[0] = Nodo(\"OPERACION ARREGLO\", p[2], [p[3]])\n\n\ndef p_opCar(p):\n\t'''\n\topCar : terminal TkSiguienteCar\n\t\t | terminal TkAnteriorCar\n\t | TkValorAscii terminal\n\t | TkValorAscii terminal TkSiguienteCar\n\t | TkValorAscii terminal TkAnteriorCar\n\t | indice TkSiguienteCar\n\t\t | indice TkAnteriorCar\n\t | TkValorAscii indice\n\t | TkValorAscii indice TkSiguienteCar\n\t | TkValorAscii indice TkAnteriorCar\n\n\t'''\n\tif (p[1] == '#'):\n\t\tif (len(p) == 3):\n\t\t\tp[0] = Nodo(\"OPERACION CARACTER\", p[1], [p[2]])\n\t\telse:\n\t\t\tp[0] = Nodo(\"OPERACION CARACTER\", p[1], [Nodo(\"OPERACION CARACTER\", p[3], [p[2]])])\n\telse:\n\t\tp[0] = Nodo(\"OPERACION CARACTER\", p[2], [p[1]])\n\n\ndef p_opRel(p):\n\t'''\n\topRel : expresion TkMayor expresion\n\t\t | expresion TkMenor expresion\n\t\t | expresion TkMayorIgual expresion\n\t\t | expresion TkMenorIgual expresion\n\t\t | expresion TkIgual expresion\n\t\t | expresion TkDesigual expresion\n\t\t | TkParAbre expresion TkMayor expresion TkParCierra\n\t\t | TkParAbre expresion TkMenor expresion TkParCierra\n\t\t | TkParAbre expresion TkMayorIgual expresion TkParCierra\n\t\t | TkParAbre expresion TkMenorIgual expresion TkParCierra\n\t\t | TkParAbre expresion TkIgual expresion TkParCierra\n\t\t | TkParAbre expresion TkDesigual expresion TkParCierra\n\t'''\n\tif (len(p) == 6):\n\t\tp[0] = Nodo(\"RELACIONAL\", p[3], [p[2], p[4]])\n\telse:\n\t\tp[0] = Nodo(\"RELACIONAL\", p[2], [p[1], p[3]])\n\n# Definicion de las variables que corresponden a una declaracion\ndef p_variables(p):\n\t'''\n\tvariables : TkId TkComa variables\n\t\t\t | TkId TkAsignacion expresion TkComa variables\n\t\t\t | TkId \n\t\t\t | TkId TkAsignacion expresion\n\t'''\n\tif (len(p) == 4):\n\t\tp[0] = Nodo('VARIABLE', p[1], [p[3]])\n\telif (len(p) == 6):\n\t\tp[0] = Nodo('VARIABLE', p[1], [p[3], p[5]])\n\telse:\n\t\tp[0] = Nodo('VARIABLE', p[1], None)\n\n# Definicion de operaciones booleanas\ndef p_opBool(p):\n\t'''\n\topBool : expresion TkConjuncion expresion\n | expresion TkDisyuncion expresion\n | TkParAbre expresion TkConjuncion expresion TkParCierra\n | TkParAbre expresion TkDisyuncion expresion TkParCierra\n | TkNot expresion\n | TkParAbre TkNot expresion TkParCierra\n\n\t'''\n\tif (len(p) == 4):\n\t\tp[0] = Nodo(\"BOOLEANA\", p[2], [p[1], p[3]])\n\telif (len(p) == 3):\n\t\tp[0] = Nodo(\"BOOLEANA UNARIA\", p[1], [p[2]])\n\telif (len(p) == 5):\n\t\tp[0] = Nodo(\"BOOLENA UNARIA\", p[2], [p[3]])\n\telif(len(p) == 2):\n\t\tp[0] = Nodo(\"TERMINO\", p[1], [])\n\telse:\n\t\tp[0] = Nodo(\"BOOLEANA\", p[3], [p[2], p[4]])\n\n# Regla para errores\ndef p_error(p):\n\tprint(\"\\nError de sintaxis en la linea \", p.lineno + 1)\n\tsys.exit(0)\n\ndef imprimirTermino(nodo, tabs):\n\t# Tipo de expresion\n\n\tif (len(nodo.hijos) == 0):\n\t\tprint(tabs + nodo.tipo)\n\t\tprint(tabs + \" - Identificador: \" + str(nodo.lexeme))\n\t\tprint(tabs + \" - Tipo: \" + str(nodo.type))\n\telse:\n\t\timprimirTermino(nodo.hijos[0], tabs)\n\n\n# Imprimir las expresiones aritmeticas\ndef imprimirAritm(nodo, tabs):\n\t# Tipo de expresion\n\tprint(tabs + nodo.tipo)\n\t# Tipo de operacion\n\tprint(tabs + \"- Operacion: \" + nodo.valor)\n\n\t# Si hay un nodo (disitinto de None)\n\tif (nodo):\n\t\t# Si el nodo tiene hijos \n\t\tif (len(nodo.hijos) > 0):\n\t\t\t# Los hijos son los operadores de la expresion\n\t\t\tizq = nodo.hijos[0]\n\t\t\tder = nodo.hijos[1]\n\n\t\t\t# Operador izquierdo\n\t\t\tprint(tabs + \"- Operador izquierdo: \")\n\t\t\tif (izq.tipo == \"EXPRESION\"):\n\t\t\t\timprimirExp(izq, tabs + \"\\t\")\n\t\t\telif (izq.tipo == \"TERMINO\"):\n\t\t\t\timprimirTermino(izq, tabs)\n\n\t\t\t# Operador derecho\n\t\t\tprint(tabs + \"- Operador derecho: \")\n\t\t\tif (der.tipo == \"EXPRESION\"):\n\t\t\t\timprimirExp(der, tabs + \"\\t\")\n\t\t\telif (der.tipo == \"TERMINO\"):\n\t\t\t\timprimirTermino(der, tabs)\n\n# Funcion general para imprimir cualquier expresion\ndef imprimirExp(nodo, tabs):\n\thijo = nodo.hijos[0]\n\t# Los hijos del nodo son cualquier tipo de expresion\n\tif (hijo.tipo == \"BIN_ARITMETICA\"):\n\t\timprimirAritm(hijo, tabs)\n\telif (hijo.tipo == \"EXPRESION\"):\n\t\timprimirExp(hijo, tabs)\n\telif (hijo.tipo == \"TERMINO\"):\n\t\timprimirTermino(hijo, tabs)\n\telif (hijo.tipo == \"OPERACION UNARIA\"):\n\t\timprimirUnaria(hijo, tabs)\n\telif (hijo.tipo == \"RELACIONAL\"):\n\t\timprimirRelacional(hijo, tabs)\n\telif (hijo.tipo == \"OPERACION CARACTER\"):\n\t\timprimirCaracter(hijo, tabs)\n\telif (hijo.tipo == \"BOOLEANA\" or hijo.tipo == \"BOOLEANA UNARIA\"):\n\t\timprimirBool(hijo, tabs)\n\telif(hijo.tipo == \"OPERACION ARREGLO\"):\n\t\timprimirArr(hijo, tabs)\n\ndef imprimirArr(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tif (len(nodo.hijos) > 0):\n\t\tprint(tabs + \"- Operacion: \" + nodo.valor)\n\t\tfor i in nodo.hijos:\n\t\t\tprint(tabs + '- Operador: ' + i)\n\n# Para imprimir exp booleanas\ndef imprimirBool(nodo, tabs):\n\n\tprint(tabs + nodo.tipo)\n\n\tif (len(nodo.hijos) > 0):\n\t\tprint(tabs + \"- Operacion: \" + nodo.valor)\n\t\tif (len(nodo.hijos) == 2):\n\t\t\t# Sus hijos son los operadores\n\t\t\tprint(tabs + \"- Operador izquierdo: \")\n\t\t\timprimirExp(nodo.hijos[0], tabs+\"\\t\")\n\t\t\tprint(tabs + \"- Operador derecho: \")\n\t\t\timprimirExp(nodo.hijos[1], tabs+\"\\t\")\n\t\telse:\n\t\t\tprint(tabs + \"- Operador: \")\n\t\t\timprimirExp(nodo.hijos[0], tabs+\"\\t\")\n\telse:\n\t\tprint(tabs + \"- Valor:\")\n\t\tprint(tabs+\"\\t\" + nodo.valor)\n\n# Para imprimir declaracion de variables\ndef imprimirDeclaracion(nodo, tabs):\n\tif (nodo.tipo == \"DECLARACION\"):\n\t\tprint(tabs + \"TIPO: \" + nodo.valor)\n\tif (nodo):\n\t\tif (len(nodo.hijos) > 0):\n\t\t\tfor i in nodo.hijos:\n\t\t\t\tif (i.tipo == \"VARIABLE\"):\n\t\t\t\t\tprint(tabs + i.tipo)\n\t\t\t\t\tprint(tabs + \"- Identificador: \" + i.valor)\n\t\t\t\t\tif (len(i.hijos) >0):\n\t\t\t\t\t\tfor j in i.hijos:\n\t\t\t\t\t\t\tif (j.tipo == \"EXPRESION\"):\n\t\t\t\t\t\t\t\tprint(tabs + \"- Valor: \")\n\t\t\t\t\t\t\t\timprimirExp(j, tabs+\"\\t\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tprint(tabs + \"- Valor: no asignado\")\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(tabs + \"- Valor: no asignado\")\n\t\t\t\t\t\n\t\t\t\timprimirDeclaracion(i, tabs)\n\n# Para imprimir expresiones con caracteres\ndef imprimirCaracter(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tprint(tabs + \"- Operacion: \" + nodo.valor)\n\n\thijo = nodo.hijos[0]\n\n\tif (hijo.tipo == \"OPERACION CARACTER\"):\n\t\tprint(tabs + \"- Operador\")\n\t\timprimirCaracter(hijo, tabs+\"\\t\")\n\telif (hijo.tipo == \"TERMINO\"):\n\t\tprint(tabs + \"- Operador\")\n\t\timprimirTermino(hijo, tabs+\"\\t\")\n\n# Para imprimir expresiones relacionales\ndef imprimirRelacional(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tprint(tabs + \"- Operacion: \" + nodo.valor)\n\n\tif (nodo):\n\t\tif (len(nodo.hijos) > 0):\n\t\t\tizq = nodo.hijos[0]\n\t\t\tder = nodo.hijos[1]\n\n\t\t\tif (izq.tipo == \"EXPRESION\"):\n\t\t\t\tprint(tabs + \"- Operador izquierdo: \")\n\t\t\t\timprimirExp(izq, tabs + \"\\t\")\n\t\t\telif (izq.tipo == \"TERMINO\"):\n\t\t\t\tprint(tabs + \"- Operador izquierdo: \")\n\t\t\t\timprimirTermino(izq, tabs+\"\\t\")\n\n\t\t\tif (der.tipo == \"EXPRESION\"):\n\t\t\t\timprimirExp(der, tabs + \"\\t\")\n\t\t\telif (der.tipo == \"TERMINO\"):\n\t\t\t\tprint(tabs + \"- Operador derecho: \")\n\t\t\t\timprimirTermino(der, tabs+\"\\t\")\n\n# Para imprimir ciclos for\ndef imprimirIterDeter(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tinf = nodo.valor[1]\n\tsup = nodo.valor[2]\n\tstep = nodo.valor[3]\n\tprint(tabs + \"- Identificador: \" + nodo.valor[0])\n\tprint(tabs + \"- Limite inferior: \")\n\tif (inf.tipo == \"TERMINO\"):\n\t\timprimirTermino(inf, tabs+\"\\t\")\n\telif (inf.tipo == \"BIN_ARITMETICA\"):\n\t\timprimirAritm(inf, tabs + \"\\t\")\n\tprint(tabs + \"- Limite superior: \")\n\tif (sup.tipo == \"TERMINO\"):\n\t\timprimirTermino(sup, tabs+\"\\t\")\n\telif (sup.tipo == \"BIN_ARITMETICA\"):\n\t\timprimirAritm(sup, tabs + \"\\t\")\n\tprint(tabs + \"- Step: \")\n\tif (step == \"1\"):\n\t\tprint(tabs + \"\\t\" + \"TERMINO\")\n\t\tprint(tabs + \"\\t\" + step)\n\telse:\t\n\t\tif (step.tipo == \"TERMINO\"):\n\t\t\timprimirTermino(step, tabs+\"\\t\")\n\t\telif (step.tipo == \"BIN_ARITMETICA\"):\n\t\t\timprimirAritm(step, tabs + \"\\t\")\n\tprint(tabs + \"- Operaciones\")\n\timprimirArbol(nodo.hijos[0], tabs + \"\\t\")\n\n# Para imprimir expresiones unarias\ndef imprimirUnaria(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tprint(tabs + \"Operacion: \" + nodo.valor)\n\tprint(tabs + \"Operador: \")\n\tif (nodo.hijos[0].tipo == \"TERMINO\"):\n\t\timprimirTermino(nodo.hijos[0], tabs+\"\\t\")\n\telif (nodo.hijos[0].tipo == \"OPERACION UNARIA\"):\n\t\timprimirUnaria(nodo.hijos[0], tabs + \"\\t\")\n\telif (nodo.hijos[0].tipo == \"EXPRESION\"):\n\t\timprimirExp(nodo.hijos[0], tabs + \"\\t\")\n\telse:\n\t\timprimirAritm(nodo.hijos[0], tabs + \"\\t\")\n\n# Para asignaciones\ndef imprimirAsig(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tif (isinstance(nodo.valor, str)):\n\t\tprint(tabs + \"Identificador: \" + nodo.valor)\n\telse:\n\t\tprint(tabs + \"Identificador: \" + nodo.valor.valor)\n\n\n\tprint(tabs + \"Valor: \")\n\n\timprimirExp(nodo.hijos[0], tabs + \"\\t\")\n\n# Para condicionales\ndef imprimirCond(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tprint(tabs + \"- Guardia\")\n\timprimirArbol(nodo.hijos[0], tabs + \"\\t\")\n\tif (len(nodo.hijos) == 3):\n\t\tprint(tabs + \"- Exito\")\n\t\timprimirArbol(nodo.hijos[1], tabs + \"\\t\")\n\t\tprint(tabs + \"- Otherwise\")\n\t\timprimirArbol(nodo.hijos[2], tabs + \"\\t\")\n\telse:\n\t\tprint(tabs + \"- Exito\")\n\t\timprimirArbol(nodo.hijos[1], tabs + \"\\t\")\n\n# Para entradas\ndef imprimirEntrada(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tprint(tabs + \"- Operador: read\")\n\tprint(tabs + \"-Identificador: \" + nodo.valor)\n\n# Para salidas\ndef imprimirSalida(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tprint(tabs + \"- Operador: \" + nodo.valor)\n\tprint(tabs + \"-Salida: \")\n\timprimirExp(nodo.hijos[0], tabs + \"\\t\")\n\n# Para imprimir while loop\ndef imprimirIndeter(nodo, tabs):\n\tprint(tabs + nodo.tipo)\n\tprint(tabs + \"- Guardia: \")\n\timprimirExp(nodo.valor, tabs + \"\\t\")\n\tprint(tabs + \"- Exito: \")\n\timprimirArbol(nodo.hijos[0], tabs + \"\\t\")\n\n# Para imprimir todo el arbol de expresiones\ndef imprimirArbol(nodo, tabs):\n\tif (nodo):\n\t\tif (len(nodo.hijos) > 0):\n\t\t\tfor i in nodo.hijos:\n\t\t\t\tif (i.tipo == \"BLOQUE\"):\n\t\t\t\t\ttabs = tabs + \"\\t\"\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\tprint(tabs + i.tipo)\n\t\t\t\t\n\t\t\t\tif (i.tipo == \"EXPRESION\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\timprimirExp(i, tabs)\n\n\t\t\t\telif (i.tipo == \"DECLARACION\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\tprint(tabs + i.tipo)\n\t\t\t\t\timprimirDeclaracion(i, tabs)\n\n\t\t\t\telif(i.tipo == \"ITERACION DETERMINADA\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\timprimirIterDeter(i, tabs)\n\n\t\t\t\telif (i.tipo == \"ITERACION INDETERMINADA\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\timprimirIndeter(i, tabs)\t\t\t\t\t\n\n\t\t\t\telif (i.tipo == \"ASIGNACION\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\timprimirAsig(i, tabs)\n\n\t\t\t\telif (i.tipo == \"CONDICIONAL\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\timprimirCond(i, tabs)\n\t\t\t\telif (i.tipo == \"SALIDA\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\timprimirSalida(i, tabs)\n\t\t\t\telif (i.tipo == \"ENTRADA\"):\n\t\t\t\t\tprint(\"\\n\")\n\t\t\t\t\timprimirEntrada(i, tabs)\n\t\t\t\telse:\n\t\t\t\t\timprimirArbol(i, tabs)\n\t\t\t\t\n\ndef main():\n\t# Leer nombre del archivo de la entrada estandar\n\tfilename = argv[1]\n\n\t# String con todas las lineas del archivo\n\tprogram = \"\"\n\n\t# Numero total de lienas en el archivo\n\tn = 0\n\tparser = yacc.yacc()\n\n\twith open(filename, 'r') as fd:\n\n\t\tfor line in fd:\n\t\t\tprogram = program + line\n\t\t\tn = n + 1\n\n\tp = parser.parse(program)\n\n\n\tc = context()\n\tc.contextCheck(p)\n\tc.imprimirTabla()\n\tprint(\"SECUENCIACION\")\n\ts = \"\\t\"\n\timprimirArbol(p, s)\n\te = evaluacion(c.scopes)\n\te.evalArbol(p)\n\nmain()","sub_path":"Fase 4/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":20091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"30551385","text":"#Import modules\nimport os\nimport csv\n\n\n#Path to collect data form the Resources folder\nbank_csv = os.path.join('Resources', 'budget_data.csv')\n\n#Set Variables\nmonth_list = []\nrevenue_list = []\ntotal_revenue = 0\ntotal_change = 0\nchange_max = [ '', 0]\nchange_min = [ '', 0]\n\n\n#Read CSV file\nwith open (bank_csv, 'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter = ',')\n header = next(csvfile)\n \n\n\n\n #Read through rows in CSV file\n for row in csvreader:\n month_year = row[0]\n revenue = float(row[1])\n month_list.append(month_year)\n revenue_list.append(revenue)\n total_revenue += revenue\n\n#Calculation to find total months\ntotal_months = len(month_list)\n\n#Loop through lists to find Financial Analysis outputs\nfor i in range(1,total_months): \n month_change = revenue_list[i] - revenue_list[i-1]\n total_change += month_change\n if month_change > change_max[1] :\n change_max = [month_list[i], month_change]\n if month_change < change_min[1] :\n change_min = [month_list[i], month_change]\n\naverage_change = total_change / (total_months-1 )\n\n\n#Put Summary Data into a list\nsummary_data = []\nline1 = 'Financial Analysis'\nline2 = '-' * 30\nline3 = (f'Total Months: {total_months}')\nline4 = (f'Total: $ {round(total_revenue)}')\nline5 = (f'Average Change: ${round(average_change,2)}')\nline6 = (f'Greatest Increase in Profits: {change_max[0]} ({change_max[1]})')\nline7 = (f'Greatest Decrease in Profits: {change_min[0]} ({change_min[1]})')\nsummary_data.extend([line1,line2,line3,line4,line5,line6,line7])\n\n#Print results to terminal\nfor line in summary_data:\n print(line)\n\n\n\n#Export results to text file\noutput_text = open('PyBank_outputs.txt', 'w')\nwith open('PyBank_outputs.txt', 'w') as txt_file:\n for line in summary_data:\n txt_file.write(line + '\\n')\n\n\n","sub_path":"PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"173587688","text":"import sys\nimport time\nimport Adafruit_DHT\nimport RPi.GPIO as GPIO\nimport datetime\n\n# Note GPIO module uses Physical PIN as reference. Physical PINs are numbered in order\n# Note Adafruit_DHT uses BCM PIN as reference. BCM PINs are the numbers on the breakout board.\n\n# Setup pins for GPIO\n# LED on PIN 11, or BCM PIN 17\n# Button on PIN 31, or BCM PIN 6\npinLED = 11\npinButton = 31\n\n# Setup pins for Adafruit_DHT\n# Sensor on PIN 7, or BCM PIN 4\npinTempSensor = 4\n\nGPIO.setmode(GPIO.BOARD)\nGPIO.setup(pinLED, GPIO.OUT)\nGPIO.setup(pinButton, GPIO.IN)\n\n# Set initial state of LED to \"off\"\nGPIO.output(pinLED, GPIO.HIGH)\n\n# Create sensor. We are using the AM2302 Sensor\n# sensor_args = { '11': Adafruit_DHT.DHT11,\n# '22': Adafruit_DHT.DHT22,\n# '2302': Adafruit_DHT.AM2302 }\nsensor = Adafruit_DHT.AM2302\n\n# Function to convert Celsious to Fahrenheit\ndef CelsToFahr(a):\n return ((a*1.8 + 32.0))\n\n# Create Loop Variable\ni=0\n\n# Create file connection to local file\nf = open('TempReadings', 'w')\nf.write(\"File created at \" + datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') + '\\n')\nf.write(\"Time,Temperature (F),Humidity (%),\\n\")\n\n# Create Loop to get temperature\nwhile i == 0:\n # Read input from switch\n value = GPIO.input(pinButton)\n # If switch is released, turn light off, and do not take a reading\n if value:\n GPIO.output(pinLED, GPIO.HIGH)\n # If switch is pressed, print message, turn on light, read temperature, and print value\n else:\n print(\"Reading Temperature\")\n GPIO.output(pinLED, GPIO.LOW)\n # Note: The time is the time in which the Raspberry Pi receives the data.\n # This means there could be delay between when the data is read from the sensor and the time stamp. \n # For our application, this difference is negligible.\n humidity, temperature = Adafruit_DHT.read_retry(sensor, pinTempSensor)\n timeSec = time.time()\n # Convert to Fahrenheit\n temperature = CelsToFahr(temperature)\n # Format strings\n timeStamp = datetime.datetime.fromtimestamp(timeSec).strftime('%Y-%m-%d %H:%M:%S')\n temperatureStr = '{0:0.1f}'.format(temperature)\n humidityStr = '{0:0.1f}'.format(humidity)\n writeString = timeStamp + ',' + temperatureStr + ',' + humidityStr\n f.write(writeString + ',\\n')\n print(timeStamp + ' Temp={0:0.1f}* Humidity={1:0.1f}%'.format(temperature, humidity))","sub_path":"PythonSensor/getTempOnButtonPress.py","file_name":"getTempOnButtonPress.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"282629608","text":"inp = []\nfor _ in range(9):\n inp.append(list(map(int, input().split())))\n\ndef get_poss_num(ri, ci):\n poss_set = set([i for i in range(1, 10)])\n # 1. Check row\n for num in inp[ri]:\n try:\n poss_set.remove(num)\n except:\n continue\n # 2. Check col\n for row in inp:\n try:\n poss_set.remove(row[ci])\n except:\n continue\n # 3. Check square\n for i in range(3):\n for j in range(3):\n try:\n poss_set.remove(inp[3 * (ri // 3) + i][3 * (ci // 3) + j])\n except:\n continue\n return list(poss_set)\n\n# One or more possible case.\nflag = False\n\ndef sudoku():\n global flag\n if flag:\n return\n global inp\n for row_idx, row in enumerate(inp):\n for col_idx, col in enumerate(row):\n if col == 0:\n for num in get_poss_num(row_idx, col_idx):\n # Backtracking\n inp[row_idx][col_idx] = num\n sudoku()\n inp[row_idx][col_idx] = 0\n else:\n return\n else:\n flag = True\n for row in inp:\n print(*list(map(str, row)))\n\nsudoku()\n","sub_path":"python/2580.py","file_name":"2580.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"567673669","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.10-x86_64/egg/programmabletuple/__init__.py\n# Compiled at: 2015-08-27 19:31:19\n# Size of source mod 2**32: 25513 bytes\n\"\"\"\n==================\nProgrammable tuple\n==================\n\n\"\"\"\nimport functools, itertools, collections\n\nclass ProgrammableTupleMeta(type):\n __doc__ = 'Programmable tuple metaclass\\n\\n This is the meta-class for programmable tuple classes. The basic idea of\\n the implementation is that for each programmable tuple class, a mutable\\n proxy class is generated that imitates its behaviour as much as possible.\\n The actual initializer will be invoked with objects of this proxy class\\n as ``self``. Then after the user-defined initialization, the values for\\n the various fields are read from this proxy object and set into the\\n actual programmable tuple. In this meta-class, the core functionality of\\n defining the proxy class and wrapping the user-defined init function is\\n performed. The definition of utility methods are in the mixin class\\n :py:class:`_UtilMethodsMixin` definition.\\n\\n '\n\n def __new__(mcs, name, bases, nmspc, auto_defining=False):\n \"\"\"Generates a new type instance for programmable tuple class\"\"\"\n new_nmspc = dict(nmspc)\n fields, defining_count = _determine_fields(bases, new_nmspc)\n proxy_class = _form_proxy_class(name, bases, nmspc, auto_defining)\n new_nmspc['__new__'] = _form_new_method(proxy_class)\n new_nmspc['__init__'] = _form_init_method(proxy_class.__init__)\n if any(issubclass(i, tuple) for i in bases):\n slots = []\n else:\n slots = [\n '__content__']\n new_nmspc['__slots__'] = slots\n cls = type.__new__(mcs, name, bases, new_nmspc)\n cls.__fields__ = fields\n cls.__defining_count__ = defining_count\n cls.__Proxy_Class__ = proxy_class\n return cls\n\n def __init__(cls, *args, **_):\n \"\"\"Initializer\n\n It just calls the initializer in the base class with all keyword\n arguments dropped.\n \"\"\"\n super().__init__(*args)\n\n\ndef _determine_fields(bases, nmspc):\n \"\"\"Determines the fields for the new programmable tuple\n\n :param tuple bases: The base classes of the new class\n :param dict nmspc: The name space dictionary for the new class\n :returns: The ordered dictionary of all the fields of the new class, field\n names as keys and the location as values. The order is consistent\n with the order of the fields. And the number of defining fields.\n \"\"\"\n fields = set()\n for base in _gen_programmable_tuple_bases(bases):\n fields.update(base.__fields__)\n continue\n\n if '__data_fields__' in nmspc:\n fields.update(nmspc['__data_fields__'])\n try:\n init_meth = nmspc['__init__']\n init_argnames = _get_argnames(init_meth)\n except KeyError:\n defining_fields = []\n defining_count = 0\n except AttributeError:\n raise ValueError('Initializer needs to be a function.')\n else:\n defining_fields = init_argnames[1:]\n defining_count = len(defining_fields)\n data_fields = sorted(fields.difference(defining_fields))\n fields = collections.OrderedDict()\n for idx, fn in enumerate(itertools.chain(defining_fields, data_fields)):\n fields[fn] = idx\n continue\n\n return (fields, defining_count)\n\n\ndef _form_proxy_class(name, bases, orig_nmspc, auto_defining):\n \"\"\"Forms a proxy class for initializing programmable tuple\n\n The generated proxy class will have got all the behaviour of the new\n class and its base classes. Just it is a regular mutable class. Its\n instances can be used in the invocation of the initializer and act as the\n ``self``. Then the actual defining and data fields can be read from the\n proxy object and set in the actual immutable class instance.\n\n :param str name: The name of the new named tuple class\n :param tuple bases: The basis of the new named tuple class\n :param dict orig_nmspc: The name space dictionary of the named tuple class\n before any tweaking by the programmable tuple metaclass.\n :param bool auto_defining: If the defining attributes are going to be\n automatically assigned.\n \"\"\"\n proxy_bases = tuple(i.__Proxy_Class__ for i in _gen_programmable_tuple_bases(bases))\n proxy_class = type('{}ProxyClass'.format(name), proxy_bases if len(proxy_bases) > 0 else (object,), orig_nmspc)\n if auto_defining:\n proxy_class.__init__ = _add_auto_defining(proxy_class.__init__)\n\n def patched_super(self, cls=proxy_class):\n \"\"\"Patched super function for initialization\"\"\"\n if isinstance(cls, ProgrammableTupleMeta):\n cls = cls.__Proxy_Class__\n return super(cls, self)\n\n proxy_class.super = patched_super\n return proxy_class\n\n\ndef _add_auto_defining(init):\n \"\"\"Decorates __init__ to assign defining fields automatically\n\n After the decoration, all the arguments will be assigned as attributes of\n ``self`` before the invocation of the actual initializer.\n \"\"\"\n\n @functools.wraps(init)\n def decorated(self, *args, **kwargs):\n \"\"\"The decorated initializer\"\"\"\n argnames = _get_argnames(init)\n for field, value in itertools.chain(zip(argnames[1:], args), kwargs.items()):\n setattr(self, field, value)\n\n init(self, *args, **kwargs)\n\n return decorated\n\n\ndef _form_new_method(proxy_class):\n \"\"\"Forms the __new__ method for the class\n\n The function returned from this function, which should be used as the\n __new__ method of the programmable tuple class, will be the core of how\n the programmable tuples work. Basically a proxy object will be created to\n be initialized by the user-given initializer. Then the values of the\n fields are going to be read from the attributes of this proxy object to\n form the actual immutable object.\n\n \"\"\"\n\n @functools.wraps(proxy_class.__init__)\n def new_meth(cls, *args, **kwargs):\n \"\"\"Set a new object of the programmable tuple class\"\"\"\n proxy = proxy_class(*args, **kwargs)\n values = _get_field_values(cls.__fields__, lambda fn: getattr(proxy, fn), AttributeError)\n return _make_programmable_tuple(cls, values)\n\n return new_meth\n\n\ndef _form_init_method(proxy_init):\n \"\"\"Decorate the user-given initialization function\n\n Although the actual actions of the user-given initializer is moved to the\n initialization of the proxy object, we would still like to see the\n docstring for the initializer during development.\n\n More importantly, since the default Python ``super`` is slightly awkward\n to use inside the initializer, we want to be able to call the initializer\n of super class directly. So this function could decorate the given\n initializer into a version that is automatically disabled when called on\n a programmable tuple object.\n\n \"\"\"\n\n @functools.wraps(proxy_init)\n def decorared(self, *args, **kwargs):\n \"\"\"The decorated initializer\"\"\"\n if isinstance(type(self), ProgrammableTupleMeta):\n pass\n else:\n proxy_init(self, *args, **kwargs)\n\n return decorared\n\n\ndef _get_argnames(func):\n \"\"\"Gets the names of the argument of a function\"\"\"\n return func.__code__.co_varnames[0:func.__code__.co_argcount]\n\n\ndef _gen_programmable_tuple_bases(raw_bases):\n \"\"\"Generates the programmable tuple bases\n\n For subclassing programmable tuples, we need to read some information\n from only the bases which are programmable tuples themselves. This\n function will filter only the programmable tuple subclasses to read the\n information.\n \"\"\"\n for base in raw_bases:\n if isinstance(base, ProgrammableTupleMeta):\n yield base\n else:\n continue\n\n\nclass _UtilMethodsMixin(object):\n __doc__ = '\\n Mixin class for utility methods of programmable tuple base classes\\n\\n This class will define utility methods for working with programmable\\n tuples. Most of the utility methods directly parallels those for the\\n ``namedtuple`` class.\\n\\n This class is going to be mixed in into the two public base classes to\\n provide the utilities.\\n\\n '\n __slots__ = []\n\n def __getattr__(self, attr):\n \"\"\"Gets the attribute of the given name\"\"\"\n try:\n return self.__content__[self.__fields__[attr]]\n except KeyError:\n raise KeyError('Invalid attribute {}'.format(attr))\n\n def __setattr__(self, attr, value):\n \"\"\"Raises Attribute Error for attempts to mutate\"\"\"\n if attr == '__content__':\n super().__setattr__(attr, value)\n else:\n raise AttributeError('Cannot mutate attributes of programmable tuples')\n\n def __hash__(self):\n \"\"\"The default hash\n\n The tuple of the class and the defining fields values are going to be\n hashed.\n \"\"\"\n return hash((\n self.__class__,) + self._defining_values)\n\n def __eq__(self, other):\n \"\"\"Equality comparison\n\n Two programmable tuple objects are considered equal when\n\n 1. They are of the same class.\n 2. All of their defining fields have equal values.\n\n \"\"\"\n return self.__class__ == other.__class__ and self._defining_values == other._defining_values\n\n def _update(self, **kwargs):\n \"\"\"Updates defining attributes\n\n A programmable tuple of the same class is going to be returned,\n just with the defining fields given in the keyword arguments replaced\n by their new given value. After the new values of the defining fields\n are formed, the initialization process will be performed.\n \"\"\"\n result = type(self)(*map(kwargs.pop, self._gen_defining_field_names(), self.__content__))\n if kwargs:\n raise ValueError('Got unexpected field names {}'.format(list(kwargs.keys())))\n return result\n\n def _replace(self, **kwargs):\n \"\"\"Simply replace a field in the programmable tuple\n\n Different from the :py:meth:`_update` method, by using this method,\n the initialization process will **not** be performed and a new\n programmable tuple of the same class will be forcefully formed with\n the given fields replaced.\n \"\"\"\n values_dict = {}\n for fn in self._gen_field_names():\n if fn in kwargs:\n val = kwargs.pop(fn)\n else:\n val = getattr(self, fn)\n values_dict[fn] = val\n continue\n\n if kwargs:\n raise ValueError('Got unexpected field names {}'.format(list(kwargs.keys())))\n result = self._make(**values_dict)\n return result\n\n @classmethod\n def _make(cls, **kwargs):\n \"\"\"Makes a new programmable tuple object directly\n\n This method will bypass all the initialization process and make a\n programming tuple object according to the keyword arguments given.\n Note that **all** the fields should be present in the keyword\n arguments.\n\n :param kwargs: The values of all the fields, including defining and\n data fields.\n :returns: The programmable tuple object with the given fields.\n \"\"\"\n values = _get_field_values(cls.__fields__, kwargs.pop, KeyError)\n if len(kwargs) > 0:\n raise ValueError('Invalid field(s) {} for {}'.format(tuple(kwargs.keys()), cls.__name__))\n return _make_programmable_tuple(cls, values)\n\n def _format(self, children_fmt, include_fn):\n \"\"\"Formats itself as a string\n\n This is an internal function going to be used by both the default\n ``__repr__`` and default ``__str__`` methods.\n\n :param str children_fmt: The format string for the children,\n the children needs to have a field name of ``val``.\n :param bool include_fn: if the field name is going to be included.\n :returns: A string formatted for the values of all the defining fields.\n \"\"\"\n if include_fn:\n full_children_fmt = '{fn}=' + children_fmt\n else:\n full_children_fmt = children_fmt\n children = ', '.join(full_children_fmt.format(fn=fn, val=val) for fn, val in zip(self._gen_defining_field_names(), self.__content__))\n return '{}({})'.format(self.__class__.__name__, children)\n\n def __repr__(self, include_fn=True):\n \"\"\"Returns the formatted string able to be evaluated\"\"\"\n return self._format(children_fmt='{val!r}', include_fn=include_fn)\n\n def __str__(self, include_fn=True):\n \"\"\"Returns a nicely formatted string\"\"\"\n return self._format(children_fmt='{val!s}', include_fn=include_fn)\n\n def _asdict(self, full=False, class_tags=False):\n \"\"\"Returns an dictionary which maps field names to values\n\n This method will convert a programmable tuple into a dictionary,\n with keys being the names of the fields and values being the\n corresponding value. For fields that are programmable tuple, they are\n going to be cast into dictionary recursively. In this way,\n this method can be used for serialization into JSON or YAML.\n\n :param bool full: If the data fields are going to be contained as\n well, by default only the defining fields are contained.\n :param Mapping class_tags: The mapping from class to a string,\n which is going to be assigned to the ``__class__`` attributes of\n the dictionaries. By default, the ``__class__`` attribute will\n not be added. But when it is added, it is required that the\n mapping contains all the classes that is needed.\n :returns: The dictionary for the current programmable tuple.\n \"\"\"\n if full:\n included_fields = self._gen_field_names()\n else:\n included_fields = self._gen_defining_field_names()\n dict_ = {}\n for fn in included_fields:\n val = getattr(self, fn)\n if isinstance(type(val), ProgrammableTupleMeta):\n val = val._asdict(full=full, class_tags=class_tags)\n dict_[fn] = val\n continue\n\n if class_tags:\n dict_['__class__'] = class_tags[type(self)]\n return dict_\n\n @classmethod\n def _load_from_dict(cls, dict_, full=False, class_tags=None, top=True):\n \"\"\"Loads a programmable tuple object from its dictionary form\n\n This method is the opposite of the method :py:meth:`_asdict`. It will\n also recursively resolve the nested dictionaries when they were in\n fact serialized from programmable tuples.\n\n :param dict dict_: The dictionary to load.\n :param bool full: If the data fields are going to be read and used as\n well. By default, the programmable tuple objects are going to be\n initialized from only the defining fields.\n :param Mapping class_tags: The mapping from class tags in the\n ``__class__`` string to the actual class.\n :param bool top: If we are at the top of the recursion tree.\n :returns: The programmable tuple from parsing the dictionary.\n \"\"\"\n try:\n class_tag = dict_['__class__']\n except KeyError:\n if top:\n obj_class = cls\n else:\n return dict(dict_)\n else:\n if class_tag in class_tags:\n obj_class = class_tags[class_tag]\n else:\n raise ValueError('The class for tag {} cannot be resolved'.format(class_tag))\n if full:\n content = {}\n for i, v in dict_.items():\n if i == '__class__':\n continue\n if isinstance(v, dict):\n val = cls._load_from_dict(v, full=True, class_tags=class_tags, top=False)\n else:\n val = v\n content[i] = val\n continue\n\n return obj_class._make(**content)\n else:\n defining = {}\n for fn in obj_class._gen_defining_field_names():\n try:\n val = dict_[fn]\n except KeyError:\n raise ValueError('The definition property {} of class {} is not given'.format(fn, obj_class))\n\n if isinstance(val, dict):\n val = cls._load_from_dict(val, full=False, class_tags=class_tags, top=False)\n defining[fn] = val\n continue\n\n return obj_class(**defining)\n\n def __getnewargs__(self):\n \"\"\"Gets the arguments to be used for the new function\"\"\"\n return self._defining_values\n\n __getstate__ = lambda _: False\n __setstate__ = lambda _, state_: False\n\n @classmethod\n def _gen_field_names(cls):\n \"\"\"Gets an iterator of the field names of the class\"\"\"\n return cls.__fields__.keys()\n\n @classmethod\n def _gen_defining_field_names(cls):\n \"\"\"The names of all the defining fields\n\n An iterator is going to be returned for names of all the defining\n names of the class.\n \"\"\"\n return itertools.islice(cls.__fields__.keys(), 0, cls.__defining_count__)\n\n @property\n def _defining_values(self):\n \"\"\"The values of the defining attributes\n\n A tuple for the values of the defining fields in order.\n \"\"\"\n return tuple(self.__content__[0:self.__defining_count__])\n\n\nclass ProgrammableTuple(_UtilMethodsMixin, tuple, metaclass=ProgrammableTupleMeta):\n __doc__ = 'The programmable tuple base class\\n\\n This is an abstract base class for the programmable tuples. Users can\\n just derive from this base class to make the class a programmable tuple\\n class.\\n\\n '\n\n @property\n def __content__(self):\n \"\"\"Return the content tuple\n\n This is to make the content tuple of both subclass of tuple and\n non-subclass of tuple able to be retrieved in a uniform fashion.\n \"\"\"\n return self\n\n\nclass ProgrammableExpr(_UtilMethodsMixin, metaclass=ProgrammableTupleMeta):\n __doc__ = 'The programmable expression base class\\n\\n This base class is similar to the :py:class:`ProgrammableTuple` class,\\n just it is not a subclass of tuple. So it can be used when the desired\\n data structure is not intended to behave like a tuple. The resulted class\\n looks like expressions in the Wolfram language but with object-oriented\\n programmability added.\\n\\n\\n '\n\n\ndef _get_field_values(fields, query, non_exist_exc):\n \"\"\"Gets the values of all the fields\n\n :param OrderedDict fields: The ordered dictionary for the fields.\n :param Callable query: A callable function going to be called with the\n field name to get the value.\n :param non_exist_exc: The exception class for failed field value query.\n :returns: A list of the values of all the fields in order.\n \"\"\"\n values = []\n for i in fields.keys():\n try:\n values.append(query(i))\n except non_exist_exc:\n raise AttributeError('Attribute {} is not set'.format(i))\n\n continue\n\n return values\n\n\ndef _make_programmable_tuple(cls, data_values):\n \"\"\"Makes a programmable tuple object\n\n This function will actually make a programmable tuple object of the given\n class according to the sequence of values for the fields. It is the\n function that is actually used to make the object during the\n initialization process. It can also be used for other purposes where we\n already got values of all the fields and the initialization process needs\n to be skipped.\n\n :param cls: The class of the programmable tuple.\n :param data_values: A sequence of values for all the fields of the\n programmable tuple.\n :returns: A value of the programmable tuple with the given data fields.\n \"\"\"\n if issubclass(cls, tuple):\n tp = tuple.__new__(cls, data_values)\n else:\n content = tuple(data_values)\n tp = object.__new__(cls)\n tp.__content__ = content\n return tp","sub_path":"pycfiles/programmabletuple-0.5.0-py3.4/__init__.cpython-34.py","file_name":"__init__.cpython-34.py","file_ext":"py","file_size_in_byte":20412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"117986220","text":"\"\"\"\n.. module:: landscapedevice\n :platform: Darwin, Linux, Unix, Windows\n :synopsis: Module containing the :class:`TestLandscape` class and associated diagnostic.\n\n.. moduleauthor:: Myron Walker \n\n\"\"\"\n\n__author__ = \"Myron Walker\"\n__copyright__ = \"Copyright 2020, Myron W Walker\"\n__credits__ = []\n__version__ = \"1.0.0\"\n__maintainer__ = \"Myron Walker\"\n__email__ = \"myron.walker@gmail.com\"\n__status__ = \"Development\" # Prototype, Development or Production\n__license__ = \"MIT\"\n\n\nimport threading\nimport weakref\n\nfrom dlipower import PowerSwitch\n\nfrom akit.exceptions import AKitConfigurationError\n\nclass LandscapeDevice:\n \"\"\"\n The base class for all landscape devices. The :class:`LandscapeDevice' represents attributes that are common\n to all connected devices and provides attachements points and mechanisms for adding DeviceExtentions to\n the :class:`LandscapeDevice` device.\n \"\"\"\n\n def __init__(self, lscape, keyid, device_type, device_config):\n self._lscape_ref = weakref.ref(lscape)\n self._keyid = keyid\n self._device_type = device_type\n self._device_config = device_config\n self._device_lock = threading.RLock()\n\n self._contacted_first = None\n self._contacted_last = None\n self._is_watched = None\n self._is_isolated = None\n\n self._upnp = None\n self._muse = None\n self._ssh = None\n self._power = None\n self._serial = None\n\n self._match_functions = {}\n\n self._credentials = {}\n self._ssh_credentials = []\n if \"credentials\" in device_config:\n lscape_credentials = lscape.credentials\n for cred_key in device_config[\"credentials\"]:\n if cred_key in lscape_credentials:\n cred_info = lscape_credentials[cred_key]\n self._credentials[cred_key] = cred_info\n if cred_info.category == \"ssh\":\n self._ssh_credentials.append(cred_info)\n\n return\n\n @property\n def contacted_first(self):\n \"\"\"\n A datetime stamp of when this device was first contacted\n \"\"\"\n return self._contacted_first\n\n @property\n def contacted_last(self):\n \"\"\"\n A datetime stamp of when this device was last contacted\n \"\"\"\n return self._contacted_last\n\n @property\n def device_config(self):\n \"\"\"\n A dictionary of the configuration information for this device.\n \"\"\"\n return self._device_config\n\n @property\n def device_lock(self):\n \"\"\"\n Returns the lock for the device.\n \"\"\"\n return self._device_lock\n\n @property\n def device_type(self):\n \"\"\"\n A string representing the type of device.\n \"\"\"\n return self._device_type\n\n @property\n def has_ssh_credential(self):\n \"\"\"\n A boolean value indicating whether this device has an SSH credential.\n \"\"\"\n has_creds = len(self._ssh_credentials) > 0\n return has_creds\n\n @property\n def is_watched(self):\n \"\"\"\n A boolean indicating if this device is a watched device.\n \"\"\"\n return self._is_watched\n\n @property\n def keyid(self):\n \"\"\"\n The key identifier for this device, this is generally the identifier provided\n by the coordinator that created the device instance.\n \"\"\"\n return self._keyid\n\n @property\n def muse(self):\n \"\"\"\n The 'Muse' :class:`LandscapeDeviceExtension` attached to this device or None.\n \"\"\"\n return self._muse\n\n @property\n def power(self):\n \"\"\"\n The power agent associated with this device.\n \"\"\"\n return self._power\n\n @property\n def serial(self):\n \"\"\"\n The serial agent associated with this device.\n \"\"\"\n return self._serial\n\n @property\n def ssh(self):\n \"\"\"\n The 'SSH' :class:`LandscapeDeviceExtension` attached to this device or None.\n \"\"\"\n return self._ssh\n\n @property\n def ssh_credentials(self):\n \"\"\"\n The list of SSH credentials associated with this device\n \"\"\"\n return self._ssh_credentials\n\n @property\n def upnp(self):\n \"\"\"\n The 'UPnP' :class:`LandscapeDeviceExtension` attached to this device or None.\n \"\"\"\n return self._upnp\n\n def attach_extension(self, ext_type, extension):\n \"\"\"\n Method called by device coordinators to attach a device extension to a :class:`LandscapeDevice`.\n \"\"\"\n setattr(self, \"_\" + ext_type, extension)\n return\n\n def match_using_params(self, match_type, *match_params):\n \"\"\"\n Method that allows you to match :class:`LandscapeDevice` objects by providing a match_type and\n parameters. The match type is mapped to functions that are registered by device coordinators\n and then the function is called with the match parameters to determine if a device is a match.\n \"\"\"\n matches = False\n match_func = None\n match_self = None\n\n self._device_lock.acquire()\n try:\n if match_type in self._match_functions:\n dext_attr, match_func = self._match_functions[match_type]\n match_self = None\n if hasattr(self, dext_attr):\n match_self = getattr(self, dext_attr)\n finally:\n self._device_lock.release()\n\n if match_self is not None and match_func is not None:\n matches = match_func(match_self, *match_params)\n\n return matches\n\n def update_match_table(self, match_table: dict):\n \"\"\"\n Method called to update the match functions.\n \"\"\"\n self._device_lock.acquire()\n try:\n self._match_functions.update(match_table)\n finally:\n self._device_lock.release()\n\n return\n\n def initialize_features(self):\n \"\"\"\n Initializes the features of the device based on the feature declarations and the information\n found in the feature config.\n \"\"\"\n if \"features\" in self._device_config:\n feature_info = self._device_config[\"features\"]\n for fkey, fval in feature_info.items():\n if fkey == \"isolation\":\n self._is_isolated = fval\n elif fkey == \"power\":\n self._intitialize_power(fval)\n elif fkey == \"serial\":\n self._intitialize_serial(fval)\n elif fkey == \"\":\n pass\n return\n\n def _intitialize_power(self, power_mapping): # pylint: disable=no-self-use\n \"\"\"\n Initializes the serial port connectivity for this device.\n \"\"\"\n lscape = self._lscape_ref()\n self._power = lscape.lookup_power_agent(power_mapping)\n return\n\n def _intitialize_serial(self, serial_mapping): # pylint: disable=no-self-use\n \"\"\"\n Initializes the serial port connectivity for this device.\n \"\"\"\n #lscape = self._lscape_ref()\n #self._serial = lscape.lookup_serial_agent(serial_mapping)\n return\n","sub_path":"packages/akit/integration/landscaping/landscapedevice.py","file_name":"landscapedevice.py","file_ext":"py","file_size_in_byte":7338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"177815544","text":"import sqlite3, os \nfrom . import config, pretty\n\n_snapshotID = -1\n_caseID = -1\n\ndef connect(inDatabase):\n global _cursor, _connection\n exists = os.path.exists(config.home + inDatabase + \".db\")\n _connection = sqlite3.connect(config.home + inDatabase + \".db\",check_same_thread=False)\n _cursor = _connection.cursor()\n execute(\"PRAGMA foreign_keys = ON\")\n if not exists:\n _createNewDatabase()\n\ndef close():\n _connection.close()\n\ndef commit():\n _connection.commit()\n\ndef execute(inExecute):\n try:\n return [[str(cell) for cell in row] for row in _connection.execute(inExecute + \";\")]\n except sqlite3.OperationalError:\n print(\"SQL FAILED WITH: \" + inExecute + \";\")\n exit()\n\ndef _createNewDatabase():\n execute(\"CREATE TABLE Cases(caseID INTEGER PRIMARY KEY AUTOINCREMENT, caseName TEXT NOT NULL UNIQUE, examinerName TEXT NOT NULL, caseDesc TEXT NOT NULL, creationDate TEXT NOT NULL, modifiedDate TEXT NOT NULL)\")\n execute(\"CREATE TABLE Snapshots(snapshotID INTEGER PRIMARY KEY AUTOINCREMENT, caseID INTEGER NOT NULL, snapshotName TEXT NOT NULL, path TEXT NOT NULL, date TEXT NOT NULL, CONSTRAINT fk_cases FOREIGN KEY (caseID) REFERENCES Cases (caseID) ON DELETE CASCADE)\")\n execute(\"CREATE TABLE Files(fileID INTEGER PRIMARY KEY AUTOINCREMENT, snapshotID INTEGER NOT NULL, fileName TEXT NOT NULL, path TEXT NOT NULL, hash TEXT NOT NULL, fileType TEXT NOT NULL, size INTEGER NOT NULL, permissions INTEGER NOT NULL, changeTime TEXT NOT NULL, modifiedTime TEXT NOT NULL, birthTime TEXT NOT NULL, CONSTRAINT fk_snapshots FOREIGN KEY (snapshotID) REFERENCES Snapshots (snapshotID) ON DELETE CASCADE)\")\n execute(\"CREATE TABLE Flags(flagID INTEGER PRIMARY KEY AUTOINCREMENT, fileID INTEGER NOT NULL, flagCat TEXT NOT NULL, flagKey TEXT NOT NULL, flagDesc TEXT NOT NULL, CONSTRAINT fk_files FOREIGN KEY (fileID) REFERENCES Files (fileID) ON DELETE CASCADE)\")\n execute(\"CREATE TABLE ACLs(aclID INTEGER PRIMARY KEY AUTOINCREMENT, fileID INTEGER NOT NULL, aclObject TEXT NOT NULL, aclRule TEXT NOT NULL, CONSTRAINT fk_files FOREIGN KEY (fileID) REFERENCES Files (fileID) ON DELETE CASCADE)\")\n execute(\"INSERT INTO Cases VALUES (0,'global','SYSTEM','Snapshots placed here are accessible from any case','\" + config.time() + \"','\" + config.time() + \"')\")\n commit()\n\ndef get(inFields,inTable,inCont):\n cont = \"\"\n if len(inCont)>0:\n cont += \" WHERE \" + inCont\n return [row for row in execute(\"SELECT \" + \",\".join(inFields) + \" FROM \" + inTable + cont)]\n\ndef getCase(inCaseName):\n try:\n return [str(x[0]) for x in get([\"caseID\"],\"Cases\",\"UPPER(caseName)=UPPER('\"+sanitize(inCaseName)+\"')\")][0]\n except IndexError:\n return \"-1\"\n\ndef getSnapshot(inCaseName,inSnapshotName):\n caseID = getCase(inCaseName)\n try:\n return [str(x[0]) for x in get([\"snapshotID\"],\"Snapshots\",\"(caseID=0 OR caseID=\"+caseID+\") AND UPPER(snapshotName)=UPPER(\\'\"+sanitize(inSnapshotName)+\"\\')\")][0]\n except IndexError:\n return \"-1\"\n\ndef getFile(inCaseName,inSnapshotName,inRelativePath,inFileName):\n snapshotID = getSnapshot(inCaseName,inSnapshotName)\n return [str(x[0]) for x in get([\"fileID\"],\"Files\",\"snapshotID=\"+snapshotID+\" AND UPPER(path)=UPPER(\\'\" + inRelativePath + \"\\') AND UPPER(fileName)=UPPER(\\'\"+sanitize(inFileName)+\"\\')\")][0]\n\n\ndef sanitize(inDirty):\n dirty = str(inDirty)\n dirty = dirty.replace(\"'\",\"''\")\n clean = dirty\n return clean\n\n","sub_path":"jade/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"231450016","text":"def fibonaci(a):\n t1 = 0\n t2 = 1\n i = 1\n while i <= a:\n print(t1, end=' ')\n t1, t2 = t2, t1 + t2\n i += 1\n\n\ndef fibo(m):\n f = 0\n l = 1\n for i in range(m):\n print(f, end=' ')\n f, l = l, l + f\n\n\nk = int(input('Enter number of terms: '))\nfibonaci(k)\nprint('\\n--------------------')\nfibo(k)\n","sub_path":"Core_python/_10_Functions/_09_fibonaci.py","file_name":"_09_fibonaci.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"10588845","text":"#! /usr/bin/env python3\n#-*- coding: utf-8 -*-\nlista = []\nop = \"t\"\nwhile op == \"t\":\n while not len(lista) == 3:\n lista = input('Podaj trzy liczby oddzielone spacjami: ').split(\",\")\n #lista = [a, b, c]\n if len(lista) < 3:\n print('Wprowadzono za mało liczb.')\n elif len(lista) > 3: \n print('Wprowadzono za dużo liczb.')\n \n\n a = lista[0]\n b = lista[1]\n c = lista[2] \n\n print('Wprowadzono liczby: ', a, b, c,)\n print ('\\nNajmniejsza: ')\n \n if a < b:\n if a < c:\n najmniejsza = a\n else:\n najmniejsza = c\n elif b < c:\n najmniejsza = b\n else:\n najmniejsza = c\n\n print(najmniejsza) \n op = input('Jeszcze raz t/n? ')\n lista = []\nprint('Koniec.')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"1421.py","file_name":"1421.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"246414459","text":"import locale\nimport numpy as np\n\nfrom bball_ref.dao import teams as teams_dao, players as players_dao\nfrom bball_ref.stats import base as base_stats\n\n\nlocale.setlocale(locale.LC_ALL, '')\n\n\n###############################################################################\n########## stats helpers ##########\n###############################################################################\n\n\ndef get_team_and_all_seasons(team_id):\n \"\"\"\n given a team-id, returns a tuple of (team dataframe,\n team season dataframe)\n :param team_id:\n :return:\n \"\"\"\n\n teams_df = teams_dao.get_teams_df()\n team_df = teams_df[teams_df.id == team_id]\n\n season_df = teams_dao.get_team_seasons_by_team_df(team_id)\n\n return team_df, season_df\n\n\ndef get_team_and_player_season(team_id, year):\n \"\"\"\n given a team-id and a int year, returns a tuple of (team season dataframe,\n player season dataframe)\n :param team_id:\n :param year:\n :return:\n \"\"\"\n\n season_df = teams_dao.get_team_seasons_by_team_df(team_id)\n season_df = season_df[season_df.year == year]\n\n player_season_df = players_dao.get_season_by_team_season_df(\n \"{}-{}\".format(team_id, year)\n )\n\n return season_df, player_season_df\n\n\n###############################################################################\n########## stats classes ##########\n###############################################################################\n\n\nclass TeamHistoryStats(base_stats.BaseStats):\n \"\"\"\n overall historical team stats\n \"\"\"\n\n def __init__(self, team_id):\n self.team_id = team_id\n self.team_df, self.df = get_team_and_all_seasons(self.team_id)\n super(TeamHistoryStats, self).__init__()\n\n def get_data(self):\n\n return {\n 'team': self.get_info_and_totals(),\n 'wins_losses': self.get_wins_and_losses(),\n 'ratings': self.get_ratings()\n }\n\n def get_info_and_totals(self):\n\n return self.team_df.to_dict('records')[0]\n\n def _get_metrics_over_time(self, cols):\n\n return self.df[['id', 'year'] + cols].to_dict('records')\n\n def get_wins_and_losses(self):\n return self._get_metrics_over_time(['wins', 'losses'])\n\n def get_ratings(self):\n return self._get_metrics_over_time(\n ['srs', 'rel_off_rating', 'rel_def_rating']\n )\n\n\nclass TeamSeasonStats(base_stats.BaseStats):\n \"\"\"\n a single team-season of stats for a team + year\n \"\"\"\n\n def __init__(self, team_id, year=2015):\n self.team_id = team_id\n self.season_df, self.player_df = get_team_and_player_season(team_id, year)\n super(TeamSeasonStats, self).__init__(year=year)\n\n def get_data(self):\n roster_stats = [\n ('name', 'Name'),\n ('minutes_played', 'Minutes Played'),\n ('usg_pct', 'Usage %'),\n ('per', 'PER'),\n ('ts_pct', 'True Shooting %'),\n ('bpm', 'Box +/-'),\n ('ws', 'Win Shares'),\n ('vorp', 'Value Over Replacement')\n ]\n # only include salary if we have some data\n if not self.player_df.salary.dropna().empty:\n self.player_df['salary'] = self.player_df.salary.apply(\n lambda s: '-' if np.isnan(s) else locale.currency(s, grouping=True))\n\n roster_stats.append(('salary', 'Salary'))\n\n self.player_df['ts_pct'] = self.player_df.ts_pct * 100.\n\n return {\n 'players': self.player_df.to_dict('records'),\n 'roster_stats': roster_stats\n }","sub_path":"bball_ref/stats/teams.py","file_name":"teams.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"474119621","text":"#!/usr/bin/env python3\n\nimport os\nimport sys\nimport json\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport numpy as np\n\n\ntrain_iceberg_path = os.path.join('..', 'data', 'train_data', 'icebergs')\ntrain_other_path = os.path.join('..', 'data', 'train_data', 'other')\n\nIMG_SIZE = 75\n\ndef main():\n plot_all_in_dir(train_iceberg_path)\n plot_all_in_dir(train_other_path)\n\n return True\n\n\ndef plot_all_in_dir(directory):\n for f in os.listdir(directory):\n with open(os.path.join(directory, f), 'r') as fp:\n # load image\n img = json.load(fp)\n\n # create image data\n mat_1 = np.matrix(img['band_1']).reshape(IMG_SIZE, IMG_SIZE)\n mat_2 = np.matrix(img['band_2']).reshape(IMG_SIZE, IMG_SIZE)\n mat_s = mat_1 + mat_2\n\n # Do some plotting\n fig = plt.figure(figsize=(12, 6))\n fig.suptitle('{}: Is Iceberg: {}: Angle: {}'.\n format(f, img['is_iceberg'], img['inc_angle']))\n\n ax = plt.subplot(1, 3, 1)\n ax.imshow(mat_1, cmap=cm.Greys)\n ax.set_title('Band 1')\n\n ax = plt.subplot(1, 3, 2)\n ax.imshow(mat_2, cmap=cm.Greys)\n ax.set_title('Band 2')\n\n ax = plt.subplot(1, 3, 3)\n ax.imshow(mat_s, cmap=cm.Greys)\n ax.set_title('Sum of bands')\n\n plt.show()\n\n\nif __name__ == '__main__':\n sys.exit(not main())\n","sub_path":"visualize/plot_icebergs.py","file_name":"plot_icebergs.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"135582677","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\ndef get_soup (url):\n page = requests.get(url).content.decode()\n soup = BeautifulSoup(page,'html.parser')\n return soup\n\nlogin_url = 'http://www.114best.com/login.aspx?op=model'\n\ndriver = webdriver.Chrome()\ndriver.get(login_url)\n\nsoup = BeautifulSoup(driver.page_source,'html.parser')\n\nuser = driver.find_element_by_xpath('//*[@id=\"login-username\"]')\nprint('请输入用户名:')\n#id = input()\nuser.send_keys('18519037573')\n\npwd = driver.find_element_by_xpath('//*[@id=\"login-password\"]')\nprint('请输入密码:')\n#password = input()\npwd.send_keys('grandline7')\n\ncode = driver.find_element_by_xpath('//*[@id=\"login-verifycode\"]')\nprint('请输入验证码:')\nvc = input()\ncode.send_keys(vc)\n\nsub = driver.find_element_by_xpath('//*[@id=\"login-submit\"]')\nsub.click()\n\ntime.sleep(3)","sub_path":"spider/114/114登陆.py","file_name":"114登陆.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"405693062","text":"source = open(\"german.data\", \"r\")\r\ntarget = open(\"german.csv\", \"a\")\r\n\r\nfor line in source:\r\n\tfor i in range(len(line)):\r\n\t\tif line[i] != \" \":\r\n\t\t\ttarget.write(line[i])\r\n\t\telse:\r\n\t\t\ttarget.write(\",\")\r\n\r\nsource.close()\r\ntarget.close()","sub_path":"datatocsv.py","file_name":"datatocsv.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"178639550","text":"from django.db import models\nfrom django.utils import timezone\n\n\n# Create your models here.\nclass School(models.Model):\n name = models.CharField(max_length=200, default=\"\")\n county = models.CharField(max_length=200, default=\"\")\n students = models.IntegerField(default=0)\n dateOpened = models.DateField(default=\"\")\n def __str__(self):\n return f\"{self.name} is in {self.county} with {self.students} students and opened on {self.dateOpened}\"\n\nclass People(models.Model):\n name = models.CharField(max_length=200, default=\"\")\n age = models.DecimalField(decimal_places=3, max_digits=7)\n dob = models.DateTimeField(default=timezone.now())","sub_path":"SchoolPeopleApp/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"564606141","text":"\"\"\"\nPhase Equation near Eckhaus Boundary\n\ndtau(PHI) = - ((s/2(q0**2)) + 3 (PHIx)) (PHIxx) - (1/4(q**2)) (PHIxxxx) \n\nRef: Introduction to Pattern Formation by Rebecca Hoyle\n\nThis script should be ran serially (because it is 1D)\n\nThere should already be a folder named data\n\nusage: in dedalus mode:\npython3 phase_dyn_eckhaus.py\n\nPratik Aghor\n\"\"\"\nimport h5py\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\nimport os\n\nfrom dedalus import public as de\nfrom dedalus.extras.plot_tools import quad_mesh, pad_limits\n\nimport logging\nlogger = logging.getLogger(__name__)\n#################################################\ndef clean_data():\n path = \"data\"\n fileList = os.listdir(path)\n for fileName in fileList:\n os.remove(path+\"/\"+fileName)\n#################################################\ndef write_data(n, f, varname=\"u\"):\n # save data after every nsave steps\n n_str = str(n)\n filename = str(varname) + n_str\n hf = h5py.File('data/' + filename +'.h5', 'w') # open file in h5 format\n hf.create_dataset(str(varname), data=f)\n hf.close()\n#################################################\n# Bases and domain\nLx = 4.0*np.pi\nx_basis = de.Fourier('x', 128, interval=(-Lx, Lx), dealias=3/2)\ndomain = de.Domain([x_basis], np.float64)\n\n# Problem\n\n# Problem\nproblem = de.IVP(domain, variables=['u', 'ux', 'uxx', 'uxxx'])\n\nproblem.parameters['s'] = 0.02\nproblem.parameters['q0'] = 1.0\n\nproblem.substitutions['cf1'] = ('s/(2.0*q0*q0)')\nproblem.substitutions['cf2'] = ('1.0/(4.0*q0*q0)')\nproblem.substitutions['cf3'] = ('3.0')\n\n#problem.add_equation(\"dt(u) + cf1*dx(ux) + cf2*dx(uxxx) = -cf3*ux*uxx\")\nproblem.add_equation(\"dt(u) + cf1*dx(ux) + cf2*dx(uxxx) = -cf3*ux*uxx\")\nproblem.add_equation(\"ux - dx(u) = 0\")\nproblem.add_equation(\"uxx - dx(ux) = 0\")\nproblem.add_equation(\"uxxx - dx(uxx) = 0\")\n\n# Build solver\nsolver = problem.build_solver(de.timesteppers.SBDF2)\nsolver.stop_wall_time = np.inf\nsolver.stop_iteration = 10000\nnsave = solver.stop_iteration/500\n\n# Initial conditions\nx = domain.grid(0)\nu = solver.state['u']\nux = solver.state['ux']\nuxx = solver.state['uxx']\nuxxx = solver.state['uxxx']\n#################################################\n# IC\nn = 20; sigma = 2\nu['g'] = np.log(1 + np.cosh(n)**2/np.cosh(n*x)**2) / (2*n)\nu.differentiate(0, out=ux)\nux.differentiate(0, out=uxx)\nuxx.differentiate(0, out=uxxx)\n\n#################################################\n# Store data for final plot\nclean_data(); # clean files\nu.set_scales(1)\nwrite_data(0, np.copy(u['g']))\n\n# Main loop\ndt = 4e-3\n\ntry:\n\n logger.info('Starting loop')\n start_time = time.time()\n while solver.proceed:\n solver.step(dt)\n if solver.iteration % nsave == 0:\n u.set_scales(1)\n # c_list.append(np.copy(c['g']))\n # t_list.append(solver.sim_time)\n write_data(solver.iteration, np.copy(u['g']))\n\n if solver.iteration % 100 == 0:\n logger.info('Iteration: %i, Time: %e, dt: %e' %(solver.iteration, solver.sim_time, dt))\nexcept:\n logger.error('Exception raised, triggering end of main loop.')\n raise\nfinally:\n end_time = time.time()\n logger.info('Iterations: %i' %solver.iteration)\n logger.info('Sim end time: %f' %solver.sim_time)\n logger.info('Run time: %.2f sec' %(end_time-start_time))\n logger.info('Run time: %f cpu-hr' %((end_time-start_time)/60/60*domain.dist.comm_cart.size))\n\n# # Create space-time plot\n# c_array = np.array(c_list)\n# t_array = np.array(t_list)\n# #xmesh, ymesh = quad_mesh(x=x, y=t_array)\n# plt.figure()\n# for n in range(0, len(t_array)):\n# if(n%10 == 0):\n# plt.plot(x, c_array[n, :])\n#\n# # plt.axis(pad_limits(xmesh, ymesh))\n# # plt.colorbar()\n# plt.xlabel('$x$')\n# plt.ylabel('$u$')\n# plt.title('toy_1d, (nu,mu)=(%g,%g)' %(problem.parameters['nu'], problem.parameters['mu']))\n# plt.savefig('toy_1d.png')\n","sub_path":"dedalus_exp/phase_dyn_Eckhaus_dedalus/phase_dyn_eckhaus.py","file_name":"phase_dyn_eckhaus.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"212890648","text":"# coding: utf8\nfrom __future__ import unicode_literals\n\nfrom spacy.lang.en import English\nfrom spacy.tokens import Doc\n\n\ndef test_issue3468():\n \"\"\"Test that sentence boundaries are set correctly so Doc.is_sentenced can\n be restored after serialization.\"\"\"\n nlp = English()\n nlp.add_pipe(nlp.create_pipe(\"sentencizer\"))\n doc = nlp(\"Hello world\")\n assert doc[0].is_sent_start\n assert doc.is_sentenced\n assert len(list(doc.sents)) == 1\n doc_bytes = doc.to_bytes()\n new_doc = Doc(nlp.vocab).from_bytes(doc_bytes)\n assert new_doc[0].is_sent_start\n assert new_doc.is_sentenced\n assert len(list(new_doc.sents)) == 1\n","sub_path":"spacy/tests/regression/test_issue3468.py","file_name":"test_issue3468.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"238427054","text":"from ase.test import cli, require\nfrom ase.db import connect\nfrom ase.io.jsonio import read_json\nfrom ase.io import read\nfrom numpy.testing import assert_allclose\n\nrequire('nwchem')\n\n\ncli(\"\"\"\\\nase build O O.traj &&\nase run nwchem O.traj -o nwchem_cmdline.json &&\nase build O2 O2.traj &&\nase run nwchem O2.traj -o nwchem_cmdline.json\"\"\")\nc = connect('nwchem_cmdline.json')\ndct = read_json('nwchem_cmdline.json')\nfor name in ['O2', 'O']:\n d = c.get([('formula', '=', name)])\n id = d.id\n e1 = d.energy\n e2 = c.get_atoms(id).get_potential_energy()\n e3 = read('{name}.nwo'.format(name=name)).get_potential_energy()\n e4 = dct[id]['energy']\n assert e1 == e2 == e3 == e4\n print(e1)\nae = 2 * c.get('formula=O').energy - c.get('formula=O2').energy\nassert_allclose(ae, 6.599194233179787, atol=1e-4, rtol=1e-4)\n","sub_path":"test/nwchem/nwchem_cmdline.py","file_name":"nwchem_cmdline.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"103447123","text":"import pygame\r\nimport random\r\nfrom pygame.locals import *\r\nfrom levels import *\r\n\r\ndef checkpos(x,y,array):\r\n freeTiles = []\r\n for i in [(0,1),(0,-1),(0,0),(1,0),(-1,0)]:\r\n if array[(x+i[0])%len(array)][(y+i[1])%len(array[x])][0] in [\"b\",\"v\",\"p\"]:\r\n freeTiles.append(i)\r\n\r\n #ici\r\n\r\n return freeTiles\r\n\r\ndef enemyCanMove(e):\r\n if e[2] == \"0\" and moveCounter % 3 == 0:\r\n return True\r\n if e[2] == \"1\" and moveCounter %2 == 0:\r\n return True\r\n if e[2] == \"2\":\r\n return True\r\n return False\r\n\r\n\r\n#fonction qui gère les mouvements du joueur + enimies\r\ndef move(speed):\r\n points = 0\r\n playerpos = (-1,-1)\r\n entitiesDone = []\r\n x1,y1 = speed #direction du mouvement\r\n irange = range(len(levelMap))\r\n if x1 < 0:\r\n irange = range(len(levelMap)-1,-1,-1)\r\n\r\n for i in irange: #on parcour le niveau\r\n\r\n jrange = range(len(levelMap[i]))\r\n if y1 < 0:\r\n jrange = range(len(levelMap[i])-1,-1,-1)\r\n for j in jrange:\r\n if levelMap[i][j][0] == \"p\" and levelMap[i][j] not in entitiesDone:\r\n entitiesDone.append(levelMap[i][j])\r\n playerpos = (i,j)\r\n #la case est une bille on peut y aller et on renvoi 1\r\n if levelMap[(i+x1)%len(levelMap)][(j+y1)%len(levelMap[i])][0] == \"b\":\r\n levelMap[(i+x1)%len(levelMap)][(j+y1)%len(levelMap[i])] = levelMap[i][j]\r\n levelMap[i][j] = \"v\"\r\n points = 1\r\n\r\n #la case est vide on peut y aller\r\n if levelMap[(i+x1)%len(levelMap)][(j+y1)%len(levelMap[i])][0] == \"v\":\r\n levelMap[(i+x1)%len(levelMap)][(j+y1)%len(levelMap[i])] = levelMap[i][j]\r\n levelMap[i][j] = \"v\"\r\n\r\n if levelMap[(i+x1)%len(levelMap)][(j+y1)%len(levelMap[i])][0] == \"e\":\r\n levelMap[i][j] = \"v\"\r\n\r\n if levelMap[i][j][0] == \"e\" and levelMap[i][j] not in entitiesDone and speed != (0,0):\r\n if enemyCanMove(levelMap[i][j]):\r\n entitiesDone.append(levelMap[i][j])\r\n possibleSpeeds = checkpos(i,j,levelMap)\r\n try:\r\n x2,y2 = random.choice(possibleSpeeds)\r\n except:\r\n x2,y2 = 0,0\r\n levelMap[(i+x2)%len(levelMap)][(j+y2)%len(levelMap[i])] = levelMap[i][j]\r\n levelMap[i][j] = \"v\"\r\n\r\n if playerpos == (-1,-1):\r\n return -1\r\n\r\n #on ne peut pas aller sur la case\r\n return points\r\n\r\n#affiche a l'ecran l'image contenue dans path, au coordonées (x,y) et de taille (w,h)\r\ndef renderSprite(window,path, x, y, w, h):\r\n try:\r\n sprite = pygame.image.load(\"assets/\"+str(path)+\".png\").convert_alpha()\r\n sprite = pygame.transform.scale(sprite, (w, h))\r\n window.blit(sprite,(x,y))\r\n except:\r\n print(\"error loading texture of \" + str(path) + \".png\")\r\n exit()\r\n\r\n\r\n#initialisation de la fenetre de jeu, et des drapeaux\r\npygame.init()\r\npygame.font.init()\r\nscoreFont = pygame.font.SysFont('PrStart.ttf', 30)\r\nrunning = True\r\nlevelSelect = True\r\n\r\nwhile running:\r\n\r\n #au debut on selectionne un niveau\r\n if levelSelect:\r\n level = 0\r\n starting = True\r\n playing = True\r\n levelSelect = False\r\n window = pygame.display.set_mode((500,500))\r\n\r\n\r\n #quand on commence un niveau, initialisation des variables + redimention de la fenetre\r\n if starting:\r\n frameTime = 100\r\n countdown = 1000\r\n pygame.time.set_timer(USEREVENT+1,frameTime)\r\n GAMEOVER, FLOOR, levelMap = levelsMap[level]\r\n levelMap = list(levelMap)\r\n ROWS, COLUMNS,WIDTH,HEIGHT = (len(levelMap),len(levelMap[0]),round(900/len(levelMap)),round(900/len(levelMap[0])))\r\n window = pygame.display.set_mode((ROWS*WIDTH,COLUMNS*HEIGHT))\r\n points = 0\r\n maxWaitTime = 2\r\n pointsLeft = 1\r\n moveCounter = 0\r\n cooldown = 0\r\n speed = (0,0)\r\n starting = False\r\n playing = True\r\n\r\n #si le timer arrive a 0 on affiche l'ecran de fin\r\n if playing and (countdown <= 0 or pointsLeft == 0) :\r\n playing = False\r\n if countdown <= 0:\r\n renderSprite(window, GAMEOVER, 0, 0, 100, 100)\r\n\r\n # gestion des evenements\r\n for event in pygame.event.get():\r\n if event.type == QUIT: #bouton fermer\r\n running = False\r\n if event.type == MOUSEBUTTONDOWN: #clic kde souris\r\n x,y = event.pos\r\n levelSelect = False\r\n pass\r\n if event.type == KEYDOWN and event.key == K_a: #\"a\"\r\n level=(level+1)%len(levelsMap)\r\n starting = True\r\n if event.type == KEYDOWN and event.key == K_UP: #\"up\"\r\n speed = (0,-1)\r\n if event.type == KEYDOWN and event.key == K_DOWN: #\"down\"\r\n speed = (0,1)\r\n if event.type == KEYDOWN and event.key == K_RIGHT: #\"right\"\r\n speed = (1,0)\r\n if event.type == KEYDOWN and event.key == K_LEFT: #\"left\"\r\n speed = (-1,0)\r\n if event.type == USEREVENT+1 and playing:\r\n\r\n #le joueur et l'enemi se deplacent\r\n value = move(speed)\r\n if value != -1:\r\n points += value\r\n else :\r\n running = False\r\n if speed != (0,0):\r\n moveCounter += 1\r\n\r\n #on affiche les elements du niveau\r\n renderSprite(window, FLOOR, 0, 0, WIDTH * ROWS, HEIGHT * COLUMNS)\r\n\r\n pointsLeft = 0\r\n for x in range(len(levelMap)):\r\n for y in range(len(levelMap[x])):\r\n if levelMap[x][y][0] != \"v\":\r\n renderSprite(window, levelMap[x][y][3:], x*WIDTH, y*HEIGHT, WIDTH, HEIGHT)\r\n if levelMap[x][y][0] == \"b\":\r\n pointsLeft += 1\r\n\r\n #affichage du texte\r\n score = scoreFont.render(\"Points:\"+str(points), False, (255, 255, 255))\r\n time = scoreFont.render(\"Time left:\"+str(int(countdown)), False, (255, 255, 255))\r\n window.blit(score,(10,5))\r\n window.blit(time,(WIDTH * COLUMNS - 200,5))\r\n\r\n #reinitialisation du veteur vitesse\r\n speed = (0,0)\r\n\r\n #update de la fenetre\r\n pygame.display.update()\r\n#on ferme la fenetre\r\npygame.quit()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"587587090","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport asyncio\n\nasync def wget(host):\n\n\tconnect = asyncio.open_connection(host, 80)\n\treader, writer = await connect\n\theader = 'GET / HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n'% host\n\twriter.write(header.encode('utf-8'))\n\t\n\tn = 0\n\twhile n < 3:\n\t\tn += 1\n\t\tline = await reader.readline()\n\t\tprint(host, '\\t', line.decode('utf-8').rstrip())\n\t\tawait asyncio.sleep(2)\n\n\twriter.close()\n\nif __name__ == '__main__':\n\t\n\tloop = asyncio.get_event_loop()\n\ttasks = [wget(host) for host in ['www.yunsuo.com.cn', 'www.gov110.cn', 'www.sohu.com.cn']]\n\tloop.run_until_complete(asyncio.wait(tasks))\n\tloop.close()","sub_path":"samples/coroutine/new_coroutine.py","file_name":"new_coroutine.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"552859716","text":"# Copyright 2017 Province of British Columbia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport os\nimport subprocess\nimport tempfile\nfrom urllib.parse import urlparse\nimport multiprocessing\nfrom functools import partial\n\nimport click\nimport fiona\n\nimport pgdata\n\nfrom designatedlands import download\nfrom designatedlands import geoutil\nfrom designatedlands import util\nfrom designatedlands.config import config\n\nHELP = {\n \"cfg\": 'Path to designatedlands config file',\n \"alias\": \"The 'alias' key for the source of interest\",\n}\n\n\ndef tidy_designations(db, sources, designation_key, out_table):\n \"\"\"Add and populate 'category' column, tidy the national park designations\n \"\"\"\n # add category (rollup) column by creating lookup table from source.csv\n lookup_data = [\n dict(alias=s[designation_key], category=s[\"category\"])\n for s in sources\n if s[\"category\"]\n ]\n # create lookup table\n db[\"category_lookup\"].drop()\n db.execute(\n \"\"\"CREATE TABLE category_lookup\n (id SERIAL PRIMARY KEY, alias TEXT, category TEXT)\"\"\"\n )\n db[\"category_lookup\"].insert(lookup_data)\n # add category column\n if \"category\" not in db[out_table].columns:\n db.execute(\n \"\"\"ALTER TABLE {t}\n ADD COLUMN category TEXT\n \"\"\".format(t=out_table)\n )\n # populate category column from lookup\n db.execute(\n \"\"\"UPDATE {t} AS o\n SET category = lut.category\n FROM category_lookup AS lut\n WHERE o.designation = lut.alias\n \"\"\".format(t=out_table)\n )\n # Remove prefrixes and national park names from the designations tags\n sql = \"\"\"UPDATE {t}\n SET designation = '01_park_national'\n WHERE designation LIKE '%%01_park_national%%';\n\n UPDATE {t}\n SET designation = substring(designation from 2)\n WHERE designation ~ '^[a-c][0-9]'\n \"\"\".format(\n t=out_table\n )\n db.execute(sql)\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\ndef create_db():\n \"\"\"Create a fresh database\n \"\"\"\n util.log('Creating database %s' % config['db_url'])\n pgdata.create_db(config[\"db_url\"])\n db = pgdata.connect(config[\"db_url\"])\n db.execute(\"CREATE EXTENSION IF NOT EXISTS postgis\")\n # the pgxn extension does not work on windows\n # note to the user to add lostgis functions manually with provided\n # .bat file as a reference\n if os.name == 'posix':\n db.execute(\"CREATE EXTENSION IF NOT EXISTS lostgis\")\n else:\n util.log(\n 'Remember to add required lostgis functions to your new database',\n level=30,\n )\n util.log('See scripts\\lostgis_windows.bat as a guide', level=30)\n\n\n@cli.command()\n@click.option('--alias', '-a', help=HELP['alias'])\n@click.option(\n '--force_download',\n is_flag=True,\n default=False,\n help='Force fresh download',\n)\ndef load(alias, force_download):\n \"\"\"Download data, load to postgres\n \"\"\"\n db = pgdata.connect(config[\"db_url\"])\n sources = util.read_csv(config[\"source_csv\"])\n # filter sources based on optional provided alias and ignoring excluded\n if alias:\n sources = [s for s in sources if s[\"alias\"] == alias]\n if not sources:\n raise ValueError('Alias %s does not exist' % alias)\n\n sources = [s for s in sources if s[\"exclude\"] != 'T']\n # process sources where automated downloads are avaiable\n load_commands = []\n for source in [s for s in sources if s[\"manual_download\"] != 'T']:\n # handle BCGW downloads\n if urlparse(source[\"url\"]).hostname == 'catalogue.data.gov.bc.ca':\n file, layer = download.download_bcgw(\n source[\"url\"],\n config[\"dl_path\"],\n email=config[\"email\"],\n force_download=force_download,\n )\n # handle all other downloads (zipfiles only)\n else:\n file, layer = download.download_non_bcgw(\n source['url'],\n config['dl_path'],\n source['file_in_url'],\n source['layer_in_file'],\n force_download=force_download,\n )\n load_commands.append(\n db.ogr2pg(\n file,\n in_layer=layer,\n out_layer=source[\"input_table\"],\n sql=source[\"query\"],\n cmd_only=True,\n )\n )\n # process manually downloaded sources\n for source in [s for s in sources if s[\"manual_download\"] == 'T']:\n file = os.path.join(config['dl_path'], source[\"file_in_url\"])\n if not os.path.exists(file):\n raise Exception(file + \" does not exist, download it manually\")\n\n load_commands.append(\n db.ogr2pg(\n file,\n in_layer=source['layer_in_file'],\n out_layer=source[\"input_table\"],\n sql=source[\"query\"],\n cmd_only=True,\n )\n )\n # run all ogr commands in parallel\n util.log('Loading source data to database.')\n # https://stackoverflow.com/questions/14533458/python-threading-multiple-bash-subprocesses\n processes = [subprocess.Popen(cmd, shell=True) for cmd in load_commands]\n for p in processes:\n p.wait()\n # log ogr statements for debugging\n #for cmd in load_commands:\n # util.log(cmd)\n # subprocess.call(cmd, shell=True)\n # create tiles layer\n util.log('Creating tiles layer')\n db.execute(db.queries[\"create_tiles\"])\n\n\n@cli.command()\n@click.option(\n '--resume', '-r', help='hierarchy number at which to resume processing'\n)\n@click.option(\n '--force_preprocess',\n is_flag=True,\n default=False,\n help=\"Force re-preprocessing of input data\",\n)\n@click.option(\n '--tiles', default=None, help=\"Comma separated list of tiles to process\"\n)\ndef process(resume, force_preprocess, tiles):\n \"\"\"Create output designatedlands tables\n \"\"\"\n db = pgdata.connect(config[\"db_url\"], schema=\"public\")\n # run required preprocessing, tile, attempt to clean inputs\n geoutil.preprocess(db, config['source_csv'], force=force_preprocess)\n geoutil.tile_sources(db, config['source_csv'], force=force_preprocess)\n geoutil.clean_and_agg_sources(\n db, config['source_csv'], force=force_preprocess\n )\n # parse the list of tiles\n tilelist = geoutil.parse_tiles(db, tiles)\n # create target tables if not resuming from a bailed process\n if not resume:\n # create output tables\n db.execute(\n db.build_query(\n db.queries[\"create_outputs_prelim\"],\n {\"table\": config['out_table']},\n )\n )\n # filter sources - use only non-exlcuded sources with hierarchy > 0\n sources = [\n s\n for s in util.read_csv(config['source_csv'])\n if s['hierarchy'] != 0 and s[\"exclude\"] != 'T'\n ]\n # To create output table with overlaps, combine all source data\n # (tiles argument does not apply, we could build a tile query string but\n # it seems unnecessary)\n for source in sources:\n util.log(\n \"Inserting %s into preliminary output overlap table\" %\n source[\"tiled_table\"]\n )\n sql = db.build_query(\n db.queries[\"populate_output_overlaps\"],\n {\n \"in_table\": source[\"tiled_table\"],\n \"out_table\": config['out_table'] + \"_overlaps_prelim\",\n },\n )\n db.execute(sql)\n # To create output table with no overlaps, more processing is required\n # In case of bailing during tests/development, `resume` option is available\n # to enable resumption of processing at specified hierarchy number\n if resume:\n p_sources = [s for s in sources if int(s[\"hierarchy\"]) >= int(resume)]\n else:\n p_sources = sources\n # The tiles layer will fill in gaps between sources (so all BC is included\n # in output). To do this, first match schema of tiles to other sources\n db.execute(\"ALTER TABLE tiles ADD COLUMN IF NOT EXISTS id integer\")\n db.execute(\"UPDATE tiles SET id = tile_id\")\n db.execute(\"ALTER TABLE tiles ADD COLUMN IF NOT EXISTS designation text\")\n # Next, add simple tiles layer definition to sources list\n p_sources.append({\"cleaned_table\": \"tiles\", \"category\": None})\n # iterate through all sources\n for source in p_sources:\n sql = db.build_query(\n db.queries[\"populate_output\"],\n {\n \"in_table\": source[\"cleaned_table\"],\n \"out_table\": config['out_table'] + \"_prelim\",\n },\n )\n # determine which specified tiles are present in source layer\n src_tiles = set(\n geoutil.get_tiles(db, source[\"cleaned_table\"], tile_table='tiles')\n )\n if tilelist:\n tiles = set(tilelist) & src_tiles\n else:\n tiles = src_tiles\n if tiles:\n util.log(\n \"Inserting %s into preliminary output table\" %\n source[\"cleaned_table\"]\n )\n # for testing, run only one process and report on tile\n if config['n_processes'] == 1:\n for tile in tiles:\n util.log(tile)\n db.execute(sql, (tile + \"%\",) * 2)\n else:\n func = partial(geoutil.parallel_tiled, db.url, sql, n_subs=2)\n pool = multiprocessing.Pool(processes=config['n_processes'])\n pool.map(func, tiles)\n pool.close()\n pool.join()\n else:\n util.log(\"No tiles to process\")\n # create marine-terrestrial layer\n if 'bc_boundary' not in db.tables:\n geoutil.create_bc_boundary(db, config['n_processes'])\n\n # overlay output tables with marine-terrestrial definition\n for table in [config['out_table'], config['out_table'] + \"_overlaps\"]:\n util.log(\n 'Cutting %s with marine-terrestrial definition' % table\n )\n geoutil.intersect(\n db,\n table + \"_prelim\",\n \"bc_boundary\",\n table,\n config['n_processes'],\n tiles,\n )\n\n tidy_designations(db, sources, \"cleaned_table\", config['out_table'])\n tidy_designations(\n db, sources, \"tiled_table\", config['out_table'] + \"_overlaps\"\n )\n\n\n@cli.command()\n@click.argument('in_file', type=click.Path(exists=True))\n@click.option('--in_layer', '-l', help=\"Input layer name\")\n@click.option(\n '--dump_file',\n is_flag=True,\n default=False,\n help=\"Dump to file (out_file in .cfg)\",\n)\n@click.option('--new_layer_name', '-nln', help=\"Name of overlay output layer\")\ndef overlay(in_file, in_layer, dump_file, new_layer_name):\n \"\"\"Intersect layer with designatedlands\n \"\"\"\n # load in_file to postgres\n db = pgdata.connect(config['db_url'], schema=\"public\")\n if not in_layer:\n in_layer = fiona.listlayers(in_file)[0]\n if not new_layer_name:\n new_layer_name = in_layer[:63] # Maximum table name length is 63\n out_layer = new_layer_name[:50] + \"_overlay\"\n db.ogr2pg(in_file, in_layer=in_layer, out_layer=new_layer_name)\n # pull distinct tiles iterable into a list\n tiles = [t for t in db[\"tiles\"].distinct('map_tile')]\n # uncomment and adjust for debugging a specific tile\n # tiles = [t for t in tiles if t[:4] == '092K']\n util.log(\"Intersecting %s with %s\" % (config['out_table'], new_layer_name))\n geoutil.intersect(\n db,\n config['out_table'],\n new_layer_name,\n out_layer,\n config['n_processes'],\n tiles,\n )\n # dump result to file\n if dump_file:\n util.log(\"Dumping intersect to file %s \" % config['out_file'])\n dump(out_layer, config['out_file'], config['out_format'])\n\n\n@cli.command()\n@click.option(\n '--overlaps',\n is_flag=True,\n default=False,\n help=\"Dump output _overlaps table to file\",\n)\n@click.option('--aggregate',\n is_flag=True,\n default=False,\n help=\"Aggregate over tile boundaries\")\ndef dump(overlaps, aggregate):\n \"\"\"Dump output designatedlands table to file\n \"\"\"\n if aggregate:\n if overlaps:\n util.log('ignoring --overlaps flag')\n geoutil.dump_aggregate(config, 'designatedlands_agg')\n else:\n if overlaps:\n config['out_table'] = config['out_table'] + '_overlaps'\n db = pgdata.connect(config[\"db_url\"], schema=\"public\")\n util.log('Dumping %s to %s' % (config['out_table'], config['out_file']))\n columns = [c for c in db[config['out_table']].columns if c != 'geom' and 'prelim' not in c]\n ogr_sql = \"\"\"SELECT {cols},\n st_collectionextract(st_safe_repair(st_snaptogrid(geom, .001)), 3) as geom\n FROM {t}\n WHERE designation IS NOT NULL\n \"\"\".format(\n cols=\",\".join(columns), t=config['out_table']\n )\n util.log(ogr_sql)\n db = pgdata.connect(config[\"db_url\"])\n db.pg2ogr(\n ogr_sql,\n config['out_format'],\n config['out_file'],\n config['out_table'],\n geom_type=\"MULTIPOLYGON\",\n )\n\n\n@cli.command()\ndef run_all(config):\n \"\"\" Run complete designated lands job\n \"\"\"\n create_db(config)\n load(config)\n process(config)\n dump(config)\n\n\nif __name__ == '__main__':\n cli()\n","sub_path":"designatedlands/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"220998054","text":"'''\nwrite a program to print the following pattern\n\n1 2 3 4 5 6 7 \n 7 6 5 4 3 \n 3 4 5 \n 5 \n'''\nnum=1\nfor i in range(4):\n\n\tv=num\n\tfor j in range(7):\n\t\tif(j-i<=-1 or i+j>=7):\n\t\t\tprint(\" \",end=\" \")\n\t\telse:\n\t\t\tif(i%2==0):\n\t\t\t\tprint(num ,end=\" \")\n\t\t\t\tnum+=1\n\t\t\telse:\n\t\t\t\t\n\t\t\t\tnum-=1\n\t\t\t\tprint(num,end=\" \")\n\tprint(\" \")\n\tv=num-1\n","sub_path":"Python/DailyFlash/19mar2020/MySolutions/program4.py","file_name":"program4.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"32447496","text":"import time\nimport datetime\nfrom timeit import default_timer as timer\nimport settings\nfrom pymongo import MongoClient\nfrom faker import Faker\nfrom bson.decimal128 import Decimal128\n\nfake = Faker()\n\n####\n# Start script\n####\nstartTs = time.gmtime()\nstart = timer()\nprint(\"================================\")\nprint(\" Generating Sample IoT Data \")\nprint(\"================================\")\nprint(\"\\nStarting \" + time.strftime(\"%Y-%m-%d %H:%M:%S\", startTs) + \"\\n\")\n\n\n####\n# Main start function\n####\ndef main():\n\n mongo_client = MongoClient(MDB_CONNECTION)\n db = mongo_client[MDB_DATABASE]\n my_collection = db[MDB_COLLECTION]\n\n print('Delete existing documents.')\n result = my_collection.delete_many({})\n print('Num docs deleted: ' + str(result.deleted_count))\n\n print('Begin generating IOT documents.')\n print('Number of documents to generate: ' + str(NUM_DOCS))\n\n for index in range(int(NUM_DOCS)):\n # create timestamp\n fake_timestamp = fake.date_this_year()\n\n # Define IoT Document\n my_iot_document = {\n \"username\": fake.user_name(),\n \"remote_ipv4\": fake.ipv4(),\n \"httpMethod\": fake.http_method(),\n \"hostName\": fake.hostname(),\n \"portNum\": fake.port_number(),\n \"location\": {\n \"type\": \"Point\",\n \"coordinates\": [\n Decimal128(fake.longitude()),\n Decimal128(fake.latitude())\n ]\n },\n \"dateAccessed\": datetime.datetime(fake_timestamp.year, fake_timestamp.month, fake_timestamp.day)\n }\n\n if index == 1:\n print('Example Document')\n print(my_iot_document)\n\n # Indicate how many docs inserted every 100 iterations\n if index % 100 == 0:\n print('Docs inserted: ' + str(index))\n\n my_collection.insert_one(my_iot_document)\n\n\n####\n# Constants loaded from .env file\n####\nMDB_CONNECTION = settings.MDB_CONNECTION\nMDB_DATABASE = settings.MDB_DATABASE\nMDB_COLLECTION = settings.MDB_COLLECTION\nNUM_DOCS = settings.NUM_DOCS\n\n####\n# Main\n####\nif __name__ == '__main__':\n main()\n\n####\n# Indicate end of script\n####\nend = timer()\nendTs = time.gmtime()\ntotal_time = end - start\n\nif total_time < 1:\n docs_inserted_time = int(NUM_DOCS) / 1\nelse:\n docs_inserted_time = int(NUM_DOCS) / total_time\n\nprint(\"\\nEnding \" + time.strftime(\"%Y-%m-%d %H:%M:%S\", endTs))\nprint('===============================')\n\nif total_time > 60:\n print('Total Time Elapsed (in minutes): ' + str(total_time/60))\nelse:\n print('Total Time Elapsed (in seconds): ' + str(total_time))\nprint('===============================')\nprint('Number of Docs inserted per second: ' + str(docs_inserted_time))\nprint('===============================')\n","sub_path":"generate_iot_data.py","file_name":"generate_iot_data.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"508126054","text":"import random\n\nn = 20\n\nz = [random.randint(1,5)]\nfor i in range(0,n):\n z = z + [z[i] + random.randint(1,5) ]\n\nprint(z)\n\nprint()\ncislo = int(input(\"zadaj číslo:\"))\n\"\"\"\ni = 0\n\nwhile i < len(z):\n if z[i]>cislo:\n break\n i+=1\n \nz.insert(i,cislo)\n\n\nfor t in range(0,n+1):\n print(z[t], end = \", \")\n\"\"\"\n\ndh = 0\nhh = n\nstred = (dh + hh) // 2\n\nwhile dh != stred and hh != stred:\n if cislo > z[stred]:\n dh = stred\n stred = (dh + hh) // 2\n else:\n hh = stred\n stred = (dh + hh) // 2\n\nif stred == 0:\n z.insert(0,cislo)\nelse:\n if dh == stred:\n z.insert(stred + 1, cislo)\n if hh == stred:\n z.insert(stred - 1, cislo)\n \nprint()\nprint(z)\n","sub_path":"python/insert.py","file_name":"insert.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"114355051","text":"from django.db import models\n\n\nclass CarModel(models.Model):\n class Meta:\n verbose_name = '車種'\n\n name = models.CharField(verbose_name='車名', max_length=50)\n model_name = models.CharField(verbose_name='型式', max_length=10)\n image = models.ImageField(verbose_name='画像', blank=True)\n delivery_date = models.DateTimeField(verbose_name='納車日', blank=True, null=True)\n url = models.URLField(verbose_name='公式ページ', blank=True)\n\n def __str__(self):\n return self.name\n\n\nclass Manufacturer(models.Model):\n class Meta:\n verbose_name = 'メーカー'\n\n name = models.CharField(verbose_name='社名', max_length=50)\n url = models.URLField(verbose_name='公式ページ', blank=True)\n\n def __str__(self):\n return self.name\n\n\nclass Parts(models.Model):\n class Meta:\n verbose_name = '部品'\n\n status_list = (\n ('installed', '導入済み'),\n ('nothing_yet', '未���入')\n )\n\n conforming_car = models.ForeignKey(CarModel, on_delete=models.CASCADE, verbose_name='適合車', null=True, default=\"\")\n maker = models.ForeignKey(Manufacturer, on_delete=models.CASCADE, verbose_name='製造会社', null=True, default=\"\")\n name = models.CharField(verbose_name='パーツ名', max_length=50)\n price = models.IntegerField(verbose_name='価格')\n image = models.ImageField(verbose_name='製品画像', blank=True)\n status = models.CharField(verbose_name='導入状態', choices=status_list, max_length=11)\n intro_date = models.DateTimeField(verbose_name='導入日', blank=True, null=True)\n url = models.URLField(verbose_name='公式ページ', blank=True)\n\n def __str__(self):\n return self.name\n","sub_path":"main_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"480247007","text":"# ----------------------------------------------------------------------------\n# Copyright (c) 2013--, scikit-bio development team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# ----------------------------------------------------------------------------\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom unittest import TestCase, main\nfrom collections import defaultdict\n\nimport numpy as np\nimport numpy.testing as npt\nfrom scipy.stats import pearsonr\n\nfrom skbio.io._fileobject import StringIO\nfrom skbio import DistanceMatrix, TreeNode\nfrom skbio.tree import (DuplicateNodeError, NoLengthError,\n TreeError, MissingNodeError, NoParentError)\nfrom skbio.util import RepresentationWarning\n\n\nclass TreeTests(TestCase):\n\n def setUp(self):\n \"\"\"Prep the self\"\"\"\n self.simple_t = TreeNode.read(StringIO(u\"((a,b)i1,(c,d)i2)root;\"))\n nodes = dict([(x, TreeNode(x)) for x in 'abcdefgh'])\n nodes['a'].append(nodes['b'])\n nodes['b'].append(nodes['c'])\n nodes['c'].append(nodes['d'])\n nodes['c'].append(nodes['e'])\n nodes['c'].append(nodes['f'])\n nodes['f'].append(nodes['g'])\n nodes['a'].append(nodes['h'])\n self.TreeNode = nodes\n self.TreeRoot = nodes['a']\n\n def rev_f(items):\n items.reverse()\n\n def rotate_f(items):\n tmp = items[-1]\n items[1:] = items[:-1]\n items[0] = tmp\n\n self.rev_f = rev_f\n self.rotate_f = rotate_f\n self.complex_tree = TreeNode.read(StringIO(u\"(((a,b)int1,(x,y,(w,z)int\"\n \"2,(c,d)int3)int4),(e,f)int\"\n \"5);\"))\n\n def test_observed_node_counts(self):\n \"\"\"returns observed nodes counts given vector of otu observation counts\n \"\"\"\n # no OTUs observed\n otu_counts = {}\n expected = defaultdict(int)\n self.assertEqual(self.simple_t.observed_node_counts(otu_counts),\n expected)\n # error on zero count(s)\n otu_counts = {'a': 0}\n self.assertRaises(ValueError, self.simple_t.observed_node_counts,\n otu_counts)\n otu_counts = {'a': 0, 'b': 0, 'c': 0, 'd': 0}\n self.assertRaises(ValueError, self.simple_t.observed_node_counts,\n otu_counts)\n\n # all OTUs observed once\n otu_counts = {'a': 1, 'b': 1, 'c': 1, 'd': 1}\n expected = defaultdict(int)\n expected[self.simple_t.find('root')] = 4\n expected[self.simple_t.find('i1')] = 2\n expected[self.simple_t.find('i2')] = 2\n expected[self.simple_t.find('a')] = 1\n expected[self.simple_t.find('b')] = 1\n expected[self.simple_t.find('c')] = 1\n expected[self.simple_t.find('d')] = 1\n self.assertEqual(self.simple_t.observed_node_counts(otu_counts),\n expected)\n\n # some OTUs observed twice\n otu_counts = {'a': 2, 'b': 1, 'c': 1, 'd': 1}\n expected = defaultdict(int)\n expected[self.simple_t.find('root')] = 5\n expected[self.simple_t.find('i1')] = 3\n expected[self.simple_t.find('i2')] = 2\n expected[self.simple_t.find('a')] = 2\n expected[self.simple_t.find('b')] = 1\n expected[self.simple_t.find('c')] = 1\n expected[self.simple_t.find('d')] = 1\n self.assertEqual(self.simple_t.observed_node_counts(otu_counts),\n expected)\n\n otu_counts = {'a': 2, 'b': 1, 'c': 1, 'd': 2}\n expected = defaultdict(int)\n expected[self.simple_t.find('root')] = 6\n expected[self.simple_t.find('i1')] = 3\n expected[self.simple_t.find('i2')] = 3\n expected[self.simple_t.find('a')] = 2\n expected[self.simple_t.find('b')] = 1\n expected[self.simple_t.find('c')] = 1\n expected[self.simple_t.find('d')] = 2\n self.assertEqual(self.simple_t.observed_node_counts(otu_counts),\n expected)\n\n # some OTUs observed, others not observed\n otu_counts = {'a': 2, 'b': 1}\n expected = defaultdict(int)\n expected[self.simple_t.find('root')] = 3\n expected[self.simple_t.find('i1')] = 3\n expected[self.simple_t.find('a')] = 2\n expected[self.simple_t.find('b')] = 1\n self.assertEqual(self.simple_t.observed_node_counts(otu_counts),\n expected)\n\n otu_counts = {'d': 1}\n expected = defaultdict(int)\n expected[self.simple_t.find('root')] = 1\n expected[self.simple_t.find('i2')] = 1\n expected[self.simple_t.find('d')] = 1\n self.assertEqual(self.simple_t.observed_node_counts(otu_counts),\n expected)\n\n # error on non-tips\n otu_counts = {'a': 2, 'e': 1}\n self.assertRaises(MissingNodeError, self.simple_t.observed_node_counts,\n otu_counts)\n otu_counts = {'a': 2, 'i1': 1}\n self.assertRaises(MissingNodeError, self.simple_t.observed_node_counts,\n otu_counts)\n\n # test with another tree\n otu_counts = {}\n expected = defaultdict(int)\n self.assertEqual(self.complex_tree.observed_node_counts(otu_counts),\n expected)\n\n otu_counts = {'e': 42, 'f': 1}\n expected[self.complex_tree.root()] = 43\n expected[self.complex_tree.find('int5')] = 43\n expected[self.complex_tree.find('e')] = 42\n expected[self.complex_tree.find('f')] = 1\n self.assertEqual(self.complex_tree.observed_node_counts(otu_counts),\n expected)\n\n def test_count(self):\n \"\"\"Get node counts\"\"\"\n exp = 7\n obs = self.simple_t.count()\n self.assertEqual(obs, exp)\n\n exp = 4\n obs = self.simple_t.count(tips=True)\n self.assertEqual(obs, exp)\n\n def test_copy(self):\n \"\"\"copy a tree\"\"\"\n self.simple_t.children[0].length = 1.2\n self.simple_t.children[1].children[0].length = 0.5\n cp = self.simple_t.copy()\n gen = zip(cp.traverse(include_self=True),\n self.simple_t.traverse(include_self=True))\n\n for a, b in gen:\n self.assertIsNot(a, b)\n self.assertEqual(a.name, b.name)\n self.assertEqual(a.length, b.length)\n\n def test_append(self):\n \"\"\"Append a node to a tree\"\"\"\n second_tree = TreeNode.read(StringIO(u\"(x,y)z;\"))\n self.simple_t.append(second_tree)\n\n self.assertEqual(self.simple_t.children[0].name, 'i1')\n self.assertEqual(self.simple_t.children[1].name, 'i2')\n self.assertEqual(self.simple_t.children[2].name, 'z')\n self.assertEqual(len(self.simple_t.children), 3)\n self.assertEqual(self.simple_t.children[2].children[0].name, 'x')\n self.assertEqual(self.simple_t.children[2].children[1].name, 'y')\n self.assertEqual(second_tree.parent, self.simple_t)\n\n def test_extend(self):\n \"\"\"Extend a few nodes\"\"\"\n second_tree = TreeNode.read(StringIO(u\"(x1,y1)z1;\"))\n third_tree = TreeNode.read(StringIO(u\"(x2,y2)z2;\"))\n first_tree = TreeNode.read(StringIO(u\"(x1,y1)z1;\"))\n fourth_tree = TreeNode.read(StringIO(u\"(x2,y2)z2;\"))\n self.simple_t.extend([second_tree, third_tree])\n\n first_tree.extend(fourth_tree.children)\n self.assertEqual(0, len(fourth_tree.children))\n self.assertEqual(first_tree.children[0].name, 'x1')\n self.assertEqual(first_tree.children[1].name, 'y1')\n self.assertEqual(first_tree.children[2].name, 'x2')\n self.assertEqual(first_tree.children[3].name, 'y2')\n\n self.assertEqual(self.simple_t.children[0].name, 'i1')\n self.assertEqual(self.simple_t.children[1].name, 'i2')\n self.assertEqual(self.simple_t.children[2].name, 'z1')\n self.assertEqual(self.simple_t.children[3].name, 'z2')\n self.assertEqual(len(self.simple_t.children), 4)\n self.assertEqual(self.simple_t.children[2].children[0].name, 'x1')\n self.assertEqual(self.simple_t.children[2].children[1].name, 'y1')\n self.assertEqual(self.simple_t.children[3].children[0].name, 'x2')\n self.assertEqual(self.simple_t.children[3].children[1].name, 'y2')\n self.assertIs(second_tree.parent, self.simple_t)\n self.assertIs(third_tree.parent, self.simple_t)\n\n def test_extend_empty(self):\n \"\"\"Extend on the empty case should work\"\"\"\n self.simple_t.extend([])\n self.assertEqual(self.simple_t.children[0].name, 'i1')\n self.assertEqual(self.simple_t.children[1].name, 'i2')\n self.assertEqual(len(self.simple_t.children), 2)\n\n def test_iter(self):\n \"\"\"iter wraps children\"\"\"\n exp = ['i1', 'i2']\n obs = [n.name for n in self.simple_t]\n self.assertEqual(obs, exp)\n\n def test_gops(self):\n \"\"\"Basic TreeNode operations should work as expected\"\"\"\n p = TreeNode()\n self.assertEqual(str(p), ';\\n')\n p.name = 'abc'\n self.assertEqual(str(p), 'abc;\\n')\n p.length = 3\n self.assertEqual(str(p), 'abc:3;\\n') # don't suppress branch from root\n q = TreeNode()\n p.append(q)\n self.assertEqual(str(p), '()abc:3;\\n')\n r = TreeNode()\n q.append(r)\n self.assertEqual(str(p), '(())abc:3;\\n')\n r.name = 'xyz'\n self.assertEqual(str(p), '((xyz))abc:3;\\n')\n q.length = 2\n self.assertEqual(str(p), '((xyz):2)abc:3;\\n')\n\n def test_pop(self):\n \"\"\"Pop off a node\"\"\"\n second_tree = TreeNode.read(StringIO(u\"(x1,y1)z1;\"))\n third_tree = TreeNode.read(StringIO(u\"(x2,y2)z2;\"))\n self.simple_t.extend([second_tree, third_tree])\n\n i1 = self.simple_t.pop(0)\n z2 = self.simple_t.pop()\n\n self.assertEqual(i1.name, 'i1')\n self.assertEqual(z2.name, 'z2')\n self.assertEqual(i1.children[0].name, 'a')\n self.assertEqual(i1.children[1].name, 'b')\n self.assertEqual(z2.children[0].name, 'x2')\n self.assertEqual(z2.children[1].name, 'y2')\n\n self.assertEqual(self.simple_t.children[0].name, 'i2')\n self.assertEqual(self.simple_t.children[1].name, 'z1')\n self.assertEqual(len(self.simple_t.children), 2)\n\n def test_remove(self):\n \"\"\"Remove nodes\"\"\"\n self.assertTrue(self.simple_t.remove(self.simple_t.children[0]))\n self.assertEqual(len(self.simple_t.children), 1)\n n = TreeNode()\n self.assertFalse(self.simple_t.remove(n))\n\n def test_remove_deleted(self):\n \"\"\"Remove nodes by function\"\"\"\n def f(node):\n return node.name in ['b', 'd']\n\n self.simple_t.remove_deleted(f)\n exp = \"((a)i1,(c)i2)root;\\n\"\n obs = str(self.simple_t)\n self.assertEqual(obs, exp)\n\n def test_adopt(self):\n \"\"\"Adopt a node!\"\"\"\n n1 = TreeNode(name='n1')\n n2 = TreeNode(name='n2')\n n3 = TreeNode(name='n3')\n\n self.simple_t._adopt(n1)\n self.simple_t.children[-1]._adopt(n2)\n n2._adopt(n3)\n\n # adopt doesn't update .children\n self.assertEqual(len(self.simple_t.children), 2)\n\n self.assertIs(n1.parent, self.simple_t)\n self.assertIs(n2.parent, self.simple_t.children[-1])\n self.assertIs(n3.parent, n2)\n\n def test_remove_node(self):\n \"\"\"Remove a node by index\"\"\"\n n = self.simple_t._remove_node(-1)\n self.assertEqual(n.parent, None)\n self.assertEqual(len(self.simple_t.children), 1)\n self.assertEqual(len(n.children), 2)\n self.assertNotIn(n, self.simple_t.children)\n\n def test_prune(self):\n \"\"\"Collapse single descendent nodes\"\"\"\n # check the identity case\n cp = self.simple_t.copy()\n self.simple_t.prune()\n\n gen = zip(cp.traverse(include_self=True),\n self.simple_t.traverse(include_self=True))\n\n for a, b in gen:\n self.assertIsNot(a, b)\n self.assertEqual(a.name, b.name)\n self.assertEqual(a.length, b.length)\n\n # create a single descendent by removing tip 'a'\n n = self.simple_t.children[0]\n n.remove(n.children[0])\n self.simple_t.prune()\n\n self.assertEqual(len(self.simple_t.children), 2)\n self.assertEqual(self.simple_t.children[0].name, 'i2')\n self.assertEqual(self.simple_t.children[1].name, 'b')\n\n def test_prune_length(self):\n \"\"\"Collapse single descendent nodes\"\"\"\n # check the identity case\n cp = self.simple_t.copy()\n self.simple_t.prune()\n\n gen = zip(cp.traverse(include_self=True),\n self.simple_t.traverse(include_self=True))\n\n for a, b in gen:\n self.assertIsNot(a, b)\n self.assertEqual(a.name, b.name)\n self.assertEqual(a.length, b.length)\n\n for n in self.simple_t.traverse():\n n.length = 1.0\n\n # create a single descendent by removing tip 'a'\n n = self.simple_t.children[0]\n n.remove(n.children[0])\n self.simple_t.prune()\n\n self.assertEqual(len(self.simple_t.children), 2)\n self.assertEqual(self.simple_t.children[0].name, 'i2')\n self.assertEqual(self.simple_t.children[1].name, 'b')\n self.assertEqual(self.simple_t.children[1].length, 2.0)\n\n def test_subset(self):\n \"\"\"subset should return set of leaves that descends from node\"\"\"\n t = self.simple_t\n self.assertEqual(t.subset(), frozenset('abcd'))\n c = t.children[0]\n self.assertEqual(c.subset(), frozenset('ab'))\n leaf = c.children[1]\n self.assertEqual(leaf.subset(), frozenset(''))\n\n def test_subsets(self):\n \"\"\"subsets should return all subsets descending from a set\"\"\"\n t = self.simple_t\n self.assertEqual(t.subsets(), frozenset(\n [frozenset('ab'), frozenset('cd')]))\n\n def test_is_tip(self):\n \"\"\"see if we're a tip or not\"\"\"\n self.assertFalse(self.simple_t.is_tip())\n self.assertFalse(self.simple_t.children[0].is_tip())\n self.assertTrue(self.simple_t.children[0].children[0].is_tip())\n\n def test_is_root(self):\n \"\"\"see if we're at the root or not\"\"\"\n self.assertTrue(self.simple_t.is_root())\n self.assertFalse(self.simple_t.children[0].is_root())\n self.assertFalse(self.simple_t.children[0].children[0].is_root())\n\n def test_root(self):\n \"\"\"Get the root!\"\"\"\n root = self.simple_t\n self.assertIs(root, self.simple_t.root())\n self.assertIs(root, self.simple_t.children[0].root())\n self.assertIs(root, self.simple_t.children[1].children[1].root())\n\n def test_invalidate_lookup_caches(self):\n root = self.simple_t\n root.create_caches()\n self.assertNotEqual(root._tip_cache, {})\n self.assertNotEqual(root._non_tip_cache, {})\n root.invalidate_caches()\n self.assertEqual(root._tip_cache, {})\n self.assertEqual(root._non_tip_cache, {})\n\n def test_invalidate_attr_caches(self):\n tree = TreeNode.read(StringIO(u\"((a,b,(c,d)e)f,(g,h)i)root;\"))\n\n def f(n):\n return [n.name] if n.is_tip() else []\n\n tree.cache_attr(f, 'tip_names')\n tree.invalidate_caches()\n for n in tree.traverse(include_self=True):\n self.assertFalse(hasattr(n, 'tip_names'))\n\n def test_create_caches_duplicate_tip_names(self):\n with self.assertRaises(DuplicateNodeError):\n TreeNode.read(StringIO(u'(a, a);')).create_caches()\n\n def test_find_all(self):\n t = TreeNode.read(StringIO(u\"((a,b)c,((d,e)c)c,(f,(g,h)c)a)root;\"))\n exp = [t.children[0],\n t.children[1].children[0],\n t.children[1],\n t.children[2].children[1]]\n obs = t.find_all('c')\n self.assertEqual(obs, exp)\n\n identity = t.find_all(t)\n self.assertEqual(len(identity), 1)\n self.assertEqual(identity[0], t)\n\n identity_name = t.find_all('root')\n self.assertEqual(len(identity_name), 1)\n self.assertEqual(identity_name[0], t)\n\n exp = [t.children[2],\n t.children[0].children[0]]\n obs = t.find_all('a')\n self.assertEqual(obs, exp)\n\n with self.assertRaises(MissingNodeError):\n t.find_all('missing')\n\n def test_find(self):\n \"\"\"Find a node in a tree\"\"\"\n t = TreeNode.read(StringIO(u\"((a,b)c,(d,e)f);\"))\n exp = t.children[0]\n obs = t.find('c')\n self.assertEqual(obs, exp)\n\n exp = t.children[0].children[1]\n obs = t.find('b')\n self.assertEqual(obs, exp)\n\n with self.assertRaises(MissingNodeError):\n t.find('does not exist')\n\n def test_find_cache_bug(self):\n \"\"\"First implementation did not force the cache to be at the root\"\"\"\n t = TreeNode.read(StringIO(u\"((a,b)c,(d,e)f,(g,h)f);\"))\n exp_tip_cache_keys = set(['a', 'b', 'd', 'e', 'g', 'h'])\n exp_non_tip_cache_keys = set(['c', 'f'])\n tip_a = t.children[0].children[0]\n tip_a.create_caches()\n self.assertEqual(tip_a._tip_cache, {})\n self.assertEqual(set(t._tip_cache), exp_tip_cache_keys)\n self.assertEqual(set(t._non_tip_cache), exp_non_tip_cache_keys)\n self.assertEqual(t._non_tip_cache['f'], [t.children[1], t.children[2]])\n\n def test_find_by_id(self):\n \"\"\"Find a node by id\"\"\"\n t1 = TreeNode.read(StringIO(u\"((,),(,,));\"))\n t2 = TreeNode.read(StringIO(u\"((,),(,,));\"))\n\n exp = t1.children[1]\n obs = t1.find_by_id(6) # right inner node with 3 children\n self.assertEqual(obs, exp)\n\n exp = t2.children[1]\n obs = t2.find_by_id(6) # right inner node with 3 children\n self.assertEqual(obs, exp)\n\n with self.assertRaises(MissingNodeError):\n t1.find_by_id(100)\n\n def test_find_by_func(self):\n \"\"\"Find nodes by a function\"\"\"\n t = TreeNode.read(StringIO(u\"((a,b)c,(d,e)f);\"))\n\n def func(x):\n return x.parent == t.find('c')\n\n exp = ['a', 'b']\n obs = [n.name for n in t.find_by_func(func)]\n self.assertEqual(obs, exp)\n\n def test_ancestors(self):\n \"\"\"Get all the ancestors\"\"\"\n exp = ['i1', 'root']\n obs = self.simple_t.children[0].children[0].ancestors()\n self.assertEqual([o.name for o in obs], exp)\n\n exp = ['root']\n obs = self.simple_t.children[0].ancestors()\n self.assertEqual([o.name for o in obs], exp)\n\n exp = []\n obs = self.simple_t.ancestors()\n self.assertEqual([o.name for o in obs], exp)\n\n def test_siblings(self):\n \"\"\"Get the siblings\"\"\"\n exp = []\n obs = self.simple_t.siblings()\n self.assertEqual(obs, exp)\n\n exp = ['i2']\n obs = self.simple_t.children[0].siblings()\n self.assertEqual([o.name for o in obs], exp)\n\n exp = ['c']\n obs = self.simple_t.children[1].children[1].siblings()\n self.assertEqual([o.name for o in obs], exp)\n\n self.simple_t.append(TreeNode(name=\"foo\"))\n self.simple_t.append(TreeNode(name=\"bar\"))\n exp = ['i1', 'foo', 'bar']\n obs = self.simple_t.children[1].siblings()\n self.assertEqual([o.name for o in obs], exp)\n\n def test_ascii_art(self):\n \"\"\"Make some ascii trees\"\"\"\n # unlabeled internal node\n tr = TreeNode.read(StringIO(u\"(B:0.2,(C:0.3,D:0.4):0.6)F;\"))\n obs = tr.ascii_art(show_internal=True, compact=False)\n exp = \" /-B\\n-F-------|\\n | /-C\\n \"\\\n \" \\\\--------|\\n \\\\-D\"\n self.assertEqual(obs, exp)\n obs = tr.ascii_art(show_internal=True, compact=True)\n exp = \"-F------- /-B\\n \\-------- /-C\\n \\-D\"\n self.assertEqual(obs, exp)\n obs = tr.ascii_art(show_internal=False, compact=False)\n exp = \" /-B\\n---------|\\n | /-C\\n \"\\\n \" \\\\--------|\\n \\\\-D\"\n self.assertEqual(obs, exp)\n\n def test_ascii_art_three_children(self):\n obs = TreeNode.read(StringIO(u'(a,(b,c,d));')).ascii_art()\n self.assertEqual(obs, exp_ascii_art_three_children)\n\n def test_accumulate_to_ancestor(self):\n \"\"\"Get the distance from a node to its ancestor\"\"\"\n t = TreeNode.read(StringIO(\n u\"((a:0.1,b:0.2)c:0.3,(d:0.4,e)f:0.5)root;\"))\n a = t.find('a')\n b = t.find('b')\n exp_to_root = 0.1 + 0.3\n obs_to_root = a.accumulate_to_ancestor(t)\n self.assertEqual(obs_to_root, exp_to_root)\n\n with self.assertRaises(NoParentError):\n a.accumulate_to_ancestor(b)\n\n def test_distance(self):\n \"\"\"Get the distance between two nodes\"\"\"\n t = TreeNode.read(StringIO(\n u\"((a:0.1,b:0.2)c:0.3,(d:0.4,e)f:0.5)root;\"))\n tips = sorted([n for n in t.tips()], key=lambda x: x.name)\n\n npt.assert_almost_equal(tips[0].distance(tips[0]), 0.0)\n npt.assert_almost_equal(tips[0].distance(tips[1]), 0.3)\n npt.assert_almost_equal(tips[0].distance(tips[2]), 1.3)\n with self.assertRaises(NoLengthError):\n tips[0].distance(tips[3])\n\n npt.assert_almost_equal(tips[1].distance(tips[0]), 0.3)\n npt.assert_almost_equal(tips[1].distance(tips[1]), 0.0)\n npt.assert_almost_equal(tips[1].distance(tips[2]), 1.4)\n with self.assertRaises(NoLengthError):\n tips[1].distance(tips[3])\n\n self.assertEqual(tips[2].distance(tips[0]), 1.3)\n self.assertEqual(tips[2].distance(tips[1]), 1.4)\n self.assertEqual(tips[2].distance(tips[2]), 0.0)\n with self.assertRaises(NoLengthError):\n tips[2].distance(tips[3])\n\n def test_lowest_common_ancestor(self):\n \"\"\"TreeNode lowestCommonAncestor should return LCA for set of tips\"\"\"\n t1 = TreeNode.read(StringIO(u\"((a,(b,c)d)e,f,(g,h)i)j;\"))\n t2 = t1.copy()\n t3 = t1.copy()\n t4 = t1.copy()\n input1 = ['a'] # return self\n input2 = ['a', 'b'] # return e\n input3 = ['b', 'c'] # return d\n input4 = ['a', 'h', 'g'] # return j\n exp1 = t1.find('a')\n exp2 = t2.find('e')\n exp3 = t3.find('d')\n exp4 = t4\n obs1 = t1.lowest_common_ancestor(input1)\n obs2 = t2.lowest_common_ancestor(input2)\n obs3 = t3.lowest_common_ancestor(input3)\n obs4 = t4.lowest_common_ancestor(input4)\n self.assertEqual(obs1, exp1)\n self.assertEqual(obs2, exp2)\n self.assertEqual(obs3, exp3)\n self.assertEqual(obs4, exp4)\n\n # verify multiple calls work\n t_mul = t1.copy()\n exp_1 = t_mul.find('d')\n exp_2 = t_mul.find('i')\n obs_1 = t_mul.lowest_common_ancestor(['b', 'c'])\n obs_2 = t_mul.lowest_common_ancestor(['g', 'h'])\n self.assertEqual(obs_1, exp_1)\n self.assertEqual(obs_2, exp_2)\n\n # empty case\n with self.assertRaises(ValueError):\n t1.lowest_common_ancestor([])\n\n def test_get_max_distance(self):\n \"\"\"get_max_distance should get max tip distance across tree\"\"\"\n tree = TreeNode.read(StringIO(\n u\"((a:0.1,b:0.2)c:0.3,(d:0.4,e:0.5)f:0.6)root;\"))\n dist, nodes = tree.get_max_distance()\n npt.assert_almost_equal(dist, 1.6)\n self.assertEqual(sorted([n.name for n in nodes]), ['b', 'e'])\n\n def test_set_max_distance(self):\n \"\"\"set_max_distance sets MaxDistTips across tree\"\"\"\n tree = TreeNode.read(StringIO(\n u\"((a:0.1,b:0.2)c:0.3,(d:0.4,e:0.5)f:0.6)root;\"))\n tree._set_max_distance()\n tip_a, tip_b = tree.MaxDistTips\n self.assertEqual(tip_a[0] + tip_b[0], 1.6)\n self.assertEqual(sorted([tip_a[1].name, tip_b[1].name]), ['b', 'e'])\n\n def test_set_max_distance_tie_bug(self):\n \"\"\"Corresponds to #1077\"\"\"\n s = StringIO(\"((a:1,b:1)c:2,(d:3,e:4)f:5)root;\")\n t = TreeNode.read(s)\n\n exp = ((3.0, t.find('a')), (9.0, t.find('e')))\n\n # the above tree would trigger an exception in max. The central issue\n # was that the data being passed to max were a tuple of tuple:\n # ((left_d, left_n), (right_d, right_n))\n # the call to max would break in this scenario as it would fall onto\n # idx 1 of each tuple to assess the \"max\".\n t._set_max_distance()\n\n self.assertEqual(t.MaxDistTips, exp)\n\n def test_set_max_distance_inplace_modification_bug(self):\n \"\"\"Corresponds to #1223\"\"\"\n s = StringIO(\"((a:1,b:1)c:2,(d:3,e:4)f:5)root;\")\n t = TreeNode.read(s)\n\n exp = [((0.0, t.find('a')), (0.0, t.find('a'))),\n ((0.0, t.find('b')), (0.0, t.find('b'))),\n ((1.0, t.find('a')), (1.0, t.find('b'))),\n ((0.0, t.find('d')), (0.0, t.find('d'))),\n ((0.0, t.find('e')), (0.0, t.find('e'))),\n ((3.0, t.find('d')), (4.0, t.find('e'))),\n ((3.0, t.find('a')), (9.0, t.find('e')))]\n\n t._set_max_distance()\n\n self.assertEqual([n.MaxDistTips for n in t.postorder()], exp)\n\n def test_shear(self):\n \"\"\"Shear the nodes\"\"\"\n t = TreeNode.read(StringIO(u'((H:1,G:1):2,(R:0.5,M:0.7):3);'))\n obs = str(t.shear(['G', 'M']))\n exp = '(G:3.0,M:3.7);\\n'\n self.assertEqual(obs, exp)\n\n def test_compare_tip_distances(self):\n t = TreeNode.read(StringIO(u'((H:1,G:1):2,(R:0.5,M:0.7):3);'))\n t2 = TreeNode.read(StringIO(u'(((H:1,G:1,O:1):2,R:3):1,X:4);'))\n obs = t.compare_tip_distances(t2)\n # note: common taxa are H, G, R (only)\n m1 = np.array([[0, 2, 6.5], [2, 0, 6.5], [6.5, 6.5, 0]])\n m2 = np.array([[0, 2, 6], [2, 0, 6], [6, 6, 0]])\n r = pearsonr(m1.flat, m2.flat)[0]\n self.assertAlmostEqual(obs, (1 - r) / 2)\n\n def test_compare_tip_distances_sample(self):\n t = TreeNode.read(StringIO(u'((H:1,G:1):2,(R:0.5,M:0.7):3);'))\n t2 = TreeNode.read(StringIO(u'(((H:1,G:1,O:1):2,R:3):1,X:4);'))\n obs = t.compare_tip_distances(t2, sample=3, shuffle_f=sorted)\n # note: common taxa are H, G, R (only)\n m1 = np.array([[0, 2, 6.5], [2, 0, 6.5], [6.5, 6.5, 0]])\n m2 = np.array([[0, 2, 6], [2, 0, 6], [6, 6, 0]])\n r = pearsonr(m1.flat, m2.flat)[0]\n self.assertAlmostEqual(obs, (1 - r) / 2)\n\n # 4 common taxa, still picking H, G, R\n s = u'((H:1,G:1):2,(R:0.5,M:0.7,Q:5):3);'\n t = TreeNode.read(StringIO(s))\n s3 = u'(((H:1,G:1,O:1):2,R:3,Q:10):1,X:4);'\n t3 = TreeNode.read(StringIO(s3))\n obs = t.compare_tip_distances(t3, sample=3, shuffle_f=sorted)\n\n def test_compare_tip_distances_no_common_tips(self):\n t = TreeNode.read(StringIO(u'((H:1,G:1):2,(R:0.5,M:0.7):3);'))\n t2 = TreeNode.read(StringIO(u'(((Z:1,Y:1,X:1):2,W:3):1,V:4);'))\n\n with self.assertRaises(ValueError):\n t.compare_tip_distances(t2)\n\n def test_compare_tip_distances_single_common_tip(self):\n t = TreeNode.read(StringIO(u'((H:1,G:1):2,(R:0.5,M:0.7):3);'))\n t2 = TreeNode.read(StringIO(u'(((R:1,Y:1,X:1):2,W:3):1,V:4);'))\n\n self.assertEqual(t.compare_tip_distances(t2), 1)\n self.assertEqual(t2.compare_tip_distances(t), 1)\n\n def test_tip_tip_distances_endpoints(self):\n \"\"\"Test getting specifc tip distances with tipToTipDistances\"\"\"\n t = TreeNode.read(StringIO(u'((H:1,G:1):2,(R:0.5,M:0.7):3);'))\n nodes = [t.find('H'), t.find('G'), t.find('M')]\n names = ['H', 'G', 'M']\n exp = DistanceMatrix(np.array([[0, 2.0, 6.7],\n [2.0, 0, 6.7],\n [6.7, 6.7, 0.0]]), ['H', 'G', 'M'])\n\n obs = t.tip_tip_distances(endpoints=names)\n self.assertEqual(obs, exp)\n\n obs = t.tip_tip_distances(endpoints=nodes)\n self.assertEqual(obs, exp)\n\n def test_tip_tip_distances_non_tip_endpoints(self):\n t = TreeNode.read(StringIO(u'((H:1,G:1)foo:2,(R:0.5,M:0.7):3);'))\n with self.assertRaises(ValueError):\n t.tip_tip_distances(endpoints=['foo'])\n\n def test_tip_tip_distances_no_length(self):\n t = TreeNode.read(StringIO(u\"((a,b)c,(d,e)f);\"))\n exp_t = TreeNode.read(StringIO(u\"((a:0,b:0)c:0,(d:0,e:0)f:0);\"))\n exp_t_dm = exp_t.tip_tip_distances()\n\n t_dm = npt.assert_warns(RepresentationWarning, t.tip_tip_distances)\n self.assertEqual(t_dm, exp_t_dm)\n\n for node in t.preorder():\n self.assertIs(node.length, None)\n\n def test_tip_tip_distances_missing_length(self):\n t = TreeNode.read(StringIO(u\"((a,b:6)c:4,(d,e:0)f);\"))\n exp_t = TreeNode.read(StringIO(u\"((a:0,b:6)c:4,(d:0,e:0)f:0);\"))\n exp_t_dm = exp_t.tip_tip_distances()\n\n t_dm = npt.assert_warns(RepresentationWarning, t.tip_tip_distances)\n self.assertEqual(t_dm, exp_t_dm)\n\n def test_neighbors(self):\n \"\"\"Get neighbors of a node\"\"\"\n t = TreeNode.read(StringIO(u\"((a,b)c,(d,e)f);\"))\n exp = t.children\n obs = t.neighbors()\n self.assertEqual(obs, exp)\n\n exp = t.children[0].children + [t]\n obs = t.children[0].neighbors()\n self.assertEqual(obs, exp)\n\n exp = [t.children[0].children[0]] + [t]\n obs = t.children[0].neighbors(ignore=t.children[0].children[1])\n self.assertEqual(obs, exp)\n\n exp = [t.children[0]]\n obs = t.children[0].children[0].neighbors()\n self.assertEqual(obs, exp)\n\n def test_has_children(self):\n \"\"\"Test if has children\"\"\"\n t = TreeNode.read(StringIO(u\"((a,b)c,(d,e)f);\"))\n self.assertTrue(t.has_children())\n self.assertTrue(t.children[0].has_children())\n self.assertTrue(t.children[1].has_children())\n self.assertFalse(t.children[0].children[0].has_children())\n self.assertFalse(t.children[0].children[1].has_children())\n self.assertFalse(t.children[1].children[0].has_children())\n self.assertFalse(t.children[1].children[1].has_children())\n\n def test_tips(self):\n \"\"\"Tip traversal of tree\"\"\"\n exp = ['a', 'b', 'c', 'd']\n obs = [n.name for n in self.simple_t.tips()]\n self.assertEqual(obs, exp)\n obs2 = [n.name for n in self.simple_t.traverse(False, False)]\n self.assertEqual(obs2, exp)\n\n def test_pre_and_postorder(self):\n \"\"\"Pre and post order traversal of the tree\"\"\"\n exp = ['root', 'i1', 'a', 'b', 'i1', 'i2', 'c', 'd', 'i2', 'root']\n obs = [n.name for n in self.simple_t.pre_and_postorder()]\n self.assertEqual(obs, exp)\n obs2 = [n.name for n in self.simple_t.traverse(True, True)]\n self.assertEqual(obs2, exp)\n\n def test_pre_and_postorder_no_children(self):\n t = TreeNode('brofist')\n\n # include self\n exp = ['brofist']\n obs = [n.name for n in t.pre_and_postorder()]\n self.assertEqual(obs, exp)\n\n # do not include self\n obs = list(t.pre_and_postorder(include_self=False))\n self.assertEqual(obs, [])\n\n def test_levelorder(self):\n \"\"\"Test level order traversal of the tree\"\"\"\n exp = ['root', 'i1', 'i2', 'a', 'b', 'c', 'd']\n obs = [n.name for n in self.simple_t.levelorder()]\n self.assertEqual(obs, exp)\n\n def test_index_tree_single_node(self):\n \"\"\"index_tree handles single node tree\"\"\"\n t1 = TreeNode.read(StringIO(u'root;'))\n id_index, child_index = t1.index_tree()\n self.assertEqual(id_index[0], t1)\n npt.assert_equal(child_index, np.array([[]]))\n\n def test_index_tree(self):\n \"\"\"index_tree should produce correct index and node map\"\"\"\n # test for first tree: contains singleton outgroup\n t1 = TreeNode.read(StringIO(u'(((a,b),c),(d,e));'))\n t2 = TreeNode.read(StringIO(u'(((a,b),(c,d)),(e,f));'))\n t3 = TreeNode.read(StringIO(u'(((a,b,c),(d)),(e,f));'))\n\n id_1, child_1 = t1.index_tree()\n nodes_1 = [n.id for n in t1.traverse(self_before=False,\n self_after=True)]\n self.assertEqual(nodes_1, [0, 1, 2, 3, 6, 4, 5, 7, 8])\n npt.assert_equal(child_1, np.array([[2, 0, 1], [6, 2, 3], [7, 4, 5],\n [8, 6, 7]]))\n\n # test for second tree: strictly bifurcating\n id_2, child_2 = t2.index_tree()\n nodes_2 = [n.id for n in t2.traverse(self_before=False,\n self_after=True)]\n self.assertEqual(nodes_2, [0, 1, 4, 2, 3, 5, 8, 6, 7, 9, 10])\n npt.assert_equal(child_2, np.array([[4, 0, 1], [5, 2, 3],\n [8, 4, 5], [9, 6, 7],\n [10, 8, 9]]))\n\n # test for third tree: contains trifurcation and single-child parent\n id_3, child_3 = t3.index_tree()\n nodes_3 = [n.id for n in t3.traverse(self_before=False,\n self_after=True)]\n self.assertEqual(nodes_3, [0, 1, 2, 4, 3, 5, 8, 6, 7, 9, 10])\n npt.assert_equal(child_3, np.array([[4, 0, 2], [5, 3, 3], [8, 4, 5],\n [9, 6, 7], [10, 8, 9]]))\n\n def test_root_at(self):\n \"\"\"Form a new root\"\"\"\n t = TreeNode.read(StringIO(u\"(((a,b)c,(d,e)f)g,h)i;\"))\n with self.assertRaises(TreeError):\n t.root_at(t.find('h'))\n\n exp = \"(a,b,((d,e)f,(h)g)c)root;\\n\"\n rooted = t.root_at('c')\n obs = str(rooted)\n self.assertEqual(obs, exp)\n\n def test_root_at_midpoint(self):\n \"\"\"Root at the midpoint\"\"\"\n tree1 = self.TreeRoot\n for n in tree1.traverse():\n n.length = 1\n\n result = tree1.root_at_midpoint()\n self.assertEqual(result.distance(result.find('e')), 1.5)\n self.assertEqual(result.distance(result.find('g')), 2.5)\n exp_dist = tree1.tip_tip_distances()\n obs_dist = result.tip_tip_distances()\n self.assertEqual(obs_dist, exp_dist)\n\n def test_root_at_midpoint_no_lengths(self):\n # should get same tree back (a copy)\n nwk = u'(a,b)c;\\n'\n t = TreeNode.read(StringIO(nwk))\n obs = t.root_at_midpoint()\n self.assertEqual(str(obs), nwk)\n\n def test_root_at_midpoint_tie(self):\n nwk = u\"(((a:1,b:1)c:2,(d:3,e:4)f:5),g:1)root;\"\n t = TreeNode.read(StringIO(nwk))\n exp = u\"((d:3,e:4)f:2,((a:1,b:1)c:2,(g:1)):3)root;\"\n texp = TreeNode.read(StringIO(exp))\n\n obs = t.root_at_midpoint()\n\n for o, e in zip(obs.traverse(), texp.traverse()):\n self.assertEqual(o.name, e.name)\n self.assertEqual(o.length, e.length)\n\n def test_compare_subsets(self):\n \"\"\"compare_subsets should return the fraction of shared subsets\"\"\"\n t = TreeNode.read(StringIO(u'((H,G),(R,M));'))\n t2 = TreeNode.read(StringIO(u'(((H,G),R),M);'))\n t4 = TreeNode.read(StringIO(u'(((H,G),(O,R)),X);'))\n\n result = t.compare_subsets(t)\n self.assertEqual(result, 0)\n\n result = t2.compare_subsets(t2)\n self.assertEqual(result, 0)\n\n result = t.compare_subsets(t2)\n self.assertEqual(result, 0.5)\n\n result = t.compare_subsets(t4)\n self.assertEqual(result, 1 - 2. / 5)\n\n result = t.compare_subsets(t4, exclude_absent_taxa=True)\n self.assertEqual(result, 1 - 2. / 3)\n\n result = t.compare_subsets(self.TreeRoot, exclude_absent_taxa=True)\n self.assertEqual(result, 1)\n\n result = t.compare_subsets(self.TreeRoot)\n self.assertEqual(result, 1)\n\n def test_compare_rfd(self):\n \"\"\"compare_rfd should return the Robinson Foulds distance\"\"\"\n t = TreeNode.read(StringIO(u'((H,G),(R,M));'))\n t2 = TreeNode.read(StringIO(u'(((H,G),R),M);'))\n t4 = TreeNode.read(StringIO(u'(((H,G),(O,R)),X);'))\n\n obs = t.compare_rfd(t2)\n exp = 2.0\n self.assertEqual(obs, exp)\n\n self.assertEqual(t.compare_rfd(t2), t2.compare_rfd(t))\n\n obs = t.compare_rfd(t2, proportion=True)\n exp = 0.5\n self.assertEqual(obs, exp)\n\n with self.assertRaises(ValueError):\n t.compare_rfd(t4)\n\n def test_assign_ids(self):\n \"\"\"Assign IDs to the tree\"\"\"\n t1 = TreeNode.read(StringIO(u\"(((a,b),c),(e,f),(g));\"))\n t2 = TreeNode.read(StringIO(u\"(((a,b),c),(e,f),(g));\"))\n t3 = TreeNode.read(StringIO(u\"((g),(e,f),(c,(a,b)));\"))\n t1_copy = t1.copy()\n\n t1.assign_ids()\n t2.assign_ids()\n t3.assign_ids()\n t1_copy.assign_ids()\n\n self.assertEqual([(n.name, n.id) for n in t1.traverse()],\n [(n.name, n.id) for n in t2.traverse()])\n self.assertEqual([(n.name, n.id) for n in t1.traverse()],\n [(n.name, n.id) for n in t1_copy.traverse()])\n self.assertNotEqual([(n.name, n.id) for n in t1.traverse()],\n [(n.name, n.id) for n in t3.traverse()])\n\n def test_assign_ids_index_tree(self):\n \"\"\"assign_ids and index_tree should assign the same IDs\"\"\"\n t1 = TreeNode.read(StringIO(u'(((a,b),c),(d,e));'))\n t2 = TreeNode.read(StringIO(u'(((a,b),(c,d)),(e,f));'))\n t3 = TreeNode.read(StringIO(u'(((a,b,c),(d)),(e,f));'))\n t1_copy = t1.copy()\n t2_copy = t2.copy()\n t3_copy = t3.copy()\n\n t1.assign_ids()\n t1_copy.index_tree()\n t2.assign_ids()\n t2_copy.index_tree()\n t3.assign_ids()\n t3_copy.index_tree()\n\n self.assertEqual([n.id for n in t1.traverse()],\n [n.id for n in t1_copy.traverse()])\n self.assertEqual([n.id for n in t2.traverse()],\n [n.id for n in t2_copy.traverse()])\n self.assertEqual([n.id for n in t3.traverse()],\n [n.id for n in t3_copy.traverse()])\n\n def test_unrooted_deepcopy(self):\n \"\"\"Do an unrooted_copy\"\"\"\n t = TreeNode.read(StringIO(u\"((a,(b,c)d)e,(f,g)h)i;\"))\n exp = \"(b,c,(a,((f,g)h)e)d)root;\\n\"\n obs = t.find('d').unrooted_deepcopy()\n self.assertEqual(str(obs), exp)\n\n t_ids = {id(n) for n in t.traverse()}\n obs_ids = {id(n) for n in obs.traverse()}\n\n self.assertEqual(t_ids.intersection(obs_ids), set())\n\n def test_descending_branch_length(self):\n \"\"\"Calculate descending branch_length\"\"\"\n tr = TreeNode.read(StringIO(u\"(((A:.1,B:1.2)C:.6,(D:.9,E:.6)F:.9)G:2.4\"\n \",(H:.4,I:.5)J:1.3)K;\"))\n tdbl = tr.descending_branch_length()\n sdbl = tr.descending_branch_length(['A', 'E'])\n npt.assert_almost_equal(tdbl, 8.9)\n npt.assert_almost_equal(sdbl, 2.2)\n self.assertRaises(ValueError, tr.descending_branch_length,\n ['A', 'DNE'])\n self.assertRaises(ValueError, tr.descending_branch_length, ['A', 'C'])\n\n tr = TreeNode.read(StringIO(u\"(((A,B:1.2)C:.6,(D:.9,E:.6)F:.9)G:2.4,(H\"\n \":.4,I:.5)J:1.3)K;\"))\n tdbl = tr.descending_branch_length()\n npt.assert_almost_equal(tdbl, 8.8)\n\n tr = TreeNode.read(StringIO(u\"(((A,B:1.2)C:.6,(D:.9,E:.6)F)G:2.4,(H:.4\"\n \",I:.5)J:1.3)K;\"))\n tdbl = tr.descending_branch_length()\n npt.assert_almost_equal(tdbl, 7.9)\n\n tr = TreeNode.read(StringIO(u\"(((A,B:1.2)C:.6,(D:.9,E:.6)F)G:2.4,(H:.4\"\n \",I:.5)J:1.3)K;\"))\n tdbl = tr.descending_branch_length(['A', 'D', 'E'])\n npt.assert_almost_equal(tdbl, 2.1)\n\n tr = TreeNode.read(StringIO(u\"(((A,B:1.2)C:.6,(D:.9,E:.6)F:.9)G:2.4,(H\"\n \":.4,I:.5)J:1.3)K;\"))\n tdbl = tr.descending_branch_length(['I', 'D', 'E'])\n npt.assert_almost_equal(tdbl, 6.6)\n\n # test with a situation where we have unnamed internal nodes\n tr = TreeNode.read(StringIO(u\"(((A,B:1.2):.6,(D:.9,E:.6)F):2.4,(H:.4,I\"\n \":.5)J:1.3);\"))\n tdbl = tr.descending_branch_length()\n npt.assert_almost_equal(tdbl, 7.9)\n\n def test_to_array(self):\n \"\"\"Convert a tree to arrays\"\"\"\n t = TreeNode.read(StringIO(\n u'(((a:1,b:2,c:3)x:4,(d:5)y:6)z:7,(e:8,f:9)z:10);'))\n id_index, child_index = t.index_tree()\n arrayed = t.to_array()\n\n self.assertEqual(id_index, arrayed['id_index'])\n npt.assert_equal(child_index, arrayed['child_index'])\n\n exp = np.array([1, 2, 3, 5, 4, 6, 8, 9, 7, 10, np.nan])\n obs = arrayed['length']\n npt.assert_equal(obs, exp)\n\n exp = np.array(['a', 'b', 'c', 'd', 'x',\n 'y', 'e', 'f', 'z', 'z', None])\n obs = arrayed['name']\n npt.assert_equal(obs, exp)\n\n exp = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n obs = arrayed['id']\n npt.assert_equal(obs, exp)\n\n def test_to_array_attrs(self):\n t = TreeNode.read(StringIO(\n u'(((a:1,b:2,c:3)x:4,(d:5)y:6)z:7,(e:8,f:9)z:10);'))\n id_index, child_index = t.index_tree()\n arrayed = t.to_array(attrs=[('name', object)])\n\n # should only have id_index, child_index, and name since we specified\n # attrs\n self.assertEqual(len(arrayed), 3)\n\n self.assertEqual(id_index, arrayed['id_index'])\n npt.assert_equal(child_index, arrayed['child_index'])\n\n exp = np.array(['a', 'b', 'c', 'd', 'x',\n 'y', 'e', 'f', 'z', 'z', None])\n obs = arrayed['name']\n npt.assert_equal(obs, exp)\n\n # invalid attrs\n with self.assertRaises(AttributeError):\n t.to_array(attrs=[('name', object), ('brofist', int)])\n\n def test_to_array_nan_length_value(self):\n t = TreeNode.read(StringIO(u\"((a:1, b:2)c:3)root;\"))\n indexed = t.to_array(nan_length_value=None)\n npt.assert_equal(indexed['length'],\n np.array([1, 2, 3, np.nan], dtype=float))\n indexed = t.to_array(nan_length_value=0.0)\n npt.assert_equal(indexed['length'],\n np.array([1, 2, 3, 0.0], dtype=float))\n indexed = t.to_array(nan_length_value=42.0)\n npt.assert_equal(indexed['length'],\n np.array([1, 2, 3, 42.0], dtype=float))\n\n t = TreeNode.read(StringIO(u\"((a:1, b:2)c:3)root:4;\"))\n indexed = t.to_array(nan_length_value=42.0)\n npt.assert_equal(indexed['length'],\n np.array([1, 2, 3, 4], dtype=float))\n\n t = TreeNode.read(StringIO(u\"((a:1, b:2)c)root;\"))\n indexed = t.to_array(nan_length_value=42.0)\n npt.assert_equal(indexed['length'],\n np.array([1, 2, 42.0, 42.0], dtype=float))\n\n def test_from_taxonomy(self):\n input_lineages = {'1': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],\n '2': ['a', 'b', 'c', None, None, 'x', 'y'],\n '3': ['h', 'i', 'j', 'k', 'l', 'm', 'n'],\n '4': ['h', 'i', 'j', 'k', 'l', 'm', 'q'],\n '5': ['h', 'i', 'j', 'k', 'l', 'm', 'n']}\n exp = TreeNode.read(StringIO(u\"((((((((1)g)f)e)d,((((2)y)x)))c)b)a,\"\n \"(((((((3,5)n,(4)q)m)l)k)j)i)h);\"))\n\n root = TreeNode.from_taxonomy(input_lineages.items())\n\n self.assertEqual(root.compare_subsets(exp), 0.0)\n\n def test_to_taxonomy(self):\n input_lineages = {'1': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],\n '2': ['a', 'b', 'c', None, None, 'x', 'y'],\n '3': ['h', 'i', 'j', 'k', 'l', 'm', 'n'],\n '4': ['h', 'i', 'j', 'k', 'l', 'm', 'q'],\n '5': ['h', 'i', 'j', 'k', 'l', 'm', 'n']}\n tree = TreeNode.from_taxonomy(input_lineages.items())\n exp = sorted(input_lineages.items())\n obs = [(n.name, lin) for n, lin in tree.to_taxonomy(allow_empty=True)]\n self.assertEqual(sorted(obs), exp)\n\n def test_to_taxonomy_filter(self):\n input_lineages = {'1': ['a', 'b', 'c', 'd', 'e', 'f', 'g'],\n '2': ['a', 'b', 'c', None, None, 'x', 'y'],\n '3': ['h', 'i', 'j', 'k', 'l'], # test jagged\n '4': ['h', 'i', 'j', 'k', 'l', 'm', 'q'],\n '5': ['h', 'i', 'j', 'k', 'l', 'm', 'n']}\n tree = TreeNode.from_taxonomy(input_lineages.items())\n\n def f(node, lin):\n return 'k' in lin or 'x' in lin\n\n exp = [('2', ['a', 'b', 'c', 'x', 'y']),\n ('3', ['h', 'i', 'j', 'k', 'l']),\n ('4', ['h', 'i', 'j', 'k', 'l', 'm', 'q']),\n ('5', ['h', 'i', 'j', 'k', 'l', 'm', 'n'])]\n obs = [(n.name, lin) for n, lin in tree.to_taxonomy(filter_f=f)]\n self.assertEqual(sorted(obs), exp)\n\n def test_linkage_matrix(self):\n # Ensure matches: http://www.southampton.ac.uk/~re1u06/teaching/upgma/\n id_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\n linkage = np.asarray([[1.0, 5.0, 1.0, 2.0],\n [0.0, 3.0, 8.0, 2.0],\n [6.0, 7.0, 12.5, 3.0],\n [8.0, 9.0, 16.5, 5.0],\n [2.0, 10.0, 29.0, 6.0],\n [4.0, 11.0, 34.0, 7.0]])\n\n tree = TreeNode.from_linkage_matrix(linkage, id_list)\n self.assertEqual(\"(E:17.0,(C:14.5,((A:4.0,D:4.0):4.25,(G:6.25,(B:0.5,\"\n \"F:0.5):5.75):2.0):6.25):2.5);\\n\",\n str(tree))\n\n def test_shuffle_invalid_iter(self):\n shuffler = self.simple_t.shuffle(n=-1)\n with self.assertRaises(ValueError):\n next(shuffler)\n\n def test_shuffle_n_2(self):\n exp = [\"((a,b)i1,(d,c)i2)root;\\n\",\n \"((a,b)i1,(c,d)i2)root;\\n\",\n \"((a,b)i1,(d,c)i2)root;\\n\",\n \"((a,b)i1,(c,d)i2)root;\\n\",\n \"((a,b)i1,(d,c)i2)root;\\n\"]\n\n obs_g = self.simple_t.shuffle(k=2, shuffle_f=self.rev_f, n=np.inf)\n obs = [str(next(obs_g)) for i in range(5)]\n self.assertEqual(obs, exp)\n\n def test_shuffle_n_none(self):\n exp = [\"((d,c)i1,(b,a)i2)root;\\n\",\n \"((a,b)i1,(c,d)i2)root;\\n\",\n \"((d,c)i1,(b,a)i2)root;\\n\",\n \"((a,b)i1,(c,d)i2)root;\\n\"]\n obs_g = self.simple_t.shuffle(shuffle_f=self.rev_f, n=4)\n obs = [str(next(obs_g)) for i in range(4)]\n self.assertEqual(obs, exp)\n\n def test_shuffle_complex(self):\n exp = [\"(((a,b)int1,(x,y,(w,z)int2,(f,e)int3)int4),(d,c)int5);\\n\",\n \"(((a,b)int1,(x,y,(w,z)int2,(c,d)int3)int4),(e,f)int5);\\n\",\n \"(((a,b)int1,(x,y,(w,z)int2,(f,e)int3)int4),(d,c)int5);\\n\",\n \"(((a,b)int1,(x,y,(w,z)int2,(c,d)int3)int4),(e,f)int5);\\n\"]\n\n obs_g = self.complex_tree.shuffle(shuffle_f=self.rev_f,\n names=['c', 'd', 'e', 'f'], n=4)\n obs = [str(next(obs_g)) for i in range(4)]\n self.assertEqual(obs, exp)\n\n def test_shuffle_names(self):\n exp = [\"((c,a)i1,(b,d)i2)root;\\n\",\n \"((b,c)i1,(a,d)i2)root;\\n\",\n \"((a,b)i1,(c,d)i2)root;\\n\",\n \"((c,a)i1,(b,d)i2)root;\\n\"]\n\n obs_g = self.simple_t.shuffle(names=['a', 'b', 'c'],\n shuffle_f=self.rotate_f, n=np.inf)\n obs = [str(next(obs_g)) for i in range(4)]\n self.assertEqual(obs, exp)\n\n def test_shuffle_raises(self):\n with self.assertRaises(ValueError):\n next(self.simple_t.shuffle(k=1))\n\n with self.assertRaises(ValueError):\n next(self.simple_t.shuffle(k=5, names=['a', 'b']))\n\n with self.assertRaises(MissingNodeError):\n next(self.simple_t.shuffle(names=['x', 'y']))\n\n\nsample = \"\"\"\n(\n(\nxyz:0.28124,\n(\ndef:0.24498,\nmno:0.03627)\n:0.17710)\n:0.04870,\n\nabc:0.05925,\n(\nghi:0.06914,\njkl:0.13776)\n:0.09853);\n\"\"\"\n\nnode_data_sample = \"\"\"\n(\n(\nxyz:0.28124,\n(\ndef:0.24498,\nmno:0.03627)\n'A':0.17710)\nB:0.04870,\n\nabc:0.05925,\n(\nghi:0.06914,\njkl:0.13776)\nC:0.09853);\n\"\"\"\n\nminimal = \"();\"\nno_names = \"((,),(,));\"\nmissing_tip_name = \"((a,b),(c,));\"\n\nempty = '();'\nsingle = '(abc:3);'\ndouble = '(abc:3, def:4);'\nonenest = '(abc:3, (def:4, ghi:5):6 );'\nnodedata = '(abc:3, (def:4, ghi:5)jkl:6 );'\n\nexp_ascii_art_three_children = \"\"\"\\\n /-a\n |\n---------| /-b\n | |\n \\--------|--c\n |\n \\-d\\\n\"\"\"\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"toxic_docs_insight/flask/app/venv/lib/python2.7/site-packages/skbio/tree/tests/test_tree.py","file_name":"test_tree.py","file_ext":"py","file_size_in_byte":48783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"549693756","text":"#!/usr/bin/env python\n# coding: utf-8\n\nREAL_DB_PATH = ('/m100_work/INF21_fldturb_0/velocities.npy')\nCOMPONENTS = slice(0,3)\nDB_NAME = \"tracers\"\nWGAN_TYPE = \"wgangp3\"\n\nSIG_LEN = 2000\nCHANNELS = 3\nNOISE_DIM = 100\n\nDB_MAX = 10.314160931635518\nDB_MIN = -11.244815117091042\n\n# Activate to smoothen training dataset\nSMOOTH_REAL_DB = False\nif SMOOTH_REAL_DB:\n sigma_smooth_real=2\n trunc_smooth_real=5\n","sub_path":"params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"112986551","text":"import mysql.connector\r\n\r\ncnx = mysql.connector.connect(user='root', database='perbankan')\r\ncursor = cnx.cursor()\r\ncursor.execute(\"\"\"SELECT * FROM nasabah\r\n WHERE nasabah.id_nasabah IN(select transaksi.id_nasabahFK\r\n FROM transaksi where tanggal between '2009-11-10' AND '2009-12-06')\"\"\")\r\nnasabah = cursor.fetchall()\r\nfor x in nasabah:\r\n print(x)\r\n\r\ncursor.close()\r\ncnx.close()\r\n","sub_path":"MODUL_11/nasabah.py","file_name":"nasabah.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"612574748","text":"USERNAME = \"joex1011\"\r\nINVENTORY_CSV = \"inventory.csv\"\r\nFREQUENCY_LIST = False\r\n# CEDH_BOX = ('Gitrog Dredge', 'Urza Tyrant', 'Edric Turns', 'Varolz Hulk', 'Urza Scepter', 'Jace High Tide')\r\nCEDH_BOX = ('Gitrog Dredge proxy', 'Urza Tyrant proxy', 'Edric Turns proxy', 'Varolz Hulk proxy', 'Urza Scepter proxy', 'Jace High Tide proxy', 'Consultation Kess proxy', 'Curious Control proxy', 'Sacred Hulk proxy')\r\nCHROMIUM_PROJECT = [\"Dralnu Consultation\",\r\n \"Feather Voltron\",\r\n \"Grenzo Doomsday\",\r\n \"Hapatra Poisonball\",\r\n \"Momir Hackball\",\r\n \"Niv Curiosity\",\r\n \"Radha Combats\",\r\n \"Selvala Elfball\",\r\n \"Teysa Persist\",\r\n \"Alesha Aristocrats\",\r\n \"Alta Entity\",\r\n \"Derevi Freed\",\r\n \"Ghave Altar\", \r\n \"Intet Sense\", \r\n \"Kess Consultation\",\r\n \"Kykar Divergent\",\r\n \"Tasigur Hulk\",\r\n \"Brago Blink\", \r\n \"Vaevictus Reanimator\",\r\n \"Zur Breakfast\"]\r\nPERMANENT_DECKS = ['Modern Storm', 'Pauper Cube'] + \\\r\n [\"Naban Iteration\", \"Yuriko\"] + \\\r\n [\"Goreclaw\", \"Yawgmoth Bargain\"] + \\\r\n [CEDH_BOX] + ['Judge Tower'] # + CHROMIUM_PROJECT\r\nFLUID_DECKS = []\r\nINVENTORY = \"inventory.txt\"\r\nPURCHASED = \"purchased_temp.txt\"\r\nCARDS_TO_REMOVE = \"cards_to_remove.txt\"\r\nINVENTORY_TXT = 'inventory.txt'\r\nPARTITION_DECKS = CEDH_BOX\r\nCURRENT_DECK = \"Sacred Hulk proxy\"\r\nPARTITION_FILE = 'partition.txt'\r\nPARTITION_THRESHOLD = 5\r\nSCRYFALL_DEFAULT = \"scryfall-default-cards.json\"\r\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"273731874","text":"class Stack:\n def __init__(self, size):\n \"\"\"self.top points to the most recently inserted element\"\"\"\n self.size = size\n self.stack = [None]*size\n self.top = -1\n\n def push(self, x):\n if self.top > self.size-1:\n return 'Overflow'\n self.top = self.top + 1\n self.stack[self.top] = x\n\n def pop(self):\n if self.is_empty():\n return 'Underflow'\n else:\n self.top = self.top - 1\n return self.stack[self.top+1]\n\n def is_empty(self):\n if self.top < 0:\n return True\n return False\n\n def __len__(self):\n return self.top\n\n\nif __name__ == \"__main__\":\n stack = Stack(size=3)\n print(stack.is_empty())\n stack.push(15)\n stack.push('string')\n print(stack.pop())\n stack.push(0.999)\n print(stack.pop())\n print(stack.pop())\n print(stack.pop())\n print(stack.is_empty())\n","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"233946597","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n############################################\n#\n# PyGdalSAR: An InSAR post-processing package \n# written in Python-Gdal\n#\n############################################\n# Author : Mathieu Volat \n############################################\n\n\"\"\"\\\nplot\\_image.py\n-------------\nDisplay and Cut image file \n\nUsage: plot\\_image.py --infile= [] [] [] []\nOptions:\n-h --help Show this screen.\n--infile PATH File to be cut\n--ibeg VALUE Ligne numbers bounded the cutting zone [default: 0]\n--iend VALUE Ligne numbers bounded the cutting zone [default: nlign]\n--jbeg VALUE Column numbers bounded the cutting zone [default: 0]\n--jend VALUE Column numbers bounded the cutting zone [default: ncol]\n\"\"\"\n\nfrom __future__ import print_function\nimport os, sys\n\n# docopt (command line parser)\nfrom nsbas import docopt\n\nimport numpy as np\nfrom numpy.lib.stride_tricks import as_strided\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nfrom pylab import setp\nfrom osgeo import gdal\n\n# Initialize a matplotlib figure\nfig, ax = plt.subplots(1,figsize=(10,11))\n\n# read arguments\narguments = docopt.docopt(__doc__)\ninfile = arguments[\"--infile\"]\n# Open phiset (image)\nds = gdal.Open(infile, gdal.GA_ReadOnly)\n\n# Ok, assume this is a roipac image, so we can rely on the file extension\n# to know how to display the phi (in the real world, we would probably write\n# different programs)\nds_extension = os.path.splitext(sys.argv[1])[1]\n\n# Get the band that have the phi we want\nif ds_extension == \".unw\":\n phase_band = ds.GetRasterBand(2)\n amp_band = ds.GetRasterBand(1)\nelse:\n\tphase_band = ds.GetRasterBand(1)\n\n# Attributes\nprint(\"> Driver: \", ds.GetDriver().ShortName)\nprint(\"> Size: \", ds.RasterXSize,'x',ds.RasterYSize,'x',ds.RasterCount)\nprint(\"> Datatype: \", gdal.GetDataTypeName(phase_band.DataType))\n\nif arguments[\"\"] == None:\n ibeg = 0\nelse:\n ibeg = int(arguments[\"\"])\nif arguments[\"\"] == None:\n iend = ds.RasterYSize\nelse:\n iend = int(arguments[\"\"])\nif arguments[\"\"] == None:\n jbeg = 0\nelse:\n jbeg = int(arguments[\"\"])\nif arguments[\"\"] == None:\n jend = ds.RasterXSize\nelse:\n jend = int(arguments[\"\"])\n\n# Read phi in numpy array, resampled by a factor of 4\n# Resampling is nearest neighbour with that function: hardly acceptable,\n# but easy for a simple demo!\nif ds_extension == \".unw\":\n\tphi = phase_band.ReadAsArray(0, 0,\n ds.RasterXSize, ds.RasterYSize,\n ds.RasterXSize, ds.RasterYSize)\n\tamp = amp_band.ReadAsArray(0, 0,\n ds.RasterXSize, ds.RasterYSize,\n ds.RasterXSize, ds.RasterYSize)\n\t\n\t# cut image\n\tcutphi = as_strided(phi[ibeg:iend,jbeg:jend])\n\tcutamp = as_strided(amp[ibeg:iend,jbeg:jend])\n\nelse:\n\tphase = phase_band.ReadAsArray(0, 0,\n ds.RasterXSize, ds.RasterYSize,\n ds.RasterXSize, ds.RasterYSize)\n\t\n\tcutphase = as_strided(phase[ibeg:iend,jbeg:jend])\t\n\n#phi = np.nan_to_num(phi)\n#amp = np.nan_to_num(amp)\n#kk = np.flatnonzero(phi==0)\n#phi[kk] = np.float('NaN')\n\n\nif ds_extension == \".slc\":\n # SLC, display amplitude\n cutphi = np.absolute(phi)\n cax = ax.imshow(cutphi, cm.Greys_r, vmax=np.percentile(cutphi, 95))\nelif ds_extension in [\".int\", \".flat\"]:\n # Wrapped interferogram, display computed phase\n cutamp = np.absolute(cutphase)\n cutphi = np.angle(cutphase)\n # hax = ax.imshow(cutamp, cm.Greys_r,vmax=np.percentile(cutamp, 90))\n hax = ax.imshow(cutamp, cm.Greys,vmax=1,vmin=0.)\n # cax = ax.imshow(cutphi, cm.gist_rainbow, interpolation='bicubic',alpha=0.8)\n\nelif ds_extension == \".hgt\":\n # DEM in radar geometry\n cax = ax.imshow(cutphi, cm.Greys_r, vmax=np.percentile(cutphi, 95))\nelif ds_extension == \".unw\":\n # Unwrapped inteferogram\n # hax = ax.imshow(cutamp, cm.Greys,vmax=1,vmin=0.)\n #hax = ax.imshow(cutamp, cm.Greys,vmax=np.percentile(cutamp, 95))\n vmax=np.nanmean(cutphi)+2*np.nanstd(cutphi)\n vmin=np.nanmean(cutphi)-2*np.nanstd(cutphi)\n vmax=8\n vmin=-8\n cutwrap = np.mod(cutphi,2*np.pi)-np.pi\n cax = ax.imshow(cutphi, cm.gist_rainbow, interpolation='bicubic',vmax=vmax,vmin=vmin,alpha=0.5)\n # cax = ax.imshow(cutwrap, cm.gist_rainbow, interpolation='bicubic',alpha=0.7,vmax=np.pi,vmin=-np.pi)\nelif ds_extension == \".trans\":\n # Geocoding lookup table\n cax = ax.imshow(cutphi)\n\nsetp( ax.get_xticklabels(), visible=False)\ncbar = fig.colorbar(cax, orientation='vertical',aspect=9,fraction=0.02,pad=0.06)\n# cbar = fig.colorbar(hax, orientation='vertical',aspect=10,fraction=0.02,pad=0.01)\n\n# Close dataset (if this was a new image, it would be written at this moment)\n# This will free memory for the display stuff\ndel ds\n\n# Display the data\nfig.canvas.set_window_title(sys.argv[1])\n##ax.set_rasterized(True)\nfig.savefig('{}.eps'.format(infile), format='EPS',dpi=150)\nplt.show()\n","sub_path":"plots/plot_image.py","file_name":"plot_image.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"360533038","text":"import re\nimport requests\nfrom datetime import datetime\n\ndef parse_value(content, pattern):\n return float(re.match(pattern, content.strip()).group(1))\n\ndef print_data(water_temperature=0, air_temperature=0, moisture=0, ph=0):\n print(\",\".join(map(str, [datetime.now().strftime('%Y-%m-%d %H:%M:%S'), water_temperature, air_temperature, moisture, ph])))\n\ndef main():\n # get html\n html = requests.get('http://192.168.1.110').text\n\n # parse values\n parsed_values = { k: parse_value(html, pattern) for k, pattern in dict(\n water_temperature=\".*Water Temperature: (\\d*\\\\.\\d*).*\",\n air_temperature=\".*Air Temperature: (\\d*\\\\.\\d*)\",\n moisture=\".*Moisture: (\\d*)%\",\n ph=\".*pH: (\\d*\\\\.\\d*)\"\n ).items() }\n\n # insert data\n print_data(**parsed_values)\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"src/scrap_esp32-wroom-32.py","file_name":"scrap_esp32-wroom-32.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"559116678","text":"#!/usr/bin/env python3\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(5)\nfruit = np.random.randint(0, 20, (4, 3))\n\nfig, ax = plt.subplots()\n\ncolumns = ('Farrah', 'Fred', 'Felicia')\nrows = ('apples', 'bananas', 'oranges', 'peaches')\ncolors = ('r', 'y', '#ff8000', '#ffe5b4')\nindex = np.zeros(3)\nbar_width = 0.5\n\nfor i, n_fruits in enumerate(fruit):\n ax.bar(\n columns,\n n_fruits,\n bar_width,\n bottom=index,\n label=rows[i],\n color=colors[i]\n )\n index += n_fruits\nax.set_ylabel('Quantity of Fruit')\nax.set_ylim(0, 80)\nax.set_title('Number of Fruit per Person')\nax.legend()\n\nplt.show()\n","sub_path":"math/0x01-plotting/6-bars.py","file_name":"6-bars.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"201766279","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nimport subprocess\nimport time\n\nclass ScanSqlInjection:\n def __init__(self):\n self.sqlmap_script = \"\"\n current_path = os.path.dirname(os.path.realpath(__file__))\n self.sqlmap_folder = os.path.join(current_path, 'sqlmap_lib')\n self.sqlmap_script = os.path.join(self.sqlmap_folder, \"sqlmap.py\")\n self.sqlmap_output = os.path.join(current_path, \"output\")\n self.result = \"\"\n\n def sql_injection(self, method, url, parameter):\n self.scan_object(method, url, parameter)\n print(\"Finish Scan!\")\n\n def scan_object(self, method, url, parameter):\n time_start = time.time()\n full_link = url\n print(\"Start scan\", full_link)\n os.chdir(self.sqlmap_folder)\n full_param = \"\"\n list_param_get = \"\"\n for param, value in parameter.items():\n full_param += str(param) + \"=\" + str(value) + \"&\"\n list_param_get += str(param) + \",\"\n full_param = full_param[:-1]\n if full_param == \"\":\n full_url = full_link\n else:\n full_url = full_link + \"?\" + full_param\n if method == \"GET\":\n command = \"python2 {0} -u '{1}' --random-agent --level=3 --risk=2 --threads=3 \" \\\n \"--tamper=space2hash --batch --timeout=20 --retries=1\".format(self.sqlmap_script, full_url, self.sqlmap_output)\n else:\n command = \"python2 {0} -u '{1}' --method=POST --data='{2}' --random-agent --level=3 --risk=2 \" \\\n \"--threads=3 \" \\\n \"--tamper=space2hash --batch --timeout=20 --retries=1\".format(self.sqlmap_script, full_url,\n str(parameter), self.sqlmap_output)\n process = subprocess.Popen(command, shell=True, stdin=None, stdout=subprocess.PIPE, stderr=None, close_fds=True) # Start scan\n\n # wait_for_finish(full_link, process) # Wait finish and update result\n stdout, stderr = process.communicate()\n output = stdout.decode('utf-8')\n self.result = self.get_sqlmap_result(full_link, output)\n print(\"Check done in %2.2f s\" % (time.time() - time_start))\n\n @staticmethod\n def get_request_body(parameters):\n request_body = \"\"\n for parameter in parameters:\n for k, v in parameter.items():\n request_body = request_body + \", \" + str(k) + \"=\" + str(v)\n request_body = request_body[2:]\n return request_body\n\n @staticmethod\n def get_sqlmap_result(full_link, output): # Format output\n print(\"FINISH FULL LINK: \" + str(full_link))\n regex = re.compile(r'--SQL--([\\s\\S].*?)--SQL--', re.DOTALL)\n match = re.search(regex, output)\n if match:\n attack_detail = match.group(1)\n print(attack_detail)\n return attack_detail\n else:\n return \"\"\n\n def exploit(self, url):\n cmd = \"python2 {} -u '{}' --wizard\".format(self.sqlmap_script, url)\n os.system(cmd)\n\n","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"391852861","text":"import unittest\nimport unittest.mock as mock\nfrom unittest.mock import patch\nimport os\nimport sys\n\nsys.path.append(os.path.abspath('../'))\nfrom app import add_to_database\nimport models\n\nKEY_INPUT = 'input'\nKEY_EXPECTED = 'expected'\n\nINITIAL_USERNAME = 'bob'\n\n\nclass AddToDatabaseTestCase(unittest.TestCase):\n def setUp(self):\n self.success_test_params = [\n {\n KEY_INPUT: 'joe',\n KEY_EXPECTED: [INITIAL_USERNAME, 'joe'],\n },\n {\n KEY_INPUT: 'thomas wellington',\n KEY_EXPECTED: [INITIAL_USERNAME, 'joe', 'thomas wellington'],\n },\n ]\n self.failure_test_params = [\n {\n KEY_INPUT: ' ',\n KEY_EXPECTED: [INITIAL_USERNAME],\n },\n ]\n\n initial_gamer = models.Gamer(username=INITIAL_USERNAME, score=100)\n self.initial_DB_mock = [initial_gamer]\n\n def mocked_db_session_add(self, username):\n self.initial_DB_mock.append(username)\n\n def mocked_db_session_commit(self):\n pass\n\n def mocked_gamer_query_all(self):\n return self.initial_DB_mock\n\n def test_success(self):\n for test in self.success_test_params:\n with patch('app.DB.session.add', self.mocked_db_session_add):\n with patch('app.DB.session.commit',\n self.mocked_db_session_commit):\n with patch('models.Gamer.query') as mocked_query:\n mocked_query.all = self.mocked_gamer_query_all\n\n print(self.initial_DB_mock)\n actual_result = add_to_database(test[KEY_INPUT])\n print(actual_result)\n expected_result = test[KEY_EXPECTED]\n print(expected_result)\n print(self.initial_DB_mock)\n\n self.assertEqual(len(actual_result),\n len(expected_result))\n\n def test_failure(self):\n for test in self.failure_test_params:\n with patch('app.DB.session.add', self.mocked_db_session_add):\n with patch('app.DB.session.commit',\n self.mocked_db_session_commit):\n with patch('models.Gamer.query') as mocked_query:\n mocked_query.all = self.mocked_gamer_query_all\n\n print(self.initial_DB_mock)\n actual_result = add_to_database(test[KEY_INPUT])\n print(actual_result)\n expected_result = test[KEY_EXPECTED]\n print(expected_result)\n print(self.initial_DB_mock)\n\n self.assertNotEqual(len(actual_result),\n len(expected_result))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"add_to_database_test.py","file_name":"add_to_database_test.py","file_ext":"py","file_size_in_byte":2924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"527678013","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import division\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\n\n\ndensidad = 1/15\nLx = 10\nLy = 15\nh = 0.2\nN_pasos_x = int(Lx/h + 1)\nN_pasos_y = int(Ly/h + 1)\n\n\ndef muestra_phi(phi):\n print(phi[::-1, :])\n\n\ndef rho(i, j, h):\n\n x = i * h - (Lx / 2.)\n y = j * h - (Ly / 2.)\n\n if (x >= -2.5 and x <= 2.5) and (y >= 2.5 and y <= 3.5): # arriba C\n return densidad\n\n elif (x >= -2.5 and x <= 2.5) and (y >= -3.5 and y <= -2.5): # baja de C\n return densidad\n\n elif (x <= -1.5 and x >= -2.5) and (y >= -2.5 and y <= 2.5): # medio\n return densidad\n else:\n return 0\n\n\ndef una_iteracion(phi, phi_next, N_pasos_x, N_pasos_y, h=0.2, w=1.):\n\n ''' esta funcion lo que realiza es dividir la caja y calcular el potencial\n segun\n las condiciones dadas previamente\n\n condiciones cercano a la linea bajo la letra\n primero: calculamos el tramo bajo la linea la linea esta en -5.5\n que en nuestra grilla seria posicion 10 y sobre la linea, luego\n al lado de la linea y finalmente las condiciones derivativas o como se\n escriba jiji'''\n\n for i in range(1, N_pasos_x - 1):\n\n for j in range(1, 10): # recorremos bajo la linea\n phi_next[i, j] = ((1 - w) * phi[i, j] +\n w / 4 * (phi[i+1, j] + phi_next[i-1, j] +\n phi[i, j+1] + phi_next[i, j-1] +\n h**2 * rho(i, j, h)))\n\n for j in range(12, N_pasos_y-1): # recorremos sobre la linea\n phi_next[i, j] = ((1 - w) * phi[i, j] +\n w / 4 * (phi[i+1, j] + phi_next[i-1, j] +\n phi[i, j+1] + phi_next[i, j-1] +\n h**2 * rho(i, j, h)))\n\n '''alrededor de la linea costado izquiedo y costado derecho :C '''\n\n for j in range(10, 12):\n\n for i in range(1, 11): # izquierda\n phi_next[i, j] = ((1 - w) * phi[i, j] +\n w / 4 * (phi[i+1, j] + phi_next[i-1, j] +\n phi[i, j+1] + phi_next[i, j-1] +\n h**2 * rho(i, j, h)))\n for i in range(41, N_pasos_x-1):\n phi_next[i, j] = ((1 - w) * phi[i, j] +\n w / 4 * (phi[i+1, j] + phi_next[i-1, j] +\n phi[i, j+1] + phi_next[i, j-1] +\n h**2 * rho(i, j, h)))\n\n '''en la linea'''\n\n for i in range(10, 41):\n # deajo de la linea\n\n for j in range(10, 11):\n phi_next[i, j] = ((1 - w) * phi[i, j] +\n w / 3 * (phi[i+1, j] + phi_next[i-1, j] +\n phi_next[i, j-1] + h**2 * rho(i, j, h) +\n h*(-1.)))\n # sobre la linea\n for j in range(11, 12):\n phi_next[i, j] = ((1 - w) * phi[i, j] +\n w / 3 * (phi[i+1, j] + phi_next[i-1, j] +\n phi_next[i, j-1] + h**2 * rho(i, j, h) +\n h*(1.)))\n\n\ndef no_ha_convergido(phi, phi_next, tolerancia=1e-5):\n not_zero = (phi_next != 0)\n diff_relativa = (phi - phi_next)[not_zero] / phi_next[not_zero]\n max_diff = np.max(np.fabs(diff_relativa))\n if max_diff > tolerancia:\n return True\n else:\n return False\n\n\nw = 1.0\n# w=0.5 0.8 1.0, 1.2, 1.5\n\nphi = np.zeros((N_pasos_x, N_pasos_y))\nphi_next = np.zeros((N_pasos_x, N_pasos_y))\n\n# iteracion\nuna_iteracion(phi, phi_next, N_pasos_x, N_pasos_y, h, w)\ncounter = 1\n\nwhile counter < 15000 and no_ha_convergido(phi, phi_next, tolerancia=1e-5):\n phi = phi_next.copy()\n una_iteracion(phi, phi_next, N_pasos_x, N_pasos_y, h, w)\n counter += 1\n\nprint(\"counter = {}\".format(counter))\n\n\nphi_next_transpuesta = phi_next.transpose()\n\nfig = plt.figure(1)\nfig.clf()\nax = fig.add_subplot(111, projection='3d')\n\nx = np.linspace(-1, 1, N_pasos_x)\ny = np.linspace(-1, 1, N_pasos_y)\n\nX, Y = np.meshgrid(x, y)\n\nax.plot_surface(X, Y, phi_next_transpuesta, rstride=1, cstride=1)\nax.set_xlabel('$\\ x [cm]$', fontsize=15)\nax.set_ylabel('$\\ y [cm]$', fontsize=15)\nax.set_zlabel('$\\ Potencial [erg/C]$', fontsize=15)\nax.set_title('$\\ Potencial $')\nfig.show()\n\nfig2 = plt.figure(2)\nfig2.clf()\nax2 = fig2.add_subplot(111)\nax2.imshow(np.arcsinh(phi_next_transpuesta),\n origin='bottom', interpolation='nearest')\nax2.set_xlabel('$\\ x [cm]$', fontsize=15)\nax2.set_ylabel('$\\ y [cm]$', fontsize=15)\nax2.set_title('$\\ Potencial $')\n\nfig2.show()\n\nplt.draw()\n","sub_path":"tarea5.py","file_name":"tarea5.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"180114298","text":"from django.core.exceptions import ValidationError\r\nfrom django.utils.translation import gettext_lazy as _\r\nfrom student.libraries import *\r\n\r\ndef Phone_Number(value):\r\n\tif len(value)!= 10:\r\n\t\traise ValidationError(\r\n\t\t\t_('The Mobile Number is invalid'),\r\n\t\t\t)\r\n\r\n\r\ndef Image_Size(Input):\r\n\tImageSize = Input.file.size\r\n\tlimit_Kb_Min = 20\r\n\tlimit_Kb_Max = 300\r\n\tif ImageSize > limit_Kb_Max * 1024:\r\n\t\traise ValidationError(\r\n\t\t\t_('The maximum image size is 300 kb'))","sub_path":"validations.py","file_name":"validations.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"604594152","text":"import numpy as np\nimport sklearn\nfrom matplotlib.pyplot import savefig\n\n\ndef read_data(filename):\n from bokeh.models import pd\n df = pd.read_csv(\n filepath_or_buffer=filename,\n header=None,\n sep=',')\n data = np.array(df.ix[:, :].values)\n data = np.hstack([np.ones((data.shape[0], 1)), data])\n return data\n\ndef split_randomly(data):\n from math import floor\n import numpy as np\n\n np.random.shuffle(data)\n # test = data[:, :]\n test = data[floor(len(data)/2):,:]\n train = data[:floor(len(data)/2),:]\n # train = data[:, :]\n return test, train\n\n\ndef separate_labels_from_features(data):\n x = data[:, :-1].T # data matrix: features as lines, samples as columns\n y = data[:, -1] # labels row vector\n return x, y\n\n\ndef split_by_class(x, y):\n x_plus1_coordX1 = [x[1, i] for i in range(y.shape[0]) if y[i] == 1]\n x_plus1_coordX2 = [x[2, i] for i in range(y.shape[0]) if y[i] == 1]\n x_minus1_coordX1 = [x[1, i] for i in range(y.shape[0]) if y[i] == 0]\n x_minus1_coordX2 = [x[2, i] for i in range(y.shape[0]) if y[i] == 0]\n return x_plus1_coordX1, x_plus1_coordX2, x_minus1_coordX1, x_minus1_coordX2\n\n\n############################################################################################################\n\ndef sigmoid(x):\n '''\n :return: the value of the sigmoid function for the given x (aka the prob. to be a positive example)\n '''\n import numpy as np\n return 1.0 / (1.0 + np.exp(-x))\n\n\ndef compute_error(w, x, y):\n error = y.T * sigmoid(w.T * x).T + (1 - y.T) * (1 - sigmoid(w.T * x).T)\n return -error\n\n\ndef compute_log_likelihood(w, x, y): # the cost function\n # compute the probability for class 1\n prob_1 = sigmoid(np.dot(w.T, x))\n # compute the value of the log likelihood vector (aka cross entropy error)\n log_likelihood = (y) * np.log(prob_1) + (1 - y) * np.log(1 - prob_1)\n # this shows how likely is each data observation to appear - the log likelihood of the whole ds is the mean\n return -log_likelihood.sum()\n\n\ndef logistic_gradient(w, x, y):\n \"\"\"\n :param w: parameter vector\n :param x: data matrix\n :param y: label vector\n :return: a vector representing the gradient dL/dw\n \"\"\"\n gradi = -np.dot(y - sigmoid(np.dot(w.T, x)), x.T)\n return gradi[0].reshape(len(w), 1)\n\n\ndef numerical_gradient(w, x, y):\n \"\"\"\n :param w: parameter vector\n :param x: data matrix\n :param y: label vector\n :return: the gradient dL/dw computed using the central difference quotient\n \"\"\"\n eps = 1 / 1000\n\n grad_approx = np.zeros(w.shape)\n\n for i in range(len(w)):\n current_ei = np.zeros(w.size).reshape(w.size, 1)\n current_ei[i] = eps\n L_plus_eps = compute_log_likelihood(w + current_ei, x, y)\n L_minus_eps = compute_log_likelihood(w - current_ei, x, y)\n grad_approx[i] = (L_plus_eps - L_minus_eps) / (2 * eps)\n return grad_approx\n\n\ndef gradient_descent(learning_rate, w, x, y):\n iteration = 0\n epsilon = 0.01\n error = 0\n\n while True:\n # compute the gradients\n grad = logistic_gradient(w, x, y)\n w = w - learning_rate * grad\n prev_error = error\n error = np.sum(abs(y - sigmoid(np.dot(w.T, x))), axis=1)\n # print(\"Iteration {0}, error {1}, w = {2}\".format(iteration, error, w))\n if abs(error - prev_error) < epsilon or iteration > 500:\n break\n iteration += 1\n\n return w\n\n\n########################################################################################\n\ndef plot_points_and_separation_line(x, y, w, title):\n import matplotlib.pyplot as plt\n\n x_plus1_coordX1, x_plus1_coordX2, x_minus1_coordX1, x_minus1_coordX2 = split_by_class(x, y)\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(x_plus1_coordX1, x_plus1_coordX2, s=30, c='red', marker='s')\n ax.scatter(x_minus1_coordX1, x_minus1_coordX2, s=30, c='blue')\n\n plt.xlabel(\"X1 coord\")\n plt.ylabel(\"X2 coord\")\n plt.title(title)\n\n # plot separation line\n coord_x_line = np.linspace(-1, 1, 100)\n\n # the weights are the coordinates of the line\n # w0*x+w1*y+w2= 0\n # solve for y: => y = (-w2-wo*x)/w1\n coord_y_line = (-w[0] - w[1] * coord_x_line) / w[2]\n ax.plot(coord_x_line, coord_y_line.T, 'g')\n\n savefig(title+\".png\", bbox_inches='tight')\n # plt.show()\n\n\n###################################################################################\n\ndef compute_prediction(w, xtest):\n prediction_fract = sigmoid(np.dot(w.T, xtest))\n prediction_m11 = []\n for i in range(prediction_fract.shape[1]):\n if prediction_fract[0][i] > 0.5:\n prediction_m11.append(1)\n else:\n prediction_m11.append(0)\n return prediction_m11\n\n\ndef compute_classification_based_confusion_matrix(predictions, true_labels):\n true_positive = 0\n true_negative = 0\n false_positive = 0\n false_negative = 0\n for i in range(len(predictions)):\n if predictions[i] == true_labels[i]:\n if predictions[i] == 1:\n true_positive += 1\n else:\n true_negative += 1\n else:\n if predictions[i] == 1:\n false_positive += 1\n else:\n false_negative += 1\n return true_positive, true_negative, false_positive, false_negative\n\n\n# formulas from http://people.inf.ethz.ch/bkay/talks/Brodersen_2010_06_21.pdf\ndef compute_accuracy(tp, tn, n):\n return (tp + tn) / n\n\n\ndef compute_balanced_accuracy(tp, tn, fp, fn):\n return (1 / 2) * (tp / (tp + fn) + tn / (fp + tn))\n\n\n###################################################################################################\n\ndef plot_roc_curve(ytest, y_prediction_as_prob_of_being_1, filename):\n import matplotlib.pyplot as plt\n import sklearn.metrics\n # Plot of a ROC curve\n\n fpr, tpr, _ = sklearn.metrics.roc_curve(ytest, y_prediction_as_prob_of_being_1)\n roc_auc = roc_auc_score(ytest, y_prediction_as_prob_of_being_1)\n\n fig = plt.figure()\n plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.title('Receiver operating characteristic ' + str(filename))\n print(\"The ROC AUC for {0} is {1}.\".format(filename, roc_auc))\n plt.legend(loc=\"lower right\")\n txt = '''\n The ROC (receiver operating characteristic) curve provides a visualization of\n the performance of a binary classifier (like logistic regresion here). The AUC\n (area under curve) summarizes it in a single number. It plots the True positive\n rate against the False positive rate for every possible classification threshold.\n For example, a threshold of 0.2 would classify 30/100 points as 1 and 70/100 points as 0.\n '''\n # fig.text(.1, .1, txt)\n\n savefig(\"ROC-\"+str(filename)+\".png\", bbox_inches='tight')\n\n\ndef plot_precision_recall_curve(ytest, y_prediction_as_prob_of_being_1, filename):\n import matplotlib.pyplot as plt\n\n precision, recall, _ = sklearn.metrics.precision_recall_curve(ytest, y_prediction_as_prob_of_being_1)\n average_precision = sklearn.metrics.average_precision_score(ytest, y_prediction_as_prob_of_being_1)\n\n # Plot Precision-Recall curve\n plt.clf()\n plt.plot(recall, precision, label='Precision-Recall curve')\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.ylim([0.0, 1.05])\n plt.xlim([0.0, 1.0])\n plt.title('Precision-Recall curve' + str(filename) + \": AUC={0:0.2f}\".format(average_precision))\n print(\"The average precision (AUC) for {0} is {1}.\".format(filename,average_precision))\n plt.legend(loc=\"lower left\")\n # plt.show()\n savefig(\"Prec-Recall-\" + str(filename)+\".png\", bbox_inches='tight')\n\n\n##############################################################################\nif __name__ == \"__main__\":\n datasetnames = [\"DataSet3.csv\", \"DataSet4.csv\"]\n for filename in datasetnames:\n # read data and split it in train and test\n data = read_data(\"DataSet4.csv\")\n test, train = split_randomly(data)\n # extract the labels\n xtrain, ytrain = separate_labels_from_features(train)\n xtest, ytest = separate_labels_from_features(test)\n\n # initialize the weights vector with 1\n # each weight for a coefficient of the separation line: ax+by+c=0\n nr_weights = xtrain.shape[0]\n w = np.ones((nr_weights, 1))\n\n # perform gradient checking by computing the gradient and its numerical approximation\n # print(logistic_gradient(w, xtrain, ytrain))\n # print(numerical_gradient(w, xtrain, ytrain))\n\n # compute the final weights using gradient descent on the training set with a learning\n # rate of 0.01\n w = gradient_descent(0.01, w, xtrain, ytrain)\n\n # for visualization purposes\n plot_points_and_separation_line(xtrain, ytrain, w, \"Training set \" + str(filename))\n plot_points_and_separation_line(xtest, ytest, w, \"Testing set \" + str(filename))\n\n # compute the predictions on the test set\n predictions = compute_prediction(w, xtest)\n # compute true positive, true neg, false pos, false neg based on true labels and predictions\n tp, tn, fp, fn = compute_classification_based_confusion_matrix(predictions, ytest)\n\n # compute accuracy and balanced accuracy\n \"\"\"\n Given a confusion matrix of classification results, the\n accuracy can be a misleading performance measure. Specifically,\n it may falsely suggest above-chance generalizability.\n\n It is a well-known phenomenon in binary classification\n that a training set consisting of different numbers of representatives\n from either class may result in a classifier that\n is biased towards the more frequent class. When applied\n to a test set that is imbalanced in the same direction, this\n classifier may yield an optimistic accuracy estimate. In an\n extreme case, the classifier might assign every single test\n case to the large class, thereby achieving an accuracy equal\n to the fraction of the more frequent labels in the test set.\n\n This observation\n motivates the use of a different generalizability\n measure: the balanced accuracy, which can be defined as\n the average accuracy obtained on either class.\n (via http://ong-home.my/papers/brodersen10post-balacc.pdf)\n \"\"\"\n accuracy = compute_accuracy(tp, fn, len(ytest))\n balanced_accuracy = compute_balanced_accuracy(tp, tn, fp, fn)\n\n print(\"The accuracy for \"+str(filename)+\" is {0} and the balanced accuracy is {1}\".format(accuracy, balanced_accuracy))\n\n # Compute ROC curve and ROC area\n from sklearn.metrics import roc_auc_score\n\n y_prediction_as_prob_of_being_1 = sigmoid(np.dot(w.T, xtest))[0]\n\n plot_roc_curve(ytest, y_prediction_as_prob_of_being_1, filename)\n\n # Compute Precision/Recall curve\n plot_precision_recall_curve(ytest, y_prediction_as_prob_of_being_1, filename)\n\n'''\nComments:\nThe accuracy for DataSet3.csv is 0.26285714285714284 and the balanced accuracy is 0.7578361981799797\nThe ROC AUC for DataSet3.csv is 0.8690596562184024.\nThe average precision (AUC) for DataSet3.csv is 0.7011633213103383.\n\nThe accuracy for DataSet4.csv is 0.2571428571428571 and the balanced accuracy is 0.7102564102564103\nThe ROC AUC for DataSet4.csv is 0.8905982905982907.\nThe average precision (AUC) for DataSet4.csv is 0.7203145041300328.\n\nOne can notice that the simple accuracy is not a very good indicator of the performance of the classifier,\nthe balanced accuracy coming closer to it.\n'''","sub_path":"tcml_a4_e10/AmaliaGoia_A4E10/ex10.py","file_name":"ex10.py","file_ext":"py","file_size_in_byte":11816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"420205924","text":"import sys\r\nimport random\r\n\r\ndef isInCircle(x, y):\r\n\r\n\tvalue = (x - 10)*(x - 10) + (y - 10)*(y - 10)\r\n\r\n\tif value > 49:\r\n\t\treturn -1\r\n\telse:\r\n\t\treturn 1\r\n\r\nmyfile = open('validation_data', 'w')\r\n\r\nfor i in range(101):\r\n\tfor j in range(101):\r\n\r\n\t\tx = i*20/100\r\n\r\n\t\ty = j*20/100\r\n\t\tres = isInCircle(x, y)\r\n\r\n\t\tmyfile.write(str(x) + ' ' + str(y) + ' ' + str(res) + '\\n')\r\n\r\nmyfile.close()\r\n","sub_path":"Proyecto1-2/validation_generator.py","file_name":"validation_generator.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"545004111","text":"import scrapy\nimport re\nfrom scrapy.spiders import CrawlSpider\nfrom scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor\n\n\nclass LinkProofArtSpider(CrawlSpider):\n name = \"linkProofArt\"\n\n def start_requests(self):\n queries =['antonio+berni','pridiliano+pueyrredon']\n urls = [\n 'https://www.bellasartes.gob.ar/coleccion/buscar?q='\n ]\n for url in urls:\n for q in queries:\n yield scrapy.Request(url=url+q, callback=self.parse)\n\n\n def parse(self, response):\n for link in LxmlLinkExtractor(allow=r'https://www.bellasartes.gob.ar/coleccion/obra/.+', restrict_xpaths='//div[@class=\"obra card\"]').extract_links(response):\n print(link)\n ","sub_path":"image_art_crawler/image_art_crawler/spiders/link_proof_spider.py","file_name":"link_proof_spider.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"634796014","text":"from qtpy.QtWidgets import QMainWindow, QDialog\nimport os\nfrom qtpy.QtGui import QIcon\nfrom qtpy import QtGui\nimport logging\n\nfrom .. import load_ui\nfrom ..utilities.get import Get\nfrom ..utilities.file_handler import read_ascii, write_ascii\nfrom .. import refresh_image, settings_image\n\n\nclass LogLauncher:\n\n def __init__(self, parent=None):\n self.parent = parent\n\n if self.parent.log_id is None:\n log_id = Log(parent=self.parent)\n log_id.show()\n self.parent.log_id = log_id\n else:\n self.parent.log_id.activateWindow()\n self.parent.log_id.setFocus()\n\n\nclass Log(QMainWindow):\n\n def __init__(self, parent=None):\n self.parent = parent\n QMainWindow.__init__(self, parent=parent)\n ui_full_path = os.path.join(os.path.dirname(__file__),\n os.path.join('ui',\n 'log.ui'))\n self.ui = load_ui(ui_full_path, baseinstance=self)\n self.setWindowTitle(\"Log\")\n self.ui.log_text.setReadOnly(True)\n\n refresh_icon = QIcon(refresh_image)\n self.ui.refresh_pushButton.setIcon(refresh_icon)\n\n settings_icon = QIcon(settings_image)\n self.ui.settings_pushButton.setIcon(settings_icon)\n\n o_get = Get(parent=self.parent)\n self.log_file_name = o_get.get_log_file_name()\n\n self.check_log_size()\n self.loading_logging_file()\n\n # jump to end of file\n self.ui.log_text.moveCursor(QtGui.QTextCursor.End)\n\n def closeEvent(self, c):\n self.parent.log_id = None\n\n def loading_logging_file(self):\n try:\n log_text = read_ascii(self.log_file_name)\n self.ui.log_text.setPlainText(log_text)\n self.ui.log_text.moveCursor(QtGui.QTextCursor.End)\n except FileNotFoundError:\n self.ui.log_text.setPlainText(\"\")\n\n def clear_clicked(self):\n if os.path.exists(self.log_file_name):\n write_ascii(text=\"\", filename=self.log_file_name)\n logging.info(\"log file has been cleared by user\")\n self.loading_logging_file()\n\n def check_log_size(self):\n o_handler = LogHandler(parent=self.parent,\n log_file_name=self.log_file_name)\n o_handler.cut_log_size_if_bigger_than_buffer()\n\n def launch_settings(self):\n log_id = LogSettings(parent=self,\n grand_parent=self.parent)\n log_id.show()\n\n\nclass LogSettings(QDialog):\n\n def __init__(self, parent=None, grand_parent=None):\n self.parent = parent\n self.grand_parent = grand_parent\n QDialog.__init__(self, parent=self.parent)\n ui_full_path = os.path.join(os.path.dirname(__file__),\n os.path.join('ui',\n 'log_settings.ui'))\n self.ui = load_ui(ui_full_path, baseinstance=self)\n self.setWindowTitle(\"Log\")\n self.init_widgets()\n\n def init_widgets(self):\n log_buffer_size = self.grand_parent.session_dict['log buffer size']\n self.ui.buffer_size_spinBox.setValue(log_buffer_size)\n\n def accept(self):\n self.grand_parent.session_dict['log buffer size'] = self.ui.buffer_size_spinBox.value()\n self.parent.check_log_size()\n self.parent.loading_logging_file()\n self.close()\n\n\nclass LogHandler:\n\n def __init__(self, parent=None, log_file_name=\"\"):\n self.parent = parent\n self.log_file_name = log_file_name\n\n def cut_log_size_if_bigger_than_buffer(self):\n log_buffer_size = self.parent.session_dict['log buffer size']\n # check current size of log file\n log_text = read_ascii(self.log_file_name)\n log_text_split_by_cr = log_text.split(\"\\n\")\n log_file_size = len(log_text_split_by_cr)\n if log_file_size <= log_buffer_size:\n return\n else:\n new_log_text = log_text_split_by_cr[-log_buffer_size:]\n new_log_text = \"\\n\".join(new_log_text)\n write_ascii(text=new_log_text, filename=self.log_file_name)\n logging.info(\"log file has been truncated to fit buffer size limit\")\n","sub_path":"ibeatles/all_steps/log_launcher.py","file_name":"log_launcher.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"613502705","text":"import pandas as pd\nimport json\nfrom itertools import islice\nfrom deprecation import deprecated\n\ndef get_branch_size(nodes):\n \"\"\"return the branch size starting from the first node.\n \"\"\"\n self = nodes[0]\n for i, node in enumerate(nodes):\n if not node.startswith(self):\n return i\n return i+1\n\n@deprecated(details='using get_size_and_total instead')\ndef each_total(df):\n \"\"\"yield the total of branch values starting from each node(row).\n \"\"\"\n for istart, row in df.iterrows():\n size = get_branch_size(df[istart:]['tree_number'].values)\n yield df[istart:istart+size]['pc'].sum()\n\ndef main_old():\n # add a column 'total' of self and descendants\n df = pd.read_csv('Top50trial_mesh_pc.csv')\n df = df.sort_values(by='tree_number').reset_index()\n df['total'] = list(each_total(df))\n df.to_csv('Top50trial_mesh_pc_branch_total.csv', index=False)\n\n\n\ndef _each_size(nodes):\n \"\"\"yield the number of nodes of the branch starting with each node.\"\"\"\n for i, node in enumerate(nodes):\n yield get_branch_size(nodes[i:])\n\ndef _each_total(pc, sizes):\n \"\"\"yield sum of node values (pc) of each branch.\"\"\"\n for i, (count, size) in enumerate(zip(pc, sizes)):\n yield pc[i:i+size].sum()\n\ndef get_size_and_total(df):\n \"\"\"return size (number of nodes) and total (sum of node values) of each branch (row).\n\n df: a data frame with tree_number and pc, it will be sorted using tree_number.\n tree_number: the node name, need to be the same number of characters at the same level\n pc: the value (patient count) for each node.\n \"\"\"\n size = list(_each_size(df['tree_number'].values))\n total = list(_each_total(df['pc'].values, size))\n return size, total\n\n## supporting json tree presentation\ndef new_node(name):\n \"\"\"contruct a tree node with a dict.\n \"\"\"\n return dict(name=name,\n parent=None, children=list())\n\ndef each_ancestor(key):\n pair = key.rsplit('.', 1)\n while len(pair)==2:\n yield pair[0]\n pair = pair[0].rsplit('.', 1)\n yield 'root'\n\ndef find_parent(key, nodes):\n for k in each_ancestor(key):\n if k in nodes:\n return nodes[k]\n\ndef main_d3_tree(incsv, outjs):\n \"\"\"output a js file with treeData.\n\n - incsv: a csv file with [tree_number, branch_total, ...]\n - outjs: a writable stream\n \"\"\"\n df = pd.read_csv(incsv, index_col=0)\n\n # initate all the nodes\n nodes = dict(root = new_node('root'))\n for i, row in df.iterrows():\n nodes[row['tree_number']] = new_node(\n name=f\"\"\"{row['tree_number']}: {row['branch_total']}\"\"\")\n\n # add the parent-children\n for key, node in islice(nodes.items(), 1, None): #skip the root\n parent = find_parent(key, nodes)\n parent['children'].append(node)\n node['parent'] = parent['name']\n\n # write to the js file\n for key, node in nodes.items():\n if not node['children']:\n del node['children']\n outjs.write('treeData = ')\n json.dump([nodes['root']], outjs)\n\ndef main(incsv, outcsv):\n #breakpoint()\n df = pd.read_csv(incsv, index_col=0)\n df = df.sort_values(by='tree_number')\n size, total = get_size_and_total(df)\n df['branch_size'] = size\n df['branch_total'] = total\n df.to_csv(outcsv)\n\n\nif __name__ == '__main__':\n import sys\n main(sys.stdin, sys.stdout)\n\n\n","sub_path":"scripts/counting_tree/mesh_counting.py","file_name":"mesh_counting.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"90942683","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 26 15:18:27 2019\n\n@author: mariandm\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport copy\n\nESS = 1e4*np.array([[1.1111,0.5555,0.0000,3.3333],[1.1111,0.5556,0.0000,3.3333],[1.1157,0.4545,0.1240,3.3884],[1.1842,0.5263,0.0000,3.4211],[1.1842,0.5263,0.0000,3.4211],[1.1111,0.5556,0.0000,3.3333],[1.1111,0.5556,0.0000,3.3333],[1.1842,0.5263,0.0000,3.4211],[1.1842,0.5263,0.0000,3.4211],[1.1842,0.5263,0.0000,3.4211],[1.2500,0.5000,0.0000,3.5000],[1.2500,0.5000,0.0000,3.5000],[1.2500,0.5000,0.0000,3.5000],[1.2500,0.5000,0.0000,3.5000],[1.2500,0.5000,0.0000,3.5000],[1.2500,0.5000,0.0000,3.5000],[1.3750,0.3125,0.0000,3.3750],[1.3750,0.3125,0.0000,3.3750],[1.3750,0.3125,0.0000,3.3750],[1.3750,0.3125,0.0000,3.3750],[1.3750,0.3125,0.0000,3.3750],[1.3750,0.3125,0.0000,3.3750]])\nmatrixCoefficients = np.array([[0.7,0.9,0.4,0.6,0.5,0.8],[0.7,0.8,0.4,0.6,0.5,0.9],[0.6,0.9,0.4,0.8,0.5,0.7],[0.6,0.9,0.4,0.7,0.5,0.8],[0.6,0.8,0.4,0.7,0.5,0.9],[0.7,0.9,0.4,0.5,0.6,0.8],[0.7,0.8,0.4,0.5,0.6,0.9],[0.6,0.9,0.4,0.5,0.7,0.8],[0.6,0.8,0.4,0.5,0.7,0.9],[0.6,0.7,0.4,0.5,0.8,0.9],[0.5,0.9,0.4,0.8,0.6,0.7],[0.5,0.9,0.4,0.7,0.6,0.8],[0.5,0.8,0.4,0.7,0.6,0.9],[0.5,0.9,0.4,0.6,0.7,0.8],[0.5,0.8,0.4,0.6,0.7,0.9],[0.5,0.7,0.4,0.6,0.8,0.9],[0.4,0.9,0.5,0.8,0.6,0.7],[0.4,0.9,0.5,0.7,0.6,0.8],[0.4,0.8,0.5,0.7,0.6,0.9],[0.4,0.9,0.5,0.6,0.7,0.8],[0.4,0.8,0.5,0.6,0.7,0.9],[0.4,0.7,0.5,0.6,0.8,0.9]])\n\n\ntreatmentType = 'Metronomic'\nsubtreatmentType=3\n\nmaxSimulationTime = 10000\nsetNumber=500\n\n\nfor curr_matrix in range(0,22):\n matrixIndex = curr_matrix\n\n\n alphas = matrixCoefficients[matrixIndex,:]\n \n \n \n finalDensity=np.zeros(setNumber)\n TminusProportion=np.zeros(setNumber)\n TminusColonizationTime=np.zeros(setNumber)\n \n \n \n for curr_set in range(setNumber):\n print(curr_set)\n \n #Creating sets\n \n #Original Parameters\n scale = .01\n r = np.array([0.27726, 0.34657, 0.66542])\n r = r*scale\n # PSA dynamics\n sigmaPSA = 0.5;\n \n \n k1 = [1.5, 10000, 10000]\n k2 = [0.5, 100, 10000]\n k3 = [15000,10000,10000]\n \n #randomizing the parameters\n random=np.random.uniform(-.1,.1,13)\n r=[r[0]+r[0]*random[0],r[1]+r[1]*random[1],r[2]+r[2]*random[2]]\n sigmaPSA=sigmaPSA+sigmaPSA*random[3]\n k1=[k1[0]+k1[0]*random[4],k1[1]+k1[1]*random[5],k1[2]+k1[2]*random[6]]\n k2=[k2[0]+k2[0]*random[7],k2[1]+k2[1]*random[8],k2[2]+k2[2]*random[9]]\n k3=[k3[0]+k3[0]*random[10],k3[1]+k3[1]*random[11],k3[2]+k3[2]*random[12]]\n \n ########################################\n\n #Initial tumor densities set at 40% of ESS values\n y0 = ESS[matrixIndex, :]* 0.4;\n y0[y0<1e-9] = 1e-9\n\n #Give abiraterone at what % of ESS PSA?\n maxPSAPercent = 0.8;\n PSA_zenith = ESS[matrixIndex,3] * maxPSAPercent\n PSA_nadir = PSA_zenith * maxPSAPercent/2\n\n\n # Find first treatment time to build treatments.\n y = copy.deepcopy(y0)\n firstTreatmentTime = 0\n while y[3] < PSA_zenith:\n \n firstTreatmentTime = firstTreatmentTime + 1;\n \n # Update carrying capacities with current symbiotic T+.\n k = k3\n \n # T+, TP, T-, and PSA ODE's\n dydt = np.zeros([4]);\n \n dydt[0] = y[0] * r[0] * (1 - ( ( y[0] + alphas[0] * y[1] + alphas[1] * y[2] ) / k[0] ) )\n dydt[1] = y[1] * r[1] * (1 - ( ( alphas[2] * y[0] + y[1] + alphas[3] * y[2] ) / k[1] ) )\n dydt[2] = y[2] * r[2] * (1 - ( ( alphas[4] * y[0] + alphas[5] * y[1] + y[2] ) / k[2] ) )\n dydt[3] = sum(y[0:3]) - sigmaPSA * y[3]\n\n y = y + dydt;\n\n\n # No abiraterone treatment sets Abi flag to 0 for entire simulation (and this is used to zero out for all other treatment types).\n AbiOnOffFlag = np.zeros([maxSimulationTime])\n ADTOnOffFlag = np.zeros([maxSimulationTime])\n\n\n if treatmentType=='Adaptive':\n if subtreatmentType==2:\n ADTOnOffFlag[firstTreatmentTime:firstTreatmentTime + 800] = 1\n AbiOnOffFlag[firstTreatmentTime:firstTreatmentTime + 800] = 0\n\n # SOC full dose abiraterone set Abi flag to 1 after first treatment time\n if treatmentType=='MTD':\n if subtreatmentType==0:\n AbiOnOffFlag[firstTreatmentTime:maxSimulationTime] = 0\n ADTOnOffFlag[firstTreatmentTime:maxSimulationTime] = 1\n elif subtreatmentType==1:\n AbiOnOffFlag[firstTreatmentTime:maxSimulationTime] = 1\n ADTOnOffFlag[firstTreatmentTime:maxSimulationTime] = 1\n\n\n\n # Metronomic gives 800 long induction with cycles thereafter.\n if treatmentType=='Metronomic': \n \n #Induction period\n ADTOnOffFlag[firstTreatmentTime:firstTreatmentTime + 800] = 1\n \n if subtreatmentType==0: #ADT+Abi, none\n # Cycles start 2000 time units after the first treatment time, are 1000\n # time units apart, and administer Abiraterone for 200 time units.\n for cycles in range(0,10):\n AbiOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1000):firstTreatmentTime + 2000 + (cycles * 1000) + 200] = 1\n ADTOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1000):firstTreatmentTime + 2000 + (cycles * 1000) + 200] = 1\n\n elif subtreatmentType==1: #ADT+Abi, none, ADT, none\n # Cycles start 2000 time units after the first treatment time, are 1000\n # time units apart, and administer Abiraterone for 200 time units.\n for cycles in range(0,10,2):\n AbiOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1000):firstTreatmentTime + 2000 + (cycles * 1000) + 200] = 1\n ADTOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1000):firstTreatmentTime + 2000 + (cycles * 1000) + 200] = 1\n for cycles in range(1,10,2):\n AbiOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1000):firstTreatmentTime + 2000 + (cycles * 1000) + 200] = 0\n ADTOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1000):firstTreatmentTime + 2000 + (cycles * 1000) + 200] = 1\n\n elif subtreatmentType==2: #ADT+abi, ADT, none\n # Cycles start 2000 time units after the first treatment time, are 1000\n # time units apart, and administer Abiraterone for 200 time units.\n for cycles in range(0,10):\n AbiOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1200):firstTreatmentTime + 2000 + (cycles * 1200) + 200] = 1\n ADTOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1200):firstTreatmentTime + 2000 + (cycles * 1200) + 200] = 1\n\n ADTOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1200) + 200:firstTreatmentTime + 2000 + (cycles * 1200) + 400] = 1\n\n elif subtreatmentType==3: #ADT, ADT+abi, none\n # Cycles start 2000 time units after the first treatment time, are 1000\n # time units apart, and administer Abiraterone for 200 time units.\n for cycles in range(0,10):\n ADTOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1200):firstTreatmentTime + 2000 + (cycles * 1200) + 200] = 1\n\n AbiOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1200) + 200:firstTreatmentTime + 2000 + (cycles * 1200) + 400] = 1\n ADTOnOffFlag[firstTreatmentTime + 2000 + (cycles * 1200) + 200:firstTreatmentTime + 2000 + (cycles * 1200) + 400] = 1\n\n\n\n # Run the ODE\n # -----------\n\n # Set initial state.\n c=0\n y = copy.deepcopy(y0)\n\n # Create and initialize matrix for ODE solution\n allSolution = []\n allSolution.append(list(y))\n count=True\n warning=False\n #Run ODE with treatment selection.\n for time in range(1,maxSimulationTime):\n # Adaptive Abi is built during the simulation. Turns Abi on once the \n # PSA zenith value is reached and turns it off once the nadir is reached.\n if treatmentType=='Adaptive':\n if subtreatmentType==0:\n if y[3] > PSA_zenith:\n AbiOnOffFlag[time] = 1\n ADTOnOffFlag[time] = 1\n elif (y[3] < PSA_nadir):\n AbiOnOffFlag[time] = 0\n ADTOnOffFlag[time] = 0\n else:\n AbiOnOffFlag[time] = AbiOnOffFlag[time - 1] \n ADTOnOffFlag[time] = AbiOnOffFlag[time - 1] \n elif subtreatmentType==1:\n if y[3] > PSA_zenith:\n if(count):\n AbiOnOffFlag[time] = 1\n ADTOnOffFlag[time] = 1\n else:\n AbiOnOffFlag[time] = 0\n ADTOnOffFlag[time] = 1\n elif (y[3] < PSA_nadir):\n AbiOnOffFlag[time] = 0\n ADTOnOffFlag[time] = 0\n else:\n AbiOnOffFlag[time] = AbiOnOffFlag[time - 1] \n ADTOnOffFlag[time] = AbiOnOffFlag[time - 1] \n\n if ((ADTOnOffFlag[-2] - ADTOnOffFlag[-1])>0):\n count=not(count)\n ############################################### \n elif subtreatmentType==2 and time>(firstTreatmentTime+2000):\n if y[3] > PSA_zenith:\n AbiOnOffFlag[time] = 1\n ADTOnOffFlag[time] = 1\n elif (y[3] < PSA_nadir):\n AbiOnOffFlag[time] = 0\n ADTOnOffFlag[time] = 0\n else:\n AbiOnOffFlag[time] = AbiOnOffFlag[time - 1] \n ADTOnOffFlag[time] = AbiOnOffFlag[time - 1] \n ################################################# \n\n if treatmentType=='MTD' and subtreatmentType==2 and time>firstTreatmentTime:\n if y[3] < PSA_zenith:\n warning=True\n if(y[3]>PSA_zenith and warning):\n count=False\n if(count):\n AbiOnOffFlag[time]=0\n ADTOnOffFlag[time]=1\n else:\n AbiOnOffFlag[time]=1\n ADTOnOffFlag[time]=1\n \n \n # If Abi is being given, then use Abi parameters.\n if (ADTOnOffFlag[time] == 0):\n k = k3\n elif (AbiOnOffFlag[time] == 1):\n k = [y[1] * k2[0], k2[1], k2[2]]\n \n # If Abi is not being given, use naive parameters.\n elif AbiOnOffFlag[time] == 0:\n k = [y[1] * k1[0], k1[1], k1[2]]\n \n # T+, TP, T-, and PSA ODE's\n dydt = np.zeros([4])\n \n dydt[0] = y[0] * r[0] * (1 - ( ( y[0] + alphas[0] * y[1] + alphas[1] * y[2] ) / k[0] ) )\n dydt[1] = y[1] * r[1] * (1 - ( ( alphas[2] * y[0] + y[1] + alphas[3] * y[2] ) / k[1] ) )\n dydt[2] = y[2] * r[2] * (1 - ( ( alphas[4] * y[0] + alphas[5] * y[1] + y[2] ) / k[2] ) )\n dydt[3] = sum(y[0:3]) - sigmaPSA * y[3]\n \n y = y + dydt;\n \n # Lower bound check to keep a small density of any cell type. \n y[y<1e-9] = 1e-9\n\n \n # Append to solutions vector. \n allSolution.append(list(y))\n \n\n finalDensity[curr_set]=np.sum(y[0:3])\n TminusProportion[curr_set]=y[2]/finalDensity[curr_set]\n print(TminusProportion[curr_set])\n \n #allSolution=np.array(allSolution)\n #plt.plot(range(maxSimulationTime),allSolution[:,3])\n #plt.xlim([0,10000])\n #plt.show()\n\n #plt.plot(range(maxSimulationTime),allSolution[:,0],color=\"b\",label=\"T+\")\n #plt.plot(range(maxSimulationTime),allSolution[:,1],color=\"r\",label=\"TP\")\n #plt.plot(range(maxSimulationTime),allSolution[:,2],color=\"g\",label=\"T-\")\n #plt.ylim([-100,15000])\n #plt.xlim([0,10000])\n #plt.legend()\n #plt.show()\n\n plt.hist(finalDensity,color=\"dimgrey\")\n plt.xlabel(\"Population Density\")\n plt.ylabel(\"Frequency\")\n plt.xlim([4000,15000])\n plt.title(\"Final Population Density, Treatment: \"+treatmentType+\", Patient \"+str(curr_matrix+1))\n plt.savefig(\"Sensitivity_FinalPopulationDensity_Treatment\"+treatmentType+\"_subtreatment_\"+str(subtreatmentType)+\"_matrixIndex\"+str(curr_matrix)+\".pdf\")\n plt.close()\n\n plt.hist(TminusProportion,color=\"silver\")\n plt.xlabel(\"Proportion of T- cells\")\n plt.ylabel(\"Frequency\")\n plt.xlim([-0.1,1.1])\n plt.title(\"Final Proportion of T- cells, Treatment: \"+treatmentType+\", Patient \"+str(curr_matrix+1))\n plt.savefig(\"Sensitivity_FinalProportion_Treatment\"+treatmentType+\"_subtreatment_\"+str(subtreatmentType)+\"_matrixIndex\"+str(curr_matrix)+\".pdf\")\n plt.close() \n\n","sub_path":"mCRPCcode/SensitivityAnalysis/AlternativeModel2.py","file_name":"AlternativeModel2.py","file_ext":"py","file_size_in_byte":13287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"47180169","text":"import datetime\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.header import Header\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email import encoders\nfrom .tools import fetch_credentials\n\n\nclass MailAux():\n\n def __init__(self, mode='local'):\n\n if mode == 'local':\n\n self.credentials = fetch_credentials('mail.json', mode=mode)\n\n else:\n\n self.credentials = fetch_credentials(\n 'credentials/mail.json', mode=mode)\n\n self.files = []\n\n def attach_file(self, filename, alias):\n\n self.files.append({'filename': filename, 'alias': alias})\n\n def send_mail(self, subject, body, sender_name, sender_mail, to, date=True):\n\n server = self.credentials['SMTP_SERVER']\n port = self.credentials['SMTP_PORT']\n login = self.credentials['LOGIN']\n password = self.credentials['PASSWORD']\n self.subject = subject\n\n mail = MIMEMultipart()\n\n conn = smtplib.SMTP(server, port)\n conn.ehlo()\n conn.starttls()\n conn.ehlo()\n conn.login(login, password)\n\n # determines current day for mail subject\n today = datetime.datetime.today()\n month_number = int(today.strftime('%m')) - 1\n month_array = ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho',\n 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro']\n month = month_array[month_number]\n date_word = str(today.strftime('%d')) + '/' + month\n\n mail[\"From\"] = '\"{}\" <{}>'.format(sender_name, sender_mail)\n mail[\"To\"] = to\n subject = '{} | {} | {}'.format(self.subject, sender_name, date_word)\n\n mail['Subject'] = Header(subject, 'utf-8')\n\n for f in self.files:\n\n part = MIMEBase('application', \"octet-stream\")\n part.set_payload(open(f['filename'], \"rb\").read())\n encoders.encode_base64(part)\n\n part.add_header(\n 'Content-Disposition', 'attachment; filename=\"' + f['alias'] + '\"')\n\n mail.attach(part)\n\n # build message, send mail\n msgText = MIMEText(body, 'html', 'utf-8')\n\n mail.attach(msgText)\n\n conn.sendmail(mail[\"From\"], mail[\"To\"].split(','), mail.as_string())\n\n return True\n\n def handle_errors(self, subject, array, sender_name, sender_mail, to):\n\n body = 'Errors: '\n\n for error in array:\n\n body += ' {}'.format(error)\n\n self.send_mail(subject, body, sender_name, sender_mail, to)\n","sub_path":"auxtools/MailAux.py","file_name":"MailAux.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"15776396","text":"# Cog Stuff\r\nfrom discord.ext import commands\r\nfrom discord.embeds import Embed\r\nfrom discord.colour import Color\r\n# AA Contexts\r\nfrom django.conf import settings\r\nfrom django.contrib.auth.models import User\r\nfrom django.core.exceptions import ObjectDoesNotExist\r\nfrom allianceauth.eveonline.models import EveCharacter\r\nfrom allianceauth.eveonline.evelinks import evewho\r\n# AA-Discordbot\r\nfrom aadiscordbot.cogs.utils.decorators import message_in_channels, sender_has_any_perm\r\nfrom aadiscordbot.app_settings import aastatistics_active\r\n\r\nimport logging\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass Members(commands.Cog):\r\n \"\"\"\r\n All about users!\r\n \"\"\"\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n\r\n @commands.command(pass_context=True)\r\n @sender_has_any_perm(['corputils.view_alliance_corpstats', 'corpstats.view_alliance_corpstats'])\r\n @message_in_channels(settings.ADMIN_DISCORD_BOT_CHANNELS)\r\n async def lookup(self, ctx):\r\n \"\"\"\r\n Gets Auth data about a character\r\n Input: a Eve Character Name\r\n \"\"\"\r\n input_name = ctx.message.content[8:]\r\n \r\n embed = Embed(\r\n title=\"Character Lookup {character_name}\".format(character_name=input_name)\r\n )\r\n \r\n try:\r\n char = EveCharacter.objects.get(character_name=input_name)\r\n\r\n try:\r\n main = char.character_ownership.user.profile.main_character\r\n state = char.character_ownership.user.profile.state.name\r\n groups = char.character_ownership.user.groups.all().values_list('name', flat=True)\r\n\r\n try:\r\n discord_string = \"<@{}>\".format(char.character_ownership.user.discord.uid)\r\n except Exception as e:\r\n logger.error(e)\r\n discord_string = \"unknown\"\r\n\r\n if aastatistics_active():\r\n alts = char.character_ownership.user.character_ownerships.all().select_related('character', 'character_stats').values_list('character__character_name', 'character__corporation_ticker', 'character__character_id', 'character__corporation_id', 'character__character_stats__zk_12m', 'character__character_stats__zk_3m')\r\n zk12 = 0\r\n zk3 = 0\r\n else:\r\n alts = char.character_ownership.user.character_ownerships.all().select_related('character').values_list('character__character_name', 'character__corporation_ticker', 'character__character_id', 'character__corporation_id')\r\n zk12 = \"Not Installed\"\r\n zk3 = \"Not Installed\"\r\n\r\n if aastatistics_active():\r\n for alt in alts:\r\n if alt[4]:\r\n zk12 += alt[4]\r\n zk3 += alt[5]\r\n\r\n embed.colour = Color.blue()\r\n embed.description = \"**{0}** is linked to **{1} [{2}]** (State: {3})\".format(\r\n char,\r\n main,\r\n main.corporation_ticker,\r\n state\r\n )\r\n\r\n alt_list = [\"[{}](https://evewho.com/character/{}) *[ [{}](https://evewho.com/corporation/{}) ]*\".format(a[0], a[2], a[1], a[3]) for a in alts]\r\n for idx, names in enumerate([alt_list[i:i + 6] for i in range(0, len(alt_list), 6)]):\r\n if idx < 6:\r\n embed.add_field(\r\n name=\"Linked Characters {}\".format(idx+1), value=\", \".join(names), inline=False\r\n )\r\n else:\r\n embed.add_field(\r\n name=\"Linked Characters {} **( Discord Limited There are More )**\".format(idx), value=\", \".join(names), inline=False\r\n )\r\n break\r\n\r\n if len(groups) > 0:\r\n embed.add_field(\r\n name=\"Groups\", value=\", \".join(groups), inline=False\r\n )\r\n\r\n if aastatistics_active():\r\n embed.add_field(\r\n name=\"12m Kills\", value=zk12, inline=True\r\n )\r\n embed.add_field(\r\n name=\"3m Kills\", value=zk3, inline=True\r\n )\r\n\r\n embed.add_field(\r\n name=\"Discord Link\", value=discord_string, inline=False\r\n )\r\n\r\n return await ctx.send(embed=embed)\r\n except ObjectDoesNotExist:\r\n users = char.ownership_records.values('user')\r\n users = User.objects.filter(id__in=users)\r\n characters = EveCharacter.objects.filter(ownership_records__user__in=users).distinct()\r\n embed = Embed(title=\"Character Lookup\")\r\n embed.colour = Color.blue()\r\n\r\n embed.description = \"**{0}** is Unlinked searching for any characters linked to known users\".format(\r\n char,\r\n )\r\n user_names = [\"{}\".format(user.username) for user in users]\r\n embed.add_field(\r\n name=\"Old Users\", value=\", \".join(user_names), inline=False\r\n )\r\n alt_list = [\"[{}](https://evewho.com/character/{}) *[ [{}](https://evewho.com/corporation/{}) ]*\".format(a.character_name,\r\n a.character_id,\r\n a.corporation_ticker,\r\n a.corporation_id\r\n ) for a in characters]\r\n for idx, names in enumerate([alt_list[i:i + 6] for i in range(0, len(alt_list), 6)]):\r\n if idx < 6:\r\n embed.add_field(\r\n name=\"Found Characters {}\".format(idx+1), value=\", \".join(names), inline=False\r\n )\r\n else:\r\n embed.add_field(\r\n name=\"Found Characters {} **( Discord Limited There are More )**\".format(idx), value=\", \".join(names), inline=False\r\n )\r\n break\r\n\r\n return await ctx.send(embed=embed)\r\n\r\n except EveCharacter.DoesNotExist:\r\n embed.colour = Color.red()\r\n\r\n embed.description = (\r\n \"Character **{character_name}** does not exist in our Auth system\"\r\n ).format(character_name=input_name)\r\n\r\n return await ctx.send(embed=embed)\r\n\r\n @commands.command(pass_context=True)\r\n @sender_has_any_perm(['corputils.view_alliance_corpstats', 'corpstats.view_alliance_corpstats'])\r\n @message_in_channels(settings.ADMIN_DISCORD_BOT_CHANNELS)\r\n async def altcorp(self, ctx):\r\n \"\"\"\r\n Gets Auth data about an altcorp\r\n Input: a Eve Character Name\r\n \"\"\"\r\n\r\n input_name = ctx.message.content[9:]\r\n chars = EveCharacter.objects.filter(corporation_name=input_name)\r\n own_ids = [settings.DISCORD_BOT_MEMBER_ALLIANCES]\r\n alts_in_corp = []\r\n for c in chars:\r\n if c.alliance_id not in own_ids:\r\n alts_in_corp.append(c)\r\n\r\n mains = {}\r\n for a in alts_in_corp:\r\n try:\r\n main = a.character_ownership.user.profile.main_character\r\n if main.character_id not in mains:\r\n mains[main.character_id] = [main, 0]\r\n mains[main.character_id][1] += 1\r\n alt_corp_id = a.corporation_id\r\n except Exception as e:\r\n logger.error(e)\r\n pass\r\n output = []\r\n base_string = \"[{}]({}) [ [{}]({}) ] has {} alt{}\"\r\n for k, m in mains.items():\r\n output.append(\r\n base_string.format(\r\n m[0],\r\n evewho.character_url(m[0].character_id),\r\n m[0].corporation_ticker,\r\n evewho.corporation_url(m[0].corporation_id),\r\n m[1],\r\n \"s\" if m[1] > 1 else \"\"\r\n )\r\n )\r\n\r\n for strings in [output[i:i + 10] for i in range(0, len(output), 10)]:\r\n embed = Embed(title=input_name)\r\n embed.colour = Color.blue()\r\n embed.description = \"\\n\".join(strings)\r\n await ctx.send(embed=embed)\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Members(bot))\r\n","sub_path":"aadiscordbot/cogs/members.py","file_name":"members.py","file_ext":"py","file_size_in_byte":9268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"599624798","text":"from django.db import transaction\nfrom django.db.models import Sum, F, Q\nfrom django.contrib.auth import get_user_model\nfrom .models import Bet, MatchResult, Standing\n\nCustomUser = get_user_model()\n\n\ndef standardize(overs):\n overs = round(overs, 1)\n base = overs // 1\n mantissa = (overs*10) % 10\n if mantissa > 5:\n mantissa = 6-mantissa\n base += 1\n return base + 0.1 * mantissa\n\n\ndef get_rr(rr_str, team_runs, team_overs):\n if rr_str:\n runs, overs = rr_str.split('/')\n runs = int(runs) + int(team_runs)\n overs = float(overs) + float(team_overs)\n overs = standardize(overs)\n else:\n runs, overs = int(team_runs), float(team_overs)\n return f\"{runs}/{overs}\"\n\n\ndef get_nrr(nrr_str):\n runs, overs = nrr_str.split('/')\n base, mantissa = overs.split('.')\n denom = int(mantissa) / 6\n final_overs = int(base) + denom\n return int(runs)/final_overs\n\n\ndef update_table(match, team1_runs, team1_overs, team2_runs, team2_overs):\n if match.match.team1 == match.winner:\n for_rr = get_rr(match.winner.standing.for_rr, team1_runs, team1_overs)\n against_rr = get_rr(match.winner.standing.against_rr,\n team2_runs, team2_overs)\n Standing.objects.filter(team=match.match.team1).update(\n played=F('played')+1,\n won=F('won')+1,\n points=F('points')+2,\n for_rr=for_rr,\n against_rr=against_rr,\n nrr=get_nrr(for_rr) - get_nrr(against_rr),\n )\n\n for_rr = get_rr(match.match.team2.standing.for_rr,\n team2_runs, team2_overs)\n against_rr = get_rr(match.match.team2.standing.against_rr,\n team1_runs, team1_overs)\n Standing.objects.filter(team=match.match.team2).update(\n played=F('played')+1,\n lost=F('lost')+1,\n for_rr=for_rr,\n against_rr=against_rr,\n nrr=get_nrr(for_rr) - get_nrr(against_rr),\n )\n\n else:\n for_rr = get_rr(match.match.team1.standing.for_rr,\n team1_runs, team1_overs)\n against_rr = get_rr(match.match.team1.standing.against_rr,\n team2_runs, team2_overs)\n Standing.objects.filter(team=match.match.team1).update(\n played=F('played')+1,\n lost=F('lost')+1,\n for_rr=for_rr,\n against_rr=against_rr,\n nrr=get_nrr(for_rr) - get_nrr(against_rr),\n )\n\n for_rr = get_rr(match.winner.standing.for_rr, team2_runs, team2_overs)\n against_rr = get_rr(match.winner.standing.against_rr,\n team1_runs, team1_overs)\n Standing.objects.filter(team=match.match.team2).update(\n played=F('played')+1,\n won=F('won')+1,\n points=F('points')+2,\n for_rr=for_rr,\n against_rr=against_rr,\n nrr=get_nrr(for_rr) - get_nrr(against_rr),\n )\n\n\ndef update_standings(match, status):\n if status == 'abandoned':\n Standing.objects.filter(Q(team=match.match.team1) |\n Q(team=match.match.team2)).update(played=F('played')+1,\n no_result=F(\n 'no_result')+1,\n points=F('points')+1)\n else:\n team1_runs, team1_overs = match.team1_score.split('/')\n team2_runs, team2_overs = match.team2_score.split('/')\n update_table(match, team1_runs, team1_overs, team2_runs, team2_overs)\n\n\ndef update_bet_table(bet, amt):\n if amt < 0:\n bet.status = 'lost'\n else:\n bet.status = 'won'\n bet.win_lose_amt = amt\n\n # Update user\n user = bet.user\n user.amount = F('amount') + amt\n\n # Save to DB\n bet.save(update_fields=['win_lose_amt', 'status'])\n user.save(update_fields=['amount'])\n\n\ndef process_winner_prediction_bets(match):\n # Get all bets for IPL Winner\n match_bets = Bet.objects.filter(match__isnull=True)\n\n if match.winner: # Match Completed\n\n # Get winning bets and losing bets\n winning_bets = match_bets.filter(bet_team=match.winner)\n losing_bets = match_bets.exclude(bet_team=match.winner)\n winners = winning_bets.count()\n\n # Get total win amount and total loss amount\n total_win_amt = winning_bets.aggregate(\n tot_amt=Sum('bet_amt'))['tot_amt']\n total_lost_amt = losing_bets.aggregate(\n tot_amt=Sum('bet_amt'))['tot_amt']\n if total_win_amt and total_lost_amt: # Some winners and Some losers\n for bet in winning_bets:\n amt = total_lost_amt / winners\n update_bet_table(bet, amt)\n for bet in losing_bets:\n update_bet_table(bet, bet.bet_amt * -1)\n\n else: # All winners (bet on same time)\n for bet in match_bets:\n bet.status = 'noresult'\n bet.save(update_fields=['status'])\n\n else: # Match Abandoned\n for bet in match_bets:\n bet.status = 'noresult'\n bet.save(update_fields=['status'])\n\n\ndef process_defaulter_bets(match):\n match_bets = Bet.objects.filter(match=match)\n default_cnt = match_bets.filter(status=\"default\").count()\n if default_cnt: # Defaulter present\n\n # Get defaulter and non-defaulters\n non_default_bets = match_bets.exclude(status=\"default\")\n default_bets = match_bets.filter(status=\"default\")\n\n # Get total default amount and total non-default amount\n total_win_amt = non_default_bets.aggregate(\n tot_amt=Sum('bet_amt'))['tot_amt']\n total_lost_amt = default_bets.aggregate(\n tot_amt=Sum('bet_amt'))['tot_amt']\n if total_win_amt:\n for bet in non_default_bets:\n amt = (bet.bet_amt/total_win_amt) * total_lost_amt\n update_bet_table(bet, amt)\n for bet in default_bets:\n update_bet_table(bet, bet.bet_amt * -1)\n else:\n for bet in match_bets:\n bet.status = 'noresult'\n bet.save(update_fields=['status'])\n else: # No defaulters\n for bet in match_bets:\n bet.status = 'noresult'\n bet.save(update_fields=['status'])\n\n\ndef process_match_completed(match):\n match_bets = Bet.objects.filter(match=match)\n\n # Get winning bets and losing bets\n winning_bets = match_bets.filter(bet_team=match.winner)\n losing_bets = match_bets.exclude(bet_team=match.winner)\n\n # Get total win amount and total loss amount\n total_win_amt = winning_bets.aggregate(\n tot_amt=Sum('bet_amt'))['tot_amt']\n total_lost_amt = losing_bets.aggregate(\n tot_amt=Sum('bet_amt'))['tot_amt']\n if total_win_amt and total_lost_amt: # Some winners and Some losers\n for bet in winning_bets:\n amt = (bet.bet_amt/total_win_amt) * total_lost_amt\n update_bet_table(bet, amt)\n for bet in losing_bets:\n update_bet_table(bet, bet.bet_amt * -1)\n elif total_lost_amt: # Either defaulters or everyone bet on non winning team\n process_defaulter_bets(match)\n else: # All winners (bet on same time)\n for bet in match_bets:\n bet.status = 'noresult'\n bet.save(update_fields=['status'])\n\n\ndef settle_bets(match):\n\n if match.winner: # Match Completed\n process_match_completed(match)\n else: # Match Abandoned\n process_defaulter_bets(match)\n\n if match.match.type == 'final':\n process_winner_prediction_bets(match)\n\n\ndef validate_bet_and_save(user, match, bet_team, bet_amt):\n\n def get_existing_bet():\n try:\n return Bet.objects.get(match=match, user=user)\n except:\n return\n\n existing_bet = get_existing_bet()\n if existing_bet and existing_bet.bet_team == bet_team and existing_bet.bet_amt < bet_amt:\n existing_bet.bet_amt = bet_amt\n existing_bet.updated = True\n existing_bet.save(update_fields=['bet_amt', 'updated'])\n return f\"Bet increased for {bet_team.shortname} to Rs.{bet_amt}\"\n elif existing_bet and existing_bet.bet_team == bet_team:\n return f\"For Bet change amount should be more than Rs.{existing_bet.bet_amt}\"\n elif existing_bet and existing_bet.bet_team != bet_team and (existing_bet.bet_amt*2) > bet_amt:\n return f\"For Team Change minimum amount is Rs.{existing_bet.bet_amt*2}\"\n elif existing_bet and existing_bet.bet_team != bet_team:\n existing_bet.bet_team = bet_team\n existing_bet.bet_amt = bet_amt\n existing_bet.updated = True\n existing_bet.save(update_fields=['bet_team', 'bet_amt', 'updated'])\n return f\"Bet changed to {bet_team.shortname} for Rs.{bet_amt}\"\n elif match.match.entry_cutoff_passed:\n return f\"Cutoff Passed for New Bet entry\"\n else:\n Bet.objects.create(user=user,\n match=match,\n bet_team=bet_team,\n bet_amt=bet_amt)\n return f\"Your Bet - {bet_team.shortname} for Rs.{bet_amt}\"\n\n\ndef winner_entered(**data):\n return data.get('winner') or data.get('win_type') or data.get('win_margin')\n\n\ndef winner_valid(**data):\n return data.get('winner') and data.get('win_type') and data.get('win_margin')\n\n\ndef default_bets_placed(obj):\n # Check if number of bets for match is same as number of players\n player_count = CustomUser.objects.exclude(is_staff=True).count()\n bet_placed_count = Bet.objects.filter(\n match=obj).count()\n return player_count == bet_placed_count\n\n\ndef bet_for_match_exists(user, obj):\n return Bet.objects.filter(user=user,\n match=obj,\n status='placed').exists()\n\n\ndef add_default_bets(obj):\n # Add default bets for all players where no match bet exists\n all_users = CustomUser.objects.exclude(is_staff=True)\n for user in all_users:\n if not bet_for_match_exists(user, obj):\n Bet.objects.create(user=user,\n match=obj,\n bet_amt=obj.match.min_bet,\n status=\"default\")\n\n\n@transaction.atomic\ndef validate_result_and_save(**data):\n match = data.get('match')\n db_obj = MatchResult.objects.get(match=match)\n status = data.get('status')\n\n if not default_bets_placed(db_obj):\n add_default_bets(db_obj)\n\n # No Match Status Sent but Winner updated\n if not status and winner_entered(**data):\n return f\"Set Match status to Completed\"\n elif not status:\n db_obj.team1_score = data.get('team1_score')\n db_obj.team2_score = data.get('team2_score')\n db_obj.save(update_fields=['team1_score', 'team2_score'])\n return f\"Team Score(s) Updated\"\n elif status == 'abandoned':\n db_obj.team1_score = data.get('team1_score')\n db_obj.team2_score = data.get('team2_score')\n db_obj.save(update_fields=['team1_score', 'team2_score'])\n\n match.status = status\n match.save(update_fields=['status'])\n if match.type == 'super12':\n update_standings(db_obj, status)\n settle_bets(db_obj)\n return f\"Match Updated\"\n elif winner_valid(**data):\n match.status = status\n match.save(update_fields=['status'])\n\n db_obj.team1_score = data.get('team1_score')\n db_obj.team2_score = data.get('team2_score')\n db_obj.winner = data.get('winner')\n db_obj.win_type = data.get('win_type')\n db_obj.win_margin = data.get('win_margin')\n db_obj.save()\n\n if match.type == 'super12':\n update_standings(db_obj, status)\n settle_bets(db_obj)\n return f\"Match Updated\"\n else:\n return f\"Set all attributes for the win\"\n","sub_path":"apps/main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"215057663","text":"from tkinter import *\nfrom PIL import ImageTk, Image\nimport BoardAndPieces\n\nglobal white_to_move\nglobal piece_selected\nglobal indications\nglobal board_map\nglobal game_state\nglobal possible_moves\nglobal announcer\nglobal announcement\n\nannouncement = \"Press the Start button\\n to begin the game\"\npiece_selected = None\n\nwhite_to_move = True\nmove_number = 1\ngame_state = \"PREP\"\n\nindications = []\nboard_map = []\n\nroot = Tk()\nroot.title('Chess Simulation')\nroot.config(bg='#404040')\n# root.option_add('*Font', '19')\nscreen_width = root.winfo_screenwidth()\nscreen_height = root.winfo_screenheight()\nroot.geometry(str(int(screen_width * 0.7)) + 'x' + str(int(screen_height * 0.7)) + '+200+100')\nroot.resizable(False, False)\n\nnew_game_button = Button(\n master=root,\n text=\"Start New Game\",\n relief=RAISED,\n width=20,\n height=3,\n)\nchess_board = BoardAndPieces.Board()\n\nnew_game_button.place(x=(screen_width * 0.7 - 300), y=40)\nsquare_size = int(screen_height * 0.7) / 8 * root.winfo_height()\ninstructions = \"Click the top button to start \\n or reset the game.To move a piece, click it \\n\" + \\\n \"first to view its legal \" + \\\n \"moves. \\nThen click the green indicators \\nto move the piece.\"\n\nannouncer_frame = Frame(master=root, relief=RAISED, background=\"white\", width=24, height=3)\nannouncer_frame.place(x=(screen_width * 0.7 - 300) - 20, y=120)\nannouncer_banner = Label(announcer_frame, text=announcement, width=24, height=3, bg=\"#34b356\")\nannouncer_banner.pack()\nscore_board = Label(master=root, text=\"Lorem ipsum\", width=30, height=16)\nscore_board.place(x=(screen_width * 0.7 - 300) - 48, y=200)\ninstructions_card = Label(master=root, text=instructions, width=30, height=6)\ninstructions_card.place(x=(screen_width * 0.7 - 300) - 48, y=500)\n\nblack_color = \"#b56b60\"\n\nis_white = False\n# Generating the chess board appearance\nfor y in range(8):\n for x in range(8):\n if is_white:\n square = Frame(\n master=root,\n relief=RAISED,\n background=\"white\",\n width=square_size,\n height=square_size\n )\n square.grid(row=7 - y, column=x)\n else:\n square = Frame(\n master=root,\n relief=RAISED,\n background=black_color,\n width=square_size,\n height=square_size\n )\n square.grid(row=7 - y, column=x)\n\n is_white = not is_white\n if x == 7:\n is_white = not is_white\n\n# obtaining chess images, converting to TkImage, resizing them, putting them in Label widgets,\n# and sticking the label widgets onto the board locations\nblack_queen_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/black_queen.png'\nblack_queen_image = Image.open(black_queen_filepath)\nblack_king_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/black_king.png'\nblack_king_image = Image.open(black_king_filepath)\nblack_bishop_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/black_bishop.png'\nblack_bishop_image = Image.open(black_bishop_filepath)\nblack_knight_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/black_knight.png'\nblack_knight_image = Image.open(black_knight_filepath)\nblack_rook_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/black_rook.png'\nblack_rook_image = Image.open(black_rook_filepath)\nblack_pawn_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/black_pawn.png'\nblack_pawn_image = Image.open(black_pawn_filepath)\n\n# Resize the image using resize() method\nresized_black_queen = black_queen_image.resize((square_size - 10, square_size - 10))\nresized_black_king = black_king_image.resize((square_size - 10, square_size - 10))\nresized_black_bishop = black_bishop_image.resize((square_size - 10, square_size - 10))\nresized_black_knight = black_knight_image.resize((square_size - 10, square_size - 10))\nresized_black_rook = black_rook_image.resize((square_size - 10, square_size - 10))\nresized_black_pawn = black_pawn_image.resize((square_size - 10, square_size - 10))\n\ntk_black_queen = ImageTk.PhotoImage(resized_black_queen)\ntk_black_king = ImageTk.PhotoImage(resized_black_king)\ntk_black_bishop = ImageTk.PhotoImage(resized_black_bishop)\ntk_black_knight = ImageTk.PhotoImage(resized_black_knight)\ntk_black_rook = ImageTk.PhotoImage(resized_black_rook)\ntk_black_pawn = ImageTk.PhotoImage(resized_black_pawn)\n\n# create label and add resize image\n\nb_rook1 = Label(master=root, image=tk_black_rook)\nb_rook1.image = tk_black_rook\nb_rook1.grid(row=0, column=7)\nb_rook1.config(bg=black_color)\n\nb_knight1 = Label(master=root, image=tk_black_knight)\nb_knight1.image = tk_black_knight\nb_knight1.grid(row=0, column=6)\nb_knight1.config(bg=\"white\")\n\nb_bishop1 = Label(master=root, image=tk_black_bishop)\nb_bishop1.image = tk_black_bishop\nb_bishop1.grid(row=0, column=5)\nb_bishop1.config(bg=black_color)\n\nb_king = Label(master=root, image=tk_black_king)\nb_king.image = tk_black_king\nb_king.grid(row=0, column=4)\nb_king.config(bg=\"white\")\n\nb_queen = Label(master=root, image=tk_black_queen)\nb_queen.image = tk_black_queen\nb_queen.grid(row=0, column=3)\nb_queen.config(bg=black_color)\n\nb_bishop2 = Label(master=root, image=tk_black_bishop)\nb_bishop2.image = tk_black_bishop\nb_bishop2.grid(row=0, column=2)\nb_bishop2.config(bg=\"white\")\n\nb_knight2 = Label(master=root, image=tk_black_knight)\nb_knight2.image = tk_black_knight\nb_knight2.grid(row=0, column=1)\nb_knight2.config(bg=black_color)\n\nb_rook2 = Label(master=root, image=tk_black_rook)\nb_rook2.image = tk_black_rook\nb_rook2.grid(row=0, column=0)\nb_rook2.config(bg=\"white\")\n\nb_h_pawn = Label(master=root, image=tk_black_pawn)\nb_h_pawn.image = tk_black_pawn\nb_h_pawn.grid(row=1, column=7)\nb_h_pawn.config(bg=\"white\")\n\nb_g_pawn = Label(master=root, image=tk_black_pawn)\nb_g_pawn.image = tk_black_pawn\nb_g_pawn.grid(row=1, column=6)\nb_g_pawn.config(bg=black_color)\n\nb_f_pawn = Label(master=root, image=tk_black_pawn)\nb_f_pawn.image = tk_black_pawn\nb_f_pawn.grid(row=1, column=5)\nb_f_pawn.config(bg=\"white\")\n\nb_e_pawn = Label(master=root, image=tk_black_pawn)\nb_e_pawn.image = tk_black_pawn\nb_e_pawn.grid(row=1, column=4)\nb_e_pawn.config(bg=black_color)\n\nb_d_pawn = Label(master=root, image=tk_black_pawn)\nb_d_pawn.image = tk_black_pawn\nb_d_pawn.grid(row=1, column=3)\nb_d_pawn.config(bg=\"white\")\n\nb_c_pawn = Label(master=root, image=tk_black_pawn)\nb_c_pawn.image = tk_black_pawn\nb_c_pawn.grid(row=1, column=2)\nb_c_pawn.config(bg=black_color)\n\nb_b_pawn = Label(master=root, image=tk_black_pawn)\nb_b_pawn.image = tk_black_pawn\nb_b_pawn.grid(row=1, column=1)\nb_b_pawn.config(bg=\"white\")\n\nb_a_pawn = Label(master=root, image=tk_black_pawn)\nb_a_pawn.image = tk_black_pawn\nb_a_pawn.grid(row=1, column=0)\nb_a_pawn.config(bg=black_color)\n\nwhite_queen_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/white_queen.png'\nwhite_queen_image = Image.open(white_queen_filepath)\nwhite_king_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/white_king.png'\nwhite_king_image = Image.open(white_king_filepath)\nwhite_bishop_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/white_bishop.png'\nwhite_bishop_image = Image.open(white_bishop_filepath)\nwhite_knight_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/white_knight.png'\nwhite_knight_image = Image.open(white_knight_filepath)\nwhite_rook_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/white_rook.png'\nwhite_rook_image = Image.open(white_rook_filepath)\nwhite_pawn_filepath = '/Users/danielhuang/PycharmProjects/ChessSimulation/venv/lib/images/white_pawn.png'\nwhite_pawn_image = Image.open(white_pawn_filepath)\n\n# Resize the image using resize() method\nresized_white_queen = white_queen_image.resize((square_size - 10, square_size - 10))\nresized_white_king = white_king_image.resize((square_size - 10, square_size - 10))\nresized_white_bishop = white_bishop_image.resize((square_size - 10, square_size - 10))\nresized_white_knight = white_knight_image.resize((square_size - 10, square_size - 10))\nresized_white_rook = white_rook_image.resize((square_size - 10, square_size - 10))\nresized_white_pawn = white_pawn_image.resize((square_size - 10, square_size - 10))\n\ntk_white_queen = ImageTk.PhotoImage(resized_white_queen)\ntk_white_king = ImageTk.PhotoImage(resized_white_king)\ntk_white_bishop = ImageTk.PhotoImage(resized_white_bishop)\ntk_white_knight = ImageTk.PhotoImage(resized_white_knight)\ntk_white_rook = ImageTk.PhotoImage(resized_white_rook)\ntk_white_pawn = ImageTk.PhotoImage(resized_white_pawn)\n\n# create label and add resize image\n\nw_rook1 = Label(master=root, image=tk_white_rook)\nw_rook1.image = tk_white_rook\nw_rook1.grid(row=7, column=0)\nw_rook1.config(bg=black_color)\n\nw_knight1 = Label(master=root, image=tk_white_knight)\nw_knight1.image = tk_white_knight\nw_knight1.grid(row=7, column=1)\nw_knight1.config(bg=\"white\")\n\nw_bishop1 = Label(master=root, image=tk_white_bishop)\nw_bishop1.image = tk_white_bishop\nw_bishop1.grid(row=7, column=2)\nw_bishop1.config(bg=black_color)\n\nw_queen = Label(master=root, image=tk_white_queen)\nw_queen.image = tk_white_queen\nw_queen.grid(row=7, column=3)\nw_queen.config(bg=\"white\")\n\nw_king = Label(master=root, image=tk_white_king)\nw_king.image = tk_white_king\nw_king.grid(row=7, column=4)\nw_king.config(bg=black_color)\n\nw_bishop2 = Label(master=root, image=tk_white_bishop)\nw_bishop2.image = tk_white_bishop\nw_bishop2.grid(row=7, column=5)\nw_bishop2.config(bg=\"white\")\n\nw_knight2 = Label(master=root, image=tk_white_knight)\nw_knight2.image = tk_white_knight\nw_knight2.grid(row=7, column=6)\nw_knight2.config(bg=black_color)\n\nw_rook2 = Label(master=root, image=tk_white_rook)\nw_rook2.image = tk_white_rook\nw_rook2.grid(row=7, column=7)\nw_rook2.config(bg=\"white\")\n\nw_h_pawn = Label(master=root, image=tk_white_pawn)\nw_h_pawn.image = tk_white_pawn\nw_h_pawn.grid(row=6, column=7)\nw_h_pawn.config(bg=black_color)\n\nw_g_pawn = Label(master=root, image=tk_white_pawn)\nw_g_pawn.image = tk_white_pawn\nw_g_pawn.grid(row=6, column=6)\nw_g_pawn.config(bg='white')\n\nw_f_pawn = Label(master=root, image=tk_white_pawn)\nw_f_pawn.image = tk_white_pawn\nw_f_pawn.grid(row=6, column=5)\nw_f_pawn.config(bg=black_color)\n\nw_e_pawn = Label(master=root, image=tk_white_pawn)\nw_e_pawn.image = tk_white_pawn\nw_e_pawn.grid(row=6, column=4)\nw_e_pawn.config(bg='white')\n\nw_d_pawn = Label(master=root, image=tk_white_pawn)\nw_d_pawn.image = tk_white_pawn\nw_d_pawn.grid(row=6, column=3)\nw_d_pawn.config(bg=black_color)\n\nw_c_pawn = Label(master=root, image=tk_white_pawn)\nw_c_pawn.image = tk_white_pawn\nw_c_pawn.grid(row=6, column=2)\nw_c_pawn.config(bg=\"white\")\n\nw_b_pawn = Label(master=root, image=tk_white_pawn)\nw_b_pawn.image = tk_white_pawn\nw_b_pawn.grid(row=6, column=1)\nw_b_pawn.config(bg=black_color)\n\nw_a_pawn = Label(master=root, image=tk_white_pawn)\nw_a_pawn.image = tk_white_pawn\nw_a_pawn.grid(row=6, column=0)\nw_a_pawn.config(bg=\"white\")\n\nblack_piece_images = [b_h_pawn, b_g_pawn, b_f_pawn, b_e_pawn, b_d_pawn, b_c_pawn, b_b_pawn, b_a_pawn,\n b_rook1, b_knight1, b_bishop1, b_king, b_queen, b_bishop2, b_knight2, b_rook2]\nwhite_piece_images = [w_a_pawn, w_b_pawn, w_c_pawn, w_d_pawn, w_e_pawn, w_f_pawn, w_g_pawn, w_h_pawn,\n w_rook1, w_knight1, w_bishop1, w_queen, w_king, w_bishop2, w_knight2, w_rook2]\n\nfor index in range(8):\n board_map.append([None, None, None, None, None, None, None, None])\n\n\ndef evaluate_board():\n for x_clear in range(8):\n for y_clear in range(len(board_map)):\n board_map[x_clear][y_clear] = None\n for piece_a in chess_board.white_pieces:\n if not piece_a.captured:\n board_map[piece_a.x][piece_a.y] = piece_a\n for piece_b in chess_board.black_pieces:\n if not piece_b.captured:\n board_map[piece_b.x][piece_b.y] = piece_b\n\n\ndef find_checks(sides):\n checks = []\n pieces_to_check = []\n if sides:\n pieces_to_check = chess_board.black_pieces\n else:\n pieces_to_check = chess_board.white_pieces\n\n for piece in pieces_to_check:\n if not piece.captured:\n if piece.identity == \"Queen\" or piece.identity == \"Rook\":\n for move_right in range(1, 8):\n if piece.x + move_right > 7:\n break\n given_piece = board_map[piece.x + move_right][piece.y]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n checks.append(piece)\n break\n else:\n break\n else:\n break\n for move_left in range(1, 8):\n if piece.x - move_left < 0:\n break\n given_piece = board_map[piece.x - move_left][piece.y]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n\n checks.append(piece)\n break\n else:\n break\n else:\n break\n for move_up in range(1, 8):\n if piece.y + move_up > 7:\n break\n given_piece = board_map[piece.x][piece.y + move_up]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n\n checks.append(piece)\n break\n else:\n break\n else:\n break\n for move_down in range(1, 8):\n if piece.y - move_down < 0:\n break\n given_piece = board_map[piece.x][piece.y - move_down]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n\n checks.append(piece)\n break\n else:\n break\n else:\n break\n if piece.identity == \"Queen\" or piece.identity == \"Bishop\":\n for move_up_right in range(1, 8):\n if piece.x + move_up_right > 7 or piece.y + move_up_right > 7:\n break\n given_piece = board_map[piece.x + move_up_right][piece.y + move_up_right]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n\n checks.append(piece)\n break\n else:\n break\n else:\n break\n for move_up_left in range(1, 8):\n if piece.x - move_up_left < 0 or piece.y + move_up_left > 7:\n break\n given_piece = board_map[piece.x - move_up_left][piece.y + move_up_left]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n\n checks.append(piece)\n break\n else:\n break\n else:\n break\n for move_down_right in range(1, 8):\n if piece.x + move_down_right > 7 or piece.y - move_down_right < 0:\n break\n given_piece = board_map[piece.x + move_down_right][piece.y - move_down_right]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n checks.append(piece)\n break\n else:\n break\n else:\n break\n for move_down_left in range(1, 8):\n if piece.x - move_down_left < 0 or piece.y - move_down_left < 0:\n break\n given_piece = board_map[piece.x - move_down_left][piece.y - move_down_left]\n if given_piece is not None:\n if given_piece.side == sides:\n if given_piece.identity == \"King\":\n checks.append(piece)\n break\n else:\n break\n else:\n break\n elif piece.identity == \"Knight\":\n jumps = [[1, 2], [-1, 2], [2, 1], [-2, 1], [2, -1], [-2, -1], [1, -2], [-1, -2]]\n for jump in jumps:\n given_piece = None\n if 0 <= piece.x + jump[0] <= 7 and 0 <= piece.y + jump[1] <= 7:\n given_piece = board_map[piece.x + jump[0]][piece.y + jump[1]]\n if given_piece is not None:\n if given_piece.side == sides and given_piece.identity == \"King\":\n checks.append(piece)\n elif piece.identity == \"Pawn\":\n jumps = []\n if sides:\n jumps = [[1, -1], [-1, -1]]\n else:\n jumps = [[1, 1], [-1, 1]]\n for jump in jumps:\n given_piece = None\n if 0 <= piece.x + jump[0] <= 7 and 0 <= piece.y + jump[1] <= 7:\n given_piece = board_map[piece.x + jump[0]][piece.y + jump[1]]\n if given_piece is not None:\n if given_piece.side == sides and given_piece.identity == \"King\":\n checks.append(piece)\n return checks\n\n\ndef update_board():\n # The following for loop displays all the widget pieces based on their location\n for index in range(len(chess_board.white_pieces)):\n if not chess_board.white_pieces[index].captured:\n white_piece_images[index].grid(row=7 - chess_board.white_pieces[index].y,\n column=chess_board.white_pieces[index].x)\n else:\n white_piece_images[index].place(x=1000, y=1000)\n\n if not chess_board.black_pieces[index].captured:\n black_piece_images[index].grid(row=7 - chess_board.black_pieces[index].y,\n column=chess_board.black_pieces[index].x)\n else:\n black_piece_images[index].place(x=4000, y=4000)\n\n if (chess_board.white_pieces[index].x % 2 == 1 and chess_board.white_pieces[index].y % 2 == 0) \\\n or (chess_board.white_pieces[index].x % 2 == 0 and chess_board.white_pieces[index].y % 2 == 1):\n white_piece_images[index].config(bg=\"white\")\n else:\n white_piece_images[index].config(bg=black_color)\n if (chess_board.black_pieces[index].x % 2 == 1 and chess_board.black_pieces[index].y % 2 == 0) \\\n or (chess_board.black_pieces[index].x % 2 == 0 and chess_board.black_pieces[index].y % 2 == 1):\n black_piece_images[index].config(bg=\"white\")\n else:\n black_piece_images[index].config(bg=black_color)\n\n\ndef find_legal_moves(given_piece):\n legal_moves = []\n if given_piece.captured:\n return legal_moves\n if given_piece.identity == \"Queen\" or given_piece.identity == \"Rook\":\n for move_right in range(1, 8):\n if given_piece.x + move_right > 7:\n break\n elif board_map[given_piece.x + move_right][given_piece.y] is None:\n legal_moves.append([move_right, 0])\n else:\n if board_map[given_piece.x + move_right][given_piece.y].side != given_piece.side:\n legal_moves.append([move_right, 0])\n break\n else:\n break\n for move_left in range(1, 8):\n if given_piece.x - move_left < 0:\n break\n elif board_map[given_piece.x - move_left][given_piece.y] is None:\n legal_moves.append([move_left * -1, 0])\n else:\n if board_map[given_piece.x - move_left][given_piece.y].side != given_piece.side:\n legal_moves.append([move_left * -1, 0])\n break\n else:\n break\n for move_up in range(1, 8):\n if given_piece.y + move_up > 7:\n break\n elif board_map[given_piece.x][given_piece.y + move_up] is None:\n legal_moves.append([0, move_up])\n else:\n if board_map[given_piece.x][given_piece.y + move_up].side != given_piece.side:\n legal_moves.append([0, move_up])\n break\n else:\n break\n for move_down in range(1, 8):\n if given_piece.y - move_down < 0:\n break\n elif board_map[given_piece.x][given_piece.y - move_down] is None:\n legal_moves.append([0, move_down * -1])\n else:\n if board_map[given_piece.x][given_piece.y - move_down].side != given_piece.side:\n legal_moves.append([0, move_down * -1])\n break\n else:\n break\n if given_piece.identity == \"Queen\" or given_piece.identity == \"Bishop\":\n for move_up_right in range(1, 8):\n if given_piece.x + move_up_right > 7 or given_piece.y + move_up_right > 7:\n break\n elif board_map[given_piece.x + move_up_right][given_piece.y + move_up_right] is None:\n legal_moves.append([move_up_right, move_up_right])\n else:\n if board_map[given_piece.x + move_up_right][given_piece.y + move_up_right].side != given_piece.side:\n legal_moves.append([move_up_right, move_up_right])\n break\n else:\n break\n for move_up_left in range(1, 8):\n if given_piece.x - move_up_left < 0 or given_piece.y + move_up_left > 7:\n break\n elif board_map[given_piece.x - move_up_left][given_piece.y + move_up_left] is None:\n legal_moves.append([move_up_left * -1, move_up_left])\n else:\n if board_map[given_piece.x - move_up_left][given_piece.y + move_up_left].side != given_piece.side:\n legal_moves.append([move_up_left * -1, move_up_left])\n break\n else:\n break\n for move_down_right in range(1, 8):\n if given_piece.x + move_down_right > 7 or given_piece.y - move_down_right < 0:\n break\n elif board_map[given_piece.x + move_down_right][given_piece.y - move_down_right] is None:\n legal_moves.append([move_down_right, move_down_right * -1])\n else:\n if board_map[given_piece.x + move_down_right][given_piece.y - move_down_right].side != given_piece.side:\n legal_moves.append([move_down_right, move_down_right * -1])\n break\n else:\n break\n for move_down_left in range(1, 8):\n if given_piece.x - move_down_left < 0 or given_piece.y - move_down_left < 0:\n break\n elif board_map[given_piece.x - move_down_left][given_piece.y - move_down_left] is None:\n legal_moves.append([move_down_left * -1, move_down_left * -1])\n else:\n if board_map[given_piece.x - move_down_left][given_piece.y - move_down_left].side != given_piece.side:\n legal_moves.append([move_down_left * -1, move_down_left * -1])\n break\n else:\n break\n elif given_piece.identity == \"Knight\":\n jumps = [[1, 2], [-1, 2], [2, 1], [-2, 1], [2, -1], [-2, -1], [1, -2], [-1, -2]]\n for jump in jumps:\n if 0 <= given_piece.x + jump[0] <= 7 and 0 <= given_piece.y + jump[1] <= 7:\n if board_map[given_piece.x + jump[0]][given_piece.y + jump[1]] is None:\n legal_moves.append([jump[0], jump[1]])\n elif board_map[given_piece.x + jump[0]][given_piece.y + jump[1]] is not None and \\\n board_map[given_piece.x + jump[0]][given_piece.y + jump[1]].side != given_piece.side:\n legal_moves.append([jump[0], jump[1]])\n elif given_piece.identity == \"Pawn\":\n step = 1\n if not given_piece.side:\n step = -1\n\n if given_piece.x - 1 >= 0:\n if board_map[given_piece.x - 1][given_piece.y + step] is not None:\n if board_map[given_piece.x - 1][given_piece.y + step].side != given_piece.side:\n legal_moves.append([-1, step])\n if given_piece.x + 1 <= 7:\n if board_map[given_piece.x + 1][given_piece.y + step] is not None:\n if board_map[given_piece.x + 1][given_piece.y + step].side != given_piece.side:\n legal_moves.append([1, step])\n if board_map[given_piece.x][given_piece.y + step] is None:\n legal_moves.append([0, step])\n if board_map[given_piece.x][given_piece.y + step] is None and \\\n board_map[given_piece.x][given_piece.y + step * 2] is None:\n if (given_piece.side and given_piece.y == 1) or (not given_piece.side and given_piece.y == 6):\n legal_moves.append([0, step * 2])\n elif given_piece.identity == \"King\":\n if not given_piece.has_moved:\n given_rook1 = None\n given_rook2 = None\n if given_piece.side:\n given_rook1 = chess_board.rook1_white\n given_rook2 = chess_board.rook2_white\n else:\n given_rook1 = chess_board.rook1_black\n given_rook2 = chess_board.rook2_black\n if given_piece.side and not given_rook2.has_moved and board_map[given_piece.x + 1][given_piece.y] \\\n is None and board_map[given_piece.x + 2][given_piece.y] is None:\n legal_moves.append([\"castle kingside\"])\n elif not given_piece.side and not given_rook1.has_moved and board_map[given_piece.x + 1][given_piece.y] \\\n is None and board_map[given_piece.x + 2][given_piece.y] is None:\n legal_moves.append([\"castle kingside\"])\n\n if given_piece.side and not given_rook1.has_moved and board_map[given_piece.x - 1][given_piece.y] \\\n is None and board_map[given_piece.x - 2][given_piece.y] is None and \\\n board_map[given_piece.x - 3][given_piece.y] is None:\n legal_moves.append([\"castle queenside\"])\n elif not given_piece.side and not given_rook2.has_moved and board_map[given_piece.x - 1][given_piece.y] \\\n is None and board_map[given_piece.x - 2][given_piece.y] is None and \\\n board_map[given_piece.x - 3][given_piece.y] is None:\n legal_moves.append([\"castle queenside\"])\n\n jumps = [[1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, 1], [1, -1], [-1, -1]]\n for jump in jumps:\n if 0 <= given_piece.x + jump[0] <= 7 and 0 <= given_piece.y + jump[1] <= 7:\n if board_map[given_piece.x + jump[0]][given_piece.y + jump[1]] is None:\n legal_moves.append([jump[0], jump[1]])\n elif board_map[given_piece.x + jump[0]][given_piece.y + jump[1]] is not None and \\\n board_map[given_piece.x + jump[0]][given_piece.y + jump[1]].side != given_piece.side:\n legal_moves.append([jump[0], jump[1]])\n\n moves_to_remove = []\n if given_piece.identity == \"King\":\n in_check = find_checks(given_piece.side)\n if len(in_check) > 0:\n if \"castle kingside\" in legal_moves:\n legal_moves.remove(\"castle kingside\")\n if \"castle queenside\" in legal_moves:\n legal_moves.remove(\"castle queenside\")\n if \"castle kingside\" in legal_moves:\n given_piece.x += 1\n evaluate_board()\n check1 = find_checks(given_piece.side)\n if len(check1) > 0:\n legal_moves.remove(\"castle kingside\")\n given_piece.x += 1\n evaluate_board()\n check2 = find_checks(given_piece.side)\n if len(check2) > 0 and \"castle kingside\" in legal_moves:\n legal_moves.remove(\"castle kingside\")\n given_piece.x -= 2\n evaluate_board()\n if \"castle queenside\" in legal_moves:\n given_piece.x -= 1\n evaluate_board()\n check1 = find_checks(given_piece.side)\n if len(check1) > 0:\n legal_moves.remove(\"castle queenside\")\n given_piece.x -= 1\n evaluate_board()\n check2 = find_checks(given_piece.side)\n if len(check2) > 0 and \"castle queenside\" in legal_moves:\n legal_moves.remove(\"castle queenside\")\n given_piece.x += 2\n evaluate_board()\n pass\n has_castling = []\n if ['castle kingside'] in legal_moves:\n has_castling.append(['castle kingside'])\n legal_moves.remove(['castle kingside'])\n if ['castle queenside'] in legal_moves:\n has_castling.append(['castle queenside'])\n legal_moves.remove(['castle queenside'])\n for move in legal_moves:\n given_piece.x += move[0]\n given_piece.y += move[1]\n evaluate_board()\n attacking_pieces = find_checks(given_piece.side)\n if len(attacking_pieces) > 0:\n moves_to_remove.append(move)\n for attacking_piece in attacking_pieces:\n if given_piece.x == attacking_piece.x and given_piece.y == attacking_piece.y and \\\n len(attacking_pieces) - 1 <= 0:\n moves_to_remove.remove(move)\n given_piece.x -= move[0]\n given_piece.y -= move[1]\n evaluate_board()\n\n for removed_move in moves_to_remove:\n legal_moves.remove(removed_move)\n\n legal_moves.extend(has_castling)\n return legal_moves\n\n\nevaluate_board()\nupdate_board()\n\n\ndef display_legal_moves(piece_to_move):\n global piece_selected\n global indications\n global possible_moves\n castling = []\n possible_moves = find_legal_moves(piece_to_move)\n piece_selected = piece_to_move\n while len(indications) > 0:\n indications[-1].destroy()\n indications.pop()\n if len(possible_moves) < 1:\n piece_selected = None\n\n for legal_move in range(len(possible_moves)):\n if len(possible_moves[legal_move]) == 2:\n indications.append(Label(master=root, bg=\"#43a159\", width=2, height=1))\n indications[legal_move].grid(row=7 - piece_selected.y - possible_moves[legal_move][1],\n column=piece_selected.x + possible_moves[legal_move][0])\n elif len(possible_moves[legal_move]) == 1:\n if possible_moves[legal_move][0] == \"castle kingside\":\n indications.append(Label(master=root, bg=\"#43a159\", width=2, height=1))\n indications[legal_move].grid(row=7 - piece_selected.y, column=piece_selected.x + 2)\n elif possible_moves[legal_move][0] == \"castle queenside\":\n indications.append(Label(master=root, bg=\"#43a159\", width=2, height=1))\n indications[legal_move].grid(row=7 - piece_selected.y, column=piece_selected.x - 2)\n\n\ndef make_move(piece_to_move, move_x, move_y):\n global white_to_move\n global piece_selected\n global possible_moves\n global indications\n enemy_pieces = []\n if piece_to_move.side:\n enemy_pieces = chess_board.black_pieces\n else:\n enemy_pieces = chess_board.white_pieces\n\n if piece_to_move.identity == \"King\" and move_x == 69 and move_y == 69:\n piece_to_move.x += 2\n if piece_to_move.side:\n chess_board.rook2_white.x -= 2\n else:\n chess_board.rook1_black.x -= 2\n elif piece_to_move.identity == \"King\" and move_x == 420 and move_y == 420:\n piece_to_move.x -= 2\n if piece_to_move.side:\n chess_board.rook1_white.x += 3\n else:\n chess_board.rook2_black.x += 3\n else:\n for captured_piece in enemy_pieces:\n if piece_to_move.x + move_x == captured_piece.x and piece_to_move.y + move_y == captured_piece.y and \\\n not captured_piece.captured:\n captured_piece.captured = True\n captured_piece.x = 8\n captured_piece.y = 8\n break\n piece_to_move.x += move_x\n piece_to_move.y += move_y\n\n if piece_to_move.identity == \"Pawn\":\n if (piece_to_move.side and piece_to_move.y == 7) or (not piece_to_move.side and piece_to_move.y == 0):\n piece_to_move.identity = \"Queen\"\n\n piece_to_move.has_moved = True\n\n evaluate_board()\n update_board()\n white_to_move = not white_to_move\n while len(indications) > 0:\n indications[-1].destroy()\n indications.pop()\n possible_moves = []\n update_status(white_to_move)\n\n\ndef test_click(event):\n global white_to_move\n global piece_selected\n global possible_moves\n reset = True\n mouse_x = event.x_root - root.winfo_x()\n mouse_y = event.y_root - root.winfo_y()\n # print(\"mouse click location: \" + str(mouse_x) + \", \" + str(mouse_y))\n\n if game_state == \"PLAYING\":\n if white_to_move:\n pieces_to_move = chess_board.white_pieces\n else:\n pieces_to_move = chess_board.black_pieces\n\n if piece_selected is not None:\n p_x = square_size * piece_selected.x\n p_y = square_size * (7 - piece_selected.y)\n # this checks if the selected piece was clicked again, in which it should de-select itself\n if p_x + square_size > mouse_x > p_x and p_y + square_size + 24 > mouse_y > 24 + p_y:\n while len(indications) > 0:\n indications[-1].destroy()\n indications.pop()\n piece_selected = None\n reset = False\n\n # this checks if one of the legal moves was selected, in which the piece should move\n castling = []\n if [\"castle kingside\"] in possible_moves:\n castling.append([\"castle kingside\"])\n possible_moves.remove([\"castle kingside\"])\n\n if [\"castle queenside\"] in possible_moves:\n castling.append([\"castle queenside\"])\n possible_moves.remove([\"castle queenside\"])\n for move in possible_moves:\n if piece_selected is not None and \\\n square_size * (piece_selected.x + move[0]) + square_size > mouse_x > square_size \\\n * (piece_selected.x + move[0]) and square_size * (7 - (piece_selected.y + move[1])) \\\n + square_size + 24 > mouse_y > 24 + square_size * (7 - (piece_selected.y + move[1])):\n make_move(piece_selected, move[0], move[1])\n piece_selected = None\n reset = False\n break\n if [\"castle kingside\"] in castling and piece_selected is not None and \\\n square_size * (piece_selected.x + 2) + square_size > mouse_x > square_size \\\n * (piece_selected.x + 2) and square_size * (7 - piece_selected.y) \\\n + square_size + 24 > mouse_y > 24 + square_size * (7 - piece_selected.y):\n make_move(piece_selected, 69, 69)\n piece_selected = None\n reset = False\n if [\"castle queenside\"] in castling and piece_selected is not None and \\\n square_size * (piece_selected.x - 2) + square_size > mouse_x > square_size \\\n * (piece_selected.x - 2) and square_size * (7 - piece_selected.y) \\\n + square_size + 24 > mouse_y > 24 + square_size * (7 - piece_selected.y):\n make_move(piece_selected, 420, 420)\n piece_selected = None\n reset = False\n if reset:\n for clicked_piece in pieces_to_move:\n if square_size * clicked_piece.x + square_size > mouse_x > square_size * clicked_piece.x and \\\n square_size * (7 - clicked_piece.y) + square_size + 24 > mouse_y > 24 + \\\n square_size * (7 - clicked_piece.y):\n if clicked_piece != piece_selected:\n display_legal_moves(clicked_piece)\n\n legal_moves2 = find_legal_moves(clicked_piece)\n # print(str(legal_moves2))\n reset = False\n break\n if reset:\n while len(indications) > 0:\n indications[-1].destroy()\n indications.pop()\n piece_selected = None\n\n\ndef update_status(whose_move):\n global game_state\n global white_to_move\n global announcement\n if whose_move:\n announcement = \"White to move\"\n announcer_banner.config(fg=\"black\", bg=\"white\")\n else:\n announcement = \"Black to move\"\n announcer_banner.config(fg=\"white\", bg=\"black\")\n moves = 0\n if white_to_move:\n for white_piece in chess_board.white_pieces:\n if len(find_legal_moves(white_piece)) > 0:\n moves += 1\n break\n if moves < 1:\n conclude_game()\n if len(find_checks(True)) > 0:\n announcement = \"Black wins by checkmate!\"\n else:\n announcement = \"Draw by stalemate\"\n else:\n for black_piece in chess_board.black_pieces:\n if len(find_legal_moves(black_piece)) > 0:\n moves += 1\n break\n if moves < 1:\n conclude_game()\n if len(find_checks(False)) > 0:\n announcement = \"White wins by checkmate!\"\n else:\n announcement = \"Draw by stalemate\"\n announcer_banner.config(text=announcement)\n\n\ndef control_game():\n global game_state\n global move_number\n global possible_moves\n global indications\n global piece_selected\n global white_to_move\n global announcement\n if game_state == \"PREP\":\n game_state = \"PLAYING\"\n announcement = \"White to move\"\n announcer_banner.config(fg=\"black\", bg=\"white\")\n new_game_button.config(text=\"Reset\")\n announcer_banner.config(text=announcement)\n return\n if game_state == \"PLAYING\" or game_state == \"CONCLUDED\":\n game_state = \"PREP\"\n move_number = 1\n possible_moves = []\n indications = []\n piece_selected = None\n white_to_move = True\n chess_board.set_up_pieces()\n evaluate_board()\n update_board()\n new_game_button.config(text=\"Start New Game\")\n new_game_button.config(bg=\"#32ad10\")\n announcement = \"Press the Start button\\n to begin the game\"\n announcer_banner.config(text=announcement, bg=\"#34b356\", fg=\"black\")\n return\n\n\ndef conclude_game():\n global game_state\n game_state = \"CONCLUDED\"\n new_game_button.config(text=\"Play Again\")\n\n\nnew_game_button.config(command=lambda: control_game())\n\nroot.bind(\"\", test_click)\n\nroot.mainloop()\n","sub_path":"GameAndGUI.py","file_name":"GameAndGUI.py","file_ext":"py","file_size_in_byte":40418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"345741476","text":"\ndef csv_writer(data, path):\n \"\"\"\n Write data to a CSV file path\n \"\"\"\n with open(path, \"w\", newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n for line in data:\n writer.writerow(line)\n\ndef dict_to_csv_writer(myDict, path):\n First = True\n textData =\"\"\n Data = []\n for key in myDict:\n D = myDict[key]\n if First:\n First = False\n x = D.keys()\n Data.append(x)\n textData += \",\".join(map(str, x)) +\"/n\"\n y = D.values()\n Data.append(y)\n textData += \",\".join(map(str, y)) +\"/n\"\n \"\"\"\n Write data to a CSV file path\n \"\"\"\n with open(path, \"w\", newline='') as csv_file:\n writer = csv.writer(csv_file, delimiter=',')\n for line in Data:\n writer.writerow(line)\n\ndef csv_dict_reader(file_obj):\n firstTime =True\n \"\"\"\n Read a CSV file using csv.DictReader\n \"\"\"\n myList = []\n reader = csv.DictReader(file_obj, delimiter=',')\n\n for line in reader:\n d =[]\n keys, values = zip(*line.items())\n for i, k in enumerate(values):\n d.append(k)\n myList.append(d)\n return myList\n\ndef csv_to_dictionery(file_obj):\n firstTime =True\n \"\"\"\n Read a CSV file using csv.DictReader\n \"\"\"\n myList = {}\n reader = csv.DictReader(file_obj, delimiter=',')\n\n for line in reader:\n\n keys, values = zip(*line.items())\n myList[values[0]] = dict(line)\n return myList\n\nif __name__ == '__main__':\n import os, sys, csv, re\n from datetime import datetime, time\n from shutil import copyfile\n\n # After commiting to SVN the commit info is collected in a new sublime text fil and saved as CSV which inturn is used here\n File_1_root = '/Users/anandihalli/Documents/01_Work/brazil/Reports'\n File_1_name = 'xbr_SVN_commit.csv' # list from art server\n File_1_path = os.path.join(File_1_root , File_1_name)\n\n # This is the CSV containg File to be commited its target path and soruce path\n File_2_root = '/Users/anandihalli/Documents/01_Work/brazil/Reports'\n File_2_name = 'xbr_SVN_list.csv' # List from ZCMS\n File_2_path = os.path.join(File_2_root , File_2_name)\n\n Report_File_name = \"xbr_SVN_list.csv\"\n Report_path = os.path.join(File_2_root,Report_File_name)\n\n report = {}\n\n\n if os.path.isfile(File_1_path):\n with open(File_1_path) as f_obj:\n File_1_dict = csv_to_dictionery(f_obj)\n\n if os.path.isfile(File_2_path):\n with open(File_2_path) as f_obj:\n File_2_dict = csv_to_dictionery(f_obj)\n\n ###### Check ZCMS elements in Art Folders List\n for f2 in File_2_dict:\n # Take element from ZCMS list of assets check if found in Art Server List and add report Not found / if found add the 'soruce' path\n found = False\n fileSearched = ''\n for f1 in File_1_dict:\n\n if f2 in f1:\n d = File_2_dict[f2]\n if d[\"SVN_Path\"].lstrip(\"/!@#$%^&*()\") in f1 :\n d[\"Commit_State\"] = \"Commited\"\n else:\n d[\"Commit_State\"] = \"Wrong folder Commited\"\n d[\"SVN_Path_current\"] = f1\n report[f2] = d\n found = True\n break\n if not found:\n d = File_2_dict[f2]\n d['Commit_State'] = \"Not Commited\"\n report[f2] = d\n\n\n ###### Finally write CSV report\n dict_to_csv_writer(report, Report_path)\n\n\n","sub_path":"Pyhton/Compare_CSVs/Compare_CSV_v1 svn commit countercheck.py","file_name":"Compare_CSV_v1 svn commit countercheck.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"61228704","text":"# -*- coding:utf-8 -*-\r\nimport re, os, configparser, requests, shutil, traceback, time, hashlib, json\r\nfrom PIL import Image\r\nfrom tkinter import filedialog, Tk\r\nfrom time import sleep\r\n\r\n\r\n# get_directory功能是 获取用户选取的文件夹路径\r\ndef get_directory():\r\n directory_root = Tk()\r\n directory_root.withdraw()\r\n work_path = filedialog.askdirectory()\r\n if work_path == '':\r\n print('你没有选择目录! 请重新选:')\r\n sleep(2)\r\n return get_directory()\r\n else:\r\n # askdirectory 获得是 正斜杠 路径C:/,所以下面要把 / 换成 反斜杠\\\r\n temp_path = work_path.replace('/', '\\\\')\r\n return temp_path\r\n\r\n\r\n# 功能为记录错误txt\r\ndef write_fail(fail_m):\r\n record_txt = open('【记得清理它】失败记录.txt', 'a', encoding=\"utf-8\")\r\n record_txt.write(fail_m)\r\n record_txt.close()\r\n\r\n\r\n# 调用百度翻译API接口,返回中文简介str\r\ndef tran(api_id, key, word, to_lang):\r\n # init salt and final_sign\r\n salt = str(time.time())[:10]\r\n final_sign = api_id + word + salt + key\r\n final_sign = hashlib.md5(final_sign.encode(\"utf-8\")).hexdigest()\r\n # 表单paramas\r\n paramas = {\r\n 'q': word,\r\n 'from': 'jp',\r\n 'to': to_lang,\r\n 'appid': '%s' % api_id,\r\n 'salt': '%s' % salt,\r\n 'sign': '%s' % final_sign\r\n }\r\n response = requests.get('http://api.fanyi.baidu.com/api/trans/vip/translate', params=paramas, timeout=10).content\r\n content = str(response, encoding=\"utf-8\")\r\n try:\r\n json_reads = json.loads(content)\r\n return json_reads['trans_result'][0]['dst']\r\n except json.decoder.JSONDecodeError:\r\n print(' >翻译简介失败,请截图给作者,检查是否有非法字符:', word)\r\n return '无法翻译该简介,请手动去arzon.jp查找简介并翻译。'\r\n except:\r\n print(' >正在尝试重新日译中...')\r\n return tran(api_id, key, word, to_lang)\r\n\r\n\r\n# 获取一个arzon_cookie,返回cookie\r\ndef get_acook(prox):\r\n if prox:\r\n session = requests.Session()\r\n session.get('https://www.arzon.jp/index.php?action=adult_customer_agecheck&agecheck=1&redirect=https%3A%2F%2Fwww.arzon.jp%2F', proxies=prox, timeout=10)\r\n return session.cookies.get_dict()\r\n else:\r\n session = requests.Session()\r\n session.get('https://www.arzon.jp/index.php?action=adult_customer_agecheck&agecheck=1&redirect=https%3A%2F%2Fwww.arzon.jp%2F', timeout=10)\r\n return session.cookies.get_dict()\r\n\r\n\r\n# 获取网页源码,返回网页text;假装python的“重载”函数\r\ndef get_jav_html(url_list):\r\n if len(url_list) == 1:\r\n rqs = requests.get(url_list[0], timeout=10, headers={'Cookie': 'existmag=all'})\r\n else:\r\n rqs = requests.get(url_list[0], proxies=url_list[1], timeout=10, headers={'Cookie': 'existmag=all'})\r\n rqs.encoding = 'utf-8'\r\n return rqs.text\r\n\r\n\r\ndef get_arzon_html(url_list):\r\n if len(url_list) == 2:\r\n rqs = requests.get(url_list[0], cookies=url_list[1], timeout=10)\r\n else:\r\n rqs = requests.get(url_list[0], cookies=url_list[1], proxies=url_list[2], timeout=10)\r\n rqs.encoding = 'utf-8'\r\n return rqs.text\r\n\r\n\r\n# 下载图片,无返回\r\ndef download_pic(cov_list):\r\n # 0错误次数 1图片url 2图片路径 3proxies\r\n if cov_list[0] < 5:\r\n try:\r\n if len(cov_list) == 3:\r\n r = requests.get(cov_list[1], stream=True, timeout=(3, 7))\r\n with open(cov_list[2], 'wb') as pic:\r\n for chunk in r:\r\n pic.write(chunk)\r\n else:\r\n r = requests.get(cov_list[1], proxies=cov_list[3], stream=True, timeout=(3, 7))\r\n with open(cov_list[2], 'wb') as pic:\r\n for chunk in r:\r\n pic.write(chunk)\r\n except:\r\n print(' >下载失败,重新下载...')\r\n cov_list[0] += 1\r\n download_pic(cov_list)\r\n try:\r\n Image.open(cov_list[2])\r\n except OSError:\r\n print(' >下载失败,重新下载....')\r\n cov_list[0] += 1\r\n download_pic(cov_list)\r\n else:\r\n raise Exception(' >下载多次,仍然失败!')\r\n\r\n\r\n# 每一部jav的“结构体”\r\nclass JavFile(object):\r\n def __init__(self):\r\n self.name = 'ABC-123.mp4' # 文件名\r\n self.car = 'ABC-123' # 车牌\r\n self.episodes = 0 # 第几集\r\n self.subt = '' # 字幕文件名 ABC-123.srt\r\n\r\n\r\n# main开始\r\nprint('1、避开21:00-1:00,访问javbus和arzon很慢。\\n'\r\n '1、如果连不上javbus,请更正防屏蔽地址\\n'\r\n ' 不要用“www.javbus.com”!\\n')\r\n# 读取配置文件,这个ini文件用来给用户设置重命名的格式和jav网址\r\nprint('正在读取ini中的设置...', end='')\r\ntry:\r\n config_settings = configparser.RawConfigParser()\r\n config_settings.read('ini的设置会影响所有exe的操作结果.ini', encoding='utf-8-sig')\r\n if_nfo = config_settings.get(\"收集nfo\", \"是否收集nfo?\")\r\n if_exnfo = config_settings.get(\"收集nfo\", \"是否跳过已存在nfo的文件夹?\")\r\n custom_title = config_settings.get(\"收集nfo\", \"nfo中title的格式\")\r\n if_mp4 = config_settings.get(\"重命名影片\", \"是否重命名影片?\")\r\n rename_mp4 = config_settings.get(\"重命名影片\", \"重命名影片的格式\")\r\n if_folder = config_settings.get(\"修改文件夹\", \"是否重命名或创建独立文件夹?\")\r\n rename_folder = config_settings.get(\"修改文件夹\", \"新文件夹的格式\")\r\n if_rename_subt = config_settings.get(\"字幕文件\", \"是否重命名已有的字幕文件\")\r\n if_classify_subt = config_settings.get(\"字幕文件\", \"是否使用字幕库\")\r\n if_classify = config_settings.get(\"归类影片\", \"是否归类影片?\")\r\n file_folder = config_settings.get(\"归类影片\", \"针对文件还是文件夹?\")\r\n classify_root = config_settings.get(\"归类影片\", \"归类的根目录\")\r\n classify_basis = config_settings.get(\"归类影片\", \"归类的标准\")\r\n if_jpg = config_settings.get(\"下载封面\", \"是否下载封面海报?\")\r\n custom_fanart = config_settings.get(\"下载封面\", \"DVD封面的格式\")\r\n custom_poster = config_settings.get(\"下载封面\", \"海报的格式\")\r\n if_sculpture = config_settings.get(\"kodi专用\", \"是否收集女优头像\")\r\n if_proxy = config_settings.get(\"代理\", \"是否使用代理?\")\r\n proxy = config_settings.get(\"代理\", \"代理IP及端口\")\r\n if_plot = config_settings.get(\"百度翻译API\", \"是否需要日语简介?\")\r\n if_tran = config_settings.get(\"百度翻译API\", \"是否翻译为中文?\")\r\n ID = config_settings.get(\"百度翻译API\", \"APP ID\")\r\n SK = config_settings.get(\"百度翻译API\", \"密钥\")\r\n simp_trad = config_settings.get(\"其他设置\", \"简繁中文?\")\r\n bus_url = config_settings.get(\"其他设置\", \"javbus网址\")\r\n suren_pref = config_settings.get(\"其他设置\", \"素人车牌(若有新车牌请自行添加)\")\r\n file_type = config_settings.get(\"其他设置\", \"扫描文件类型\")\r\n title_len = int(config_settings.get(\"其他设置\", \"重命名中的标题长度(50~150)\"))\r\n subt_words = config_settings.get(\"原影片文件的性质\", \"是否中字即文件名包含\")\r\n custom_subt = config_settings.get(\"原影片文件的性质\", \"是否中字的表现形式\")\r\n xx_words = config_settings.get(\"原影片文件的性质\", \"是否xx即文件名包含\")\r\n custom_xx = config_settings.get(\"原影片文件的性质\", \"是否xx的表现形式\")\r\n movie_type = config_settings.get(\"原影片文件的性质\", \"有码\")\r\nexcept:\r\n print(traceback.format_exc())\r\n print('\\n无法读取ini文件,请修改它为正确格式,或者打开“【ini】重新创建ini.exe”创建全新的ini!')\r\n os.system('pause')\r\n\r\n# 确认:女优头像ini及头像文件夹\r\nif if_sculpture == '是':\r\n if not os.path.exists('女优头像'):\r\n print('\\n“女优头像”文件夹丢失!请把它放进exe的文件夹中!\\n')\r\n os.system('pause')\r\n if not os.path.exists('【缺失的女优头像统计For Kodi】.ini'):\r\n config_actor = configparser.ConfigParser()\r\n config_actor.add_section(\"缺失的女优头像\")\r\n config_actor.set(\"缺失的女优头像\", \"女优姓名\", \"N(次数)\")\r\n config_actor.add_section(\"说明\")\r\n config_actor.set(\"说明\", \"上面的“女优姓名 = N(次数)”的表达式\", \"后面的N数字表示你有N部(次)影片都在找她的头像,可惜找不到\")\r\n config_actor.set(\"说明\", \"你可以去保存一下她的头像jpg到“女优头像”文件夹\", \"以后就能保存她的头像到影片的文件夹了\")\r\n config_actor.write(open('【缺失的女优头像统计For Kodi】.ini', \"w\", encoding='utf-8-sig'))\r\n print('\\n >“【缺失的女优头像统计For Kodi】.ini”文件被你玩坏了...正在重写ini...成功!')\r\n print('正在重新读取...', end='')\r\nprint('\\n读取ini文件成功!')\r\n# 确认:arzon的cookie,通过成人验证\r\nproxies = {\"http\": \"http://\" + proxy, \"https\": \"https://\" + proxy}\r\nacook = {}\r\nif if_plot == '是' and if_nfo == '是':\r\n print('正在尝试通过“https://www.arzon.jp”的成人验证...')\r\n try:\r\n if if_proxy == '是' and proxy != '':\r\n acook = get_acook(proxies)\r\n else:\r\n acook = get_acook({})\r\n print('通过arzon的成人验证!\\n')\r\n except:\r\n print('连接arzon失败,请避开网络高峰期!请重启程序!\\n')\r\n os.system('pause')\r\n# 确认:代理哪些站点\r\nif if_proxy == '是' and proxy != '': # 是否需要代理,设置requests请求时的状态\r\n jav_list = ['', proxies] # 代理jav等\r\n arzon_list = ['', acook, proxies] # 代理arzon\r\n cover_list = [0, '', '', proxies] # 代理dmm\r\nelse:\r\n jav_list = ['']\r\n arzon_list = ['', acook]\r\n cover_list = [0, '', '']\r\n# https://www.buscdn.work/\r\nif not bus_url.endswith('/'):\r\n bus_url += '/'\r\n# 归类文件夹具有最高决定权\r\nif if_classify == '是': # 如果需要归类\r\n if file_folder == '文件夹': # 并且是针对文件夹\r\n if_folder = '是' # 那么必须重命名文件夹或者创建新的文件夹\r\n else:\r\n if_folder = '否' # 否则不会操作新文件夹\r\n# 百度翻译是简/繁中文\r\nif simp_trad == '简':\r\n t_lang = 'zh'\r\nelse:\r\n t_lang = 'cht'\r\n# 初始化其他\r\nnfo_dict = {'空格': ' ', '车牌': 'ABC-123', '标题': '未知标题', '完整标题': '完整标题', '导演': '未知导演',\r\n '发行年月日': '1970-01-01', '发行年份': '1970', '月': '01', '日': '01',\r\n '片商': '未知片商', '首个女优': '未知演员', '全部女优': '未知演员',\r\n '片长': '0', '\\\\': '\\\\', '是否中字': '', '视频': 'ABC-123', '车牌前缀': 'ABC',\r\n '是否xx': '', '影片类型': movie_type, '系列': '未知系列'} # 用于暂时存放影片信息,女优,标题等\r\nsuren_list = suren_pref.split('、') # 素人番号的列表\r\nrename_mp4_list = rename_mp4.split('+') # 重命名视频的格式\r\nrename_folder_list = rename_folder.split('+') # 重命名文件夹的格式\r\ntype_tuple = tuple(file_type.split('、')) # 需要扫描的文件的类型\r\nclassify_basis_list = classify_basis.split('\\\\') # 归类标准,归类到哪个文件夹\r\ntitle_list = custom_title.replace('标题', '完整标题', 1).split('+') # nfo中title的写法\r\nfanart_list = custom_fanart.split('+') # fanart的格式\r\nposter_list = custom_poster.split('+') # poster的格式\r\nword_list = subt_words.split('、') # 包含哪些特殊含义的文字,判断是否中字\r\nxx_list = xx_words.split('、') # 包含哪些特殊含义的文字,判断是否xx\r\nfor j in rename_mp4_list:\r\n if j not in nfo_dict:\r\n nfo_dict[j] = j\r\nfor j in rename_folder_list:\r\n if j not in nfo_dict:\r\n nfo_dict[j] = j\r\nclassify_list = []\r\nfor i in classify_basis_list:\r\n for j in i.split('+'):\r\n if j not in nfo_dict:\r\n nfo_dict[j] = j\r\n classify_list.append(j)\r\n classify_list.append('\\\\')\r\nfor j in title_list:\r\n if j not in nfo_dict:\r\n nfo_dict[j] = j\r\nfor j in fanart_list:\r\n if j not in nfo_dict:\r\n nfo_dict[j] = j\r\nfor j in poster_list:\r\n if j not in nfo_dict:\r\n nfo_dict[j] = j\r\n# 特点,繁转简\r\ngen_dict = {'折磨': '折磨', '嘔吐': '呕吐', '觸手': '触手', '蠻橫嬌羞': '蛮横娇羞', '處男': '处男', '正太控': '正太控',\r\n '出軌': '出轨', '瘙癢': '瘙痒', '運動': '运动', '女同接吻': '女同接吻', '性感的x': '性感的', '美容院': '美容院',\r\n '處女': '处女', '爛醉如泥的': '烂醉如泥的', '殘忍畫面': '残忍画面', '妄想': '妄想', '惡作劇': '恶作剧', '學校作品': '学校作品',\r\n '粗暴': '粗暴', '通姦': '通奸', '姐妹': '姐妹', '雙性人': '双性人', '跳舞': '跳舞', '性奴': '性奴',\r\n '倒追': '倒追', '性騷擾': '性骚扰', '其他': '其他', '戀腿癖': '恋腿癖', '偷窥': '偷窥', '花癡': '花痴',\r\n '男同性恋': '男同性恋', '情侶': '情侣', '戀乳癖': '恋乳癖', '亂倫': '乱伦', '其他戀物癖': '其他恋物癖', '偶像藝人': '偶像艺人',\r\n '野外・露出': '野外・露出', '獵豔': '猎艳', '女同性戀': '女同性恋', '企畫': '企画', '10枚組': '10枚组', '性感的': '性感的',\r\n '科幻': '科幻', '女優ベスト・総集編': '女优的总编', '温泉': '温泉', 'M男': 'M男', '原作コラボ': '原作协作',\r\n '16時間以上作品': '16时间以上作品', 'デカチン・巨根': '巨根', 'ファン感謝・訪問': '感恩祭', '動画': '动画', '巨尻': '巨尻', 'ハーレム': '后宫',\r\n '日焼け': '晒黑', '早漏': '早漏', 'キス・接吻': '接吻.', '汗だく': '汗流浃背', 'スマホ専用縦動画': '智能手机的垂直视频', 'Vシネマ': '电影放映',\r\n 'Don Cipote\\'s choice': 'Don Cipote\\'s choice', 'アニメ': '日本动漫', 'アクション': '动作', 'イメージビデオ(男性)': '(视频)男性', '孕ませ': '孕育', 'ボーイズラブ': '男孩恋爱',\r\n 'ビッチ': 'bitch', '特典あり(AVベースボール)': '特典(AV棒球)', 'コミック雑誌': '漫画雑志', '時間停止': '时间停止',\r\n\r\n '黑幫��員': '黑帮成员', '童年朋友': '童年朋友', '公主': '公主', '亞洲女演員': '亚洲女演员', '伴侶': '伴侣', '講師': '讲师',\r\n '婆婆': '婆婆', '格鬥家': '格斗家', '女檢察官': '女检察官', '明星臉': '明星脸', '女主人、女老板': '女主人、女老板', '模特兒': '模特',\r\n '秘書': '秘书', '美少女': '美少女', '新娘、年輕妻子': '新娘、年轻妻子', '姐姐': '姐姐', '車掌小姐': '车掌小姐',\r\n '寡婦': '寡妇', '千金小姐': '千金小姐', '白人': '白人', '已婚婦女': '已婚妇女', '女醫生': '女医生', '各種職業': '各种职业',\r\n '妓女': '妓女', '賽車女郎': '赛车女郎', '女大學生': '女大学生', '展場女孩': '展场女孩', '女教師': '女教师', '母親': '母亲',\r\n '家教': '家教', '护士': '护士', '蕩婦': '荡妇', '黑人演員': '黑人演员', '女生': '女生', '女主播': '女主播',\r\n '高中女生': '高中女生', '服務生': '服务生', '魔法少女': '魔法少女', '學生(其他)': '学生(其他)', '動畫人物': '动画人物', '遊戲的真人版': '游戏真人版',\r\n '超級女英雄': '超级女英雄',\r\n\r\n '角色扮演': '角色扮演', '制服': '制服', '女戰士': '女战士', '及膝襪': '及膝袜', '娃娃': '娃娃', '女忍者': '女忍者',\r\n '女裝人妖': '女装人妖', '內衣': '內衣', '猥褻穿著': '猥亵穿着', '兔女郎': '兔女郎', '貓耳女': '猫耳女', '女祭司': '女祭司',\r\n '泡泡襪': '泡泡袜', '緊身衣': '紧身衣', '裸體圍裙': '裸体围裙', '迷你裙警察': '迷你裙警察', '空中小姐': '空中小姐',\r\n '連褲襪': '连裤袜', '身體意識': '身体意识', 'OL': 'OL', '和服・喪服': '和服・丧服', '體育服': '体育服', '内衣': '内衣',\r\n '水手服': '水手服', '學校泳裝': '学校泳装', '旗袍': '旗袍', '女傭': '女佣', '迷你裙': '迷你裙', '校服': '校服',\r\n '泳裝': '泳装', '眼鏡': '眼镜', '哥德蘿莉': '哥德萝莉', '和服・浴衣': '和服・浴衣',\r\n\r\n '超乳': '超乳', '肌肉': '肌肉', '乳房': '乳房', '嬌小的': '娇小的', '屁股': '屁股', '高': '高',\r\n '變性者': '变性人', '無毛': '无毛', '胖女人': '胖女人', '苗條': '苗条', '孕婦': '孕妇', '成熟的女人': '成熟的女人',\r\n '蘿莉塔': '萝莉塔', '貧乳・微乳': '贫乳・微乳', '巨乳': '巨乳',\r\n\r\n\r\n '顏面騎乘': '颜面骑乘', '食糞': '食粪', '足交': '足交', '母乳': '母乳', '手指插入': '手指插入', '按摩': '按摩',\r\n '女上位': '女上位', '舔陰': '舔阴', '拳交': '拳交', '深喉': '深喉', '69': '69', '淫語': '淫语',\r\n '潮吹': '潮吹', '乳交': '乳交', '排便': '排便', '飲尿': '饮尿', '口交': '口交', '濫交': '滥交',\r\n '放尿': '放尿', '打手槍': '打手枪', '吞精': '吞精', '肛交': '肛交', '顏射': '颜射', '自慰': '自慰',\r\n '顏射x': '颜射', '中出': '中出', '肛内中出': '肛内中出',\r\n\r\n '立即口交': '立即口交', '女優按摩棒': '女优按摩棒', '子宮頸': '子宫颈', '催眠': '催眠', '乳液': '乳液', '羞恥': '羞耻',\r\n '凌辱': '凌辱', '拘束': '拘束', '輪姦': '轮奸', '插入異物': '插入异物', '鴨嘴': '鸭嘴', '灌腸': '灌肠',\r\n '監禁': '监禁', '紧缚': '紧缚', '強姦': '强奸', '藥物': '药物', '汽車性愛': '汽车性爱', 'SM': 'SM',\r\n '糞便': '粪便', '玩具': '玩具', '跳蛋': '跳蛋', '緊縛': '紧缚', '按摩棒': '按摩棒', '多P': '多P',\r\n '性愛': '性爱', '假陽具': '假阳具', '逆強姦': '逆强奸',\r\n\r\n '合作作品': '合作作品', '恐怖': '恐怖', '給女性觀眾': '女性向', '教學': '教学', 'DMM專屬': 'DMM专属', 'R-15': 'R-15',\r\n 'R-18': 'R-18', '戲劇': '戏剧', '3D': '3D', '特效': '特效', '故事集': '故事集', '限時降價': '限时降价',\r\n '複刻版': '复刻版', '戲劇x': '戏剧', '戀愛': '恋爱', '高畫質': 'xxx', '主觀視角': '主观视角', '介紹影片': '介绍影片',\r\n '4小時以上作品': '4小时以上作品', '薄馬賽克': '薄马赛克', '經典': '经典', '首次亮相': '首次亮相', '數位馬賽克': '数位马赛克', '投稿': '投稿',\r\n '纪录片': '纪录片', '國外進口': '国外进口', '第一人稱攝影': '第一人称摄影', '業餘': '业余', '局部特寫': '局部特写', '獨立製作': '独立制作',\r\n 'DMM獨家': 'DMM独家', '單體作品': '单体作品', '合集': '合集', '高清': '高清', '字幕': '字幕', '天堂TV': '天堂TV',\r\n 'DVD多士爐': 'DVD多士炉', 'AV OPEN 2014 スーパーヘ���ー': 'AV OPEN 2014 S级', 'AV OPEN 2014 ヘビー級': 'AV OPEN 2014重量级', 'AV OPEN 2014 ミドル級': 'AV OPEN 2014中量级',\r\n 'AV OPEN 2015 マニア/フェチ部門': 'AV OPEN 2015 狂热者/恋物癖部门', 'AV OPEN 2015 熟女部門': 'AV OPEN 2015 熟女部门',\r\n 'AV OPEN 2015 企画部門': 'AV OPEN 2015 企画部门', 'AV OPEN 2015 乙女部門': 'AV OPEN 2015 少女部',\r\n 'AV OPEN 2015 素人部門': 'AV OPEN 2015 素人部门', 'AV OPEN 2015 SM/ハード部門': 'AV OPEN 2015 SM/硬件',\r\n 'AV OPEN 2015 女優部門': 'AV OPEN 2015 女优部门', 'AVOPEN2016人妻・熟女部門': 'AVOPEN2016人妻・熟女部门',\r\n 'AVOPEN2016企画部門': 'AVOPEN2016企画部', 'AVOPEN2016ハード部門': 'AVOPEN2016ハード部',\r\n 'AVOPEN2016マニア・フェチ部門': 'AVOPEN2016疯狂恋物科', 'AVOPEN2016乙女部門': 'AVOPEN2016少女部',\r\n 'AVOPEN2016女優部門': 'AVOPEN2016女优部', 'AVOPEN2016ドラマ・ドキュメンタリー部門': 'AVOPEN2016电视剧纪录部',\r\n 'AVOPEN2016素人部門': 'AVOPEN2016素人部', 'AVOPEN2016バラエティ部門': 'AVOPEN2016娱乐部',\r\n 'VR専用': 'VR専用', '堵嘴·喜劇': '堵嘴·喜剧', '幻想': '幻想', '性別轉型·女性化': '性别转型·女性化',\r\n '為智能手機推薦垂直視頻': '为智能手机推荐垂直视频', '設置項目': '设置项目', '迷你係列': '迷你系列',\r\n '體驗懺悔': '体验忏悔', '黑暗系統': '黑暗系统',\r\n\r\n 'オナサポ': '手淫', 'アスリート': '运动员', '覆面・マスク': '蒙面具', 'ハイクオリティVR': '高品质VR', 'ヘルス・ソープ': '保健香皂', 'ホテル': '旅馆',\r\n 'アクメ・オーガズム': '绝顶高潮', '花嫁': '花嫁', 'デート': '约会', '軟体': '软体', '娘・養女': '养女', 'スパンキング': '打屁股',\r\n 'スワッピング・夫婦交換': '夫妇交换', '部下・同僚': '部下・同僚', '旅行': '旅行', '胸チラ': '露胸', 'バック': '后卫', 'エロス': '爱的欲望',\r\n '男の潮吹き': '男人高潮', '女上司': '女上司', 'セクシー': '性感美女', '受付嬢': '接待小姐', 'ノーブラ': '不穿胸罩',\r\n '白目・失神': '白眼失神', 'M女': 'M女', '女王様': '女王大人', 'ノーパン': '不穿内裤', 'セレブ': '名流', '病院・クリニック': '医院诊所',\r\n '面接': '面试', 'お風呂': '浴室', '叔母さん': '叔母阿姨', '罵倒': '骂倒', 'お爺ちゃん': '爷爷', '逆レイプ': '强奸小姨子',\r\n 'ディルド': 'ディルド', 'ヨガ': '瑜伽', '飲み会・合コン': '酒会、联谊会', '部活・マネージャー': '社团经理', 'お婆ちゃん': '外婆', 'ビジネススーツ': '商务套装',\r\n 'チアガール': '啦啦队女孩', 'ママ友': '妈妈的朋友', 'エマニエル': '片商Emanieru熟女塾', '妄想族': '妄想族', '蝋燭': '蜡烛', '鼻フック': '鼻钩儿',\r\n '放置': '放置', 'サンプル動画': '范例影片', 'サイコ・スリラー': '心理惊悚片', 'ラブコメ': '爱情喜剧', 'オタク': '御宅族',\r\n '中文字幕': '中文字幕'}\r\n\r\nstart_key = ''\r\nwhile start_key == '':\r\n # 用户选择文件夹\r\n print('请选择要整理的文件夹:', end='')\r\n path = get_directory()\r\n print(path)\r\n write_fail('已选择文件夹:' + path+'\\n')\r\n print('...文件扫描开始...如果时间过长...请避开中午夜晚高峰期...\\n')\r\n if if_classify == '是':\r\n classify_root = classify_root.rstrip('\\\\')\r\n if classify_root != '所选文件夹':\r\n if classify_root != path: # 归类根目录和所选不一样,继续核实归类根目录和所选不一样的合法性\r\n if classify_root[:2] != path[:2]:\r\n print('归类的根目录“', classify_root, '”和所选文件夹不在同一磁盘无法归类!请修正!')\r\n os.system('pause')\r\n if not os.path.exists(classify_root):\r\n print('归类的根目录“', classify_root, '”不存在!无法归类!请修正!')\r\n os.system('pause')\r\n else: # 一样\r\n classify_root = path + '\\\\归类完成'\r\n else:\r\n classify_root = path + '\\\\归类完成'\r\n # 初始化“失败信息”\r\n fail_times = 0 # 处理过程中错失败的个数\r\n fail_list = [] # 用于存放处理失败的信息\r\n # os.system('pause')\r\n # root【当前根目录】 dirs【子目录】 files【文件】,root是字符串,后两个是列表\r\n for root, dirs, files in os.walk(path):\r\n if if_classify == '是' and root.startswith(classify_root):\r\n # print('>>该文件夹在归类的根目录中,跳过处理...', root)\r\n continue\r\n if if_exnfo == '是' and files and (files[-1].endswith('nfo') or (len(files) > 1 and files[-2].endswith('nfo'))):\r\n continue\r\n # 对这一层文件夹进行评估,有多少视频,有多少同车牌视频,是不是独立文件夹\r\n jav_videos = [] # 存放:需要整理的jav的结构体\r\n cars_dic = {}\r\n videos_num = 0 # 当前文件夹中视频的数量,可能有视频不是jav\r\n subtitles = False # 有没有字幕\r\n subts_dict = {} # 存放:jav的字幕文件\r\n for raw_file in files:\r\n # 判断文件是不是字幕文件\r\n if raw_file.endswith(('.srt', '.vtt', '.ass', '.ssa',)):\r\n srt_g = re.search(r'(\\d?\\d?[a-zA-Z]{1,7}\\d?\\d?)-? ?_?(\\d{2,6})', raw_file)\r\n if str(srt_g) != 'None':\r\n num_pref = srt_g.group(1).upper()\r\n if num_pref in suren_list:\r\n continue\r\n num_suf = srt_g.group(2)\r\n car_num = num_pref + '-' + num_suf\r\n subts_dict[raw_file] = car_num\r\n continue\r\n # print(subts_dict)\r\n # print('>>扫描字幕文件完毕!')\r\n for raw_file in files:\r\n # 判断是不是视频,得到车牌号\r\n if raw_file.endswith(type_tuple) and not raw_file.startswith('.'):\r\n videos_num += 1\r\n video_num_g = re.search(r'(\\d?\\d?[a-zA-Z]{1,7}\\d?\\d?)-? ?_?(\\d{2,6})', raw_file) # 这个正则表达式匹配“车牌号”可能有点奇怪,\r\n if str(video_num_g) != 'None': # 如果你下过上千部片,各种参差不齐的命名,你就会理解我了。\r\n num_pref = video_num_g.group(1).upper()\r\n num_suf = video_num_g.group(2)\r\n car_num = num_pref + '-' + num_suf\r\n if num_pref in suren_list: # 如果这是素人影片,告诉一下用户,它们需要另外处理\r\n fail_times += 1\r\n fail_message = '第' + str(fail_times) + '个警告!素人影片:' + root.lstrip(path) + '\\\\' + raw_file + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n continue # 素人影片不参与下面的整理\r\n if car_num not in cars_dic: # cars_dic中没有这个车牌,表示这一层文件夹下新发现一个车牌\r\n cars_dic[car_num] = 1 # 这个新车牌有了第一集\r\n else:\r\n cars_dic[car_num] += 1 # 已经有这个车牌了,加一集cd\r\n jav_file = JavFile()\r\n jav_file.car = car_num # 车牌\r\n jav_file.name = raw_file # 原文件名\r\n jav_file.episodes = cars_dic[car_num] # 这个jav视频,是第几集\r\n if car_num in subts_dict.values():\r\n jav_file.subt = list(subts_dict.keys())[list(subts_dict.values()).index(car_num)]\r\n del subts_dict[jav_file.subt]\r\n jav_videos.append(jav_file)\r\n else:\r\n continue\r\n else:\r\n continue\r\n # 判定影片所在文件夹是否是独立文件夹\r\n if cars_dic:\r\n if len(cars_dic) > 1 or videos_num > len(jav_videos) or len(dirs) > 1 or (\r\n len(dirs) == 1 and dirs[0] != '.actors'):\r\n # 当前文件夹下, 车牌不止一个,还有其他非jav视频,有其他文件夹\r\n separate_folder = False\r\n else:\r\n separate_folder = True\r\n else:\r\n continue\r\n\r\n # 正式开始\r\n # print(jav_videos)\r\n for srt in jav_videos:\r\n car_num = srt.car\r\n file = srt.name\r\n relative_path = '\\\\' + root.lstrip(path) + '\\\\' + file # 影片的相对于所选文件夹的路径,用于报错\r\n try:\r\n # 获取nfo信息的javbus搜索网页 https://www.cdnbus.work/search/avop&type=&parent=ce\r\n bus_bu_url = bus_url + 'search/' + car_num + '&type=1&parent=ce'\r\n jav_list[0] = bus_bu_url\r\n try:\r\n jav_html = get_jav_html(jav_list)\r\n except:\r\n print('>>尝试打开javbus有码页面失败,正在尝试第二次打开...')\r\n try:\r\n jav_html = get_jav_html(jav_list)\r\n print(' >第二次尝试成功!')\r\n except:\r\n fail_times += 1\r\n fail_message = '第' + str(fail_times) + '个失败!连接javbus有码失败:' + bus_bu_url + ',' + relative_path + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n continue\r\n # 搜索结果的网页,大部分情况一个结果,也有可能是多个结果的网页\r\n # 尝试找movie-box\r\n bav_urls = re.findall(r'', jav_html) # 匹配处理“标题”\r\n if len(bav_urls) == 1: # 搜索结果页面只有一个box\r\n bav_url = bav_urls[0]\r\n elif len(bav_urls) > 1: # 找到不止一个box\r\n print('>>该车牌:' + car_num + ' 搜索到多个结果,正在尝试精确定位...')\r\n car_suf = re.findall(r'\\d+', car_num)[-1] # 当前车牌的后缀数字\r\n car_suf = car_suf.lstrip('0') # 去除-0001中的000\r\n car_prefs = re.findall(r'[a-zA-Z]+', car_num) # 匹配车牌的前缀字母\r\n if car_prefs:\r\n car_pref = car_prefs[-1].upper()\r\n else:\r\n car_pref = '' # 也可能没字母,全是数字12345_678.mp4\r\n bav_url = ''\r\n for i in bav_urls:\r\n # print(re.findall(r'\\d+', i.split('/')[-1]))\r\n url_suf = re.findall(r'\\d+', i.split('/')[-1])[-1] # 匹配处理“01”,box上影片车牌的后缀数字\r\n url_suf = url_suf.lstrip('0') # 去除-0001中的000\r\n if car_suf == url_suf: # 数字相同\r\n url_prefs = re.findall(r'[a-zA-Z]+', i.split('/')[-1]) # 匹配处理“n”\r\n if url_prefs: # box的前缀字母\r\n url_pref = url_prefs[-1].upper()\r\n else:\r\n url_pref = ''\r\n if car_pref == url_pref: # 数字相同的基础下,字母也相同,即可能车牌相同\r\n bav_url = i\r\n fail_times += 1\r\n fail_message = '第' + str(fail_times) + '个警告!从“' + file + '”的多个搜索结果中确定为:' + bav_url + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n break\r\n else:\r\n continue\r\n # 有码搜索的结果一个都匹配不上\r\n if bav_url == '':\r\n fail_times += 1\r\n print(jav_html)\r\n fail_message = '第' + str(fail_times) + '个失败!多个搜索结果也找不到AV信息:' + bus_bu_url + ',' + relative_path + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n continue\r\n else: # 找不到box\r\n # 尝试在无码区搜索该车牌\r\n bus_qi_url = bus_url + 'uncensored/search/' + car_num + '&type=&parent=uc' # 有码搜索url\r\n jav_list[0] = bus_qi_url\r\n try:\r\n jav_html = get_jav_html(jav_list)\r\n except:\r\n print('>>尝试打开javbus无码页面失败,正在尝试第二次打开...')\r\n try:\r\n jav_html = get_jav_html(jav_list)\r\n print(' >第二次尝试成功!')\r\n except:\r\n fail_times += 1\r\n fail_message = '第' + str(fail_times) + '个失败!连接javbus无码失败:' + bus_qi_url + ',' + relative_path + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n continue\r\n bav_urls = re.findall(r' ', jav_html) # 在“有码”中匹配处理“标题”\r\n if len(bav_urls) > 0:\r\n print('>>跳过无码影片:', file)\r\n continue\r\n # # 上面只能搜索\r\n # bus_bu_url = bus_url + 'search/' + car_num + '&type=1'\r\n # jav_list[0] = bus_bu_url\r\n # try:\r\n # jav_html = get_jav_html(jav_list)\r\n # except:\r\n fail_times += 1\r\n fail_message = '第' + str(fail_times) + '个失败!有码无码都找不到AV信息:' + bus_bu_url + ',' + relative_path + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n continue\r\n # 经过上面的三种情况,可能找到了jav在bus上的网页链接bav_url\r\n jav_list[0] = bav_url\r\n try:\r\n bav_html = get_jav_html(jav_list)\r\n except:\r\n print('>>尝试打开javbus上的jav网页失败,正在尝试第二次打开...')\r\n try:\r\n bav_html = get_jav_html(jav_list)\r\n print(' >第二次尝试成功!')\r\n except:\r\n fail_times += 1\r\n fail_message = '第' + str(fail_times) + '个失败!打开javbus上的jav网页失败:' + bav_url + ',' + relative_path + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n continue\r\n\r\n # 正则匹配 影片信息 开始!\r\n # title的开头是车牌号,而我想要后面的纯标题\r\n try: # 标题 030619-872 スーパーボディと最強の美貌の悶える女 - JavBus \r\n title = re.search(r'(.+?) - JavBus ', bav_html, re.DOTALL).group(1) # 这边匹配番号\r\n except:\r\n fail_times += 1\r\n fail_message = '第' + str(fail_times) + '个失败!页面上找不到AV信息:' + bav_url + ',' + relative_path + '\\n'\r\n print('>>' + fail_message, end='')\r\n fail_list.append(' >' + fail_message)\r\n write_fail(' >' + fail_message)\r\n continue\r\n\r\n print('>>正在处理:', title)\r\n # 影片的一些属性\r\n video_type = '.' + file.split('.')[-1] # 文件类型,如:.mp4\r\n subt_name = srt.subt\r\n if subt_name:\r\n subtitles = True\r\n subt_type = '.' + subt_name.split('.')[-1] # 文件类型,如:.srt\r\n else:\r\n subtitles = False\r\n subt_type = ''\r\n nfo_dict['是否中字'] = ''\r\n if not subtitles: # 没有外挂字幕\r\n for i in word_list:\r\n if i in file:\r\n nfo_dict['是否中字'] = custom_subt\r\n break\r\n else:\r\n nfo_dict['是否中字'] = custom_subt\r\n nfo_dict['是否xx'] = ''\r\n for i in xx_list:\r\n if i in file:\r\n nfo_dict['是否xx'] = custom_xx\r\n break\r\n # 去除title中的特殊字符\r\n title = title.replace('\\n', '').replace('&', '和').replace('\\\\', '#') \\\r\n .replace('/', '#').replace(':', ':').replace('*', '#').replace('?', '?') \\\r\n .replace('\"', '#').replace('<', '【').replace('>', '】') \\\r\n .replace('|', '#').replace('<', '【').replace('>', '】') \\\r\n .replace('〈', '【').replace('〉', '】').replace('&', '和').replace('\\t', '').replace('\\r', '')\r\n # 正则匹配 影片信息 开始!\r\n # title的开头是车牌号,想要后面的纯标题\r\n car_titleg = re.search(r'(.+?) (.+)', title) # 这边匹配番号,[a-z]可能很奇怪,\r\n # 车牌号\r\n nfo_dict['车牌'] = car_titleg.group(1)\r\n nfo_dict['车牌前缀'] = nfo_dict['车牌'].split('-')[0]\r\n # 给用户用的标题是 短的title_easy\r\n nfo_dict['完整标题'] = car_titleg.group(2)\r\n # 处理影片的标题过长\r\n if len(nfo_dict['完整标题']) > title_len:\r\n nfo_dict['标题'] = nfo_dict['完整标题'][:title_len]\r\n else:\r\n nfo_dict['标题'] = nfo_dict['完整标题']\r\n # 片商 製作商: カリビアンコム \r\n studiog = re.search(r'製作商: (.+?) ', bav_html)\r\n if str(studiog) != 'None':\r\n nfo_dict['片商'] = studiog.group(1)\r\n else:\r\n nfo_dict['片商'] = '未知片商'\r\n # 發行日期: 2019-03-06
\r\n premieredg = re.search(r'發行日期: (.+?)', bav_html)\r\n if str(premieredg) != 'None':\r\n nfo_dict['发行年月日'] = premieredg.group(1)\r\n nfo_dict['发行年份'] = nfo_dict['发行年月日'][0:4]\r\n nfo_dict['月'] = nfo_dict['发行年月日'][5:7]\r\n nfo_dict['日'] = nfo_dict['发行年月日'][8:10]\r\n else:\r\n nfo_dict['发行年月日'] = '1970-01-01'\r\n nfo_dict['发行年份'] = '1970'\r\n nfo_dict['月'] = '01'\r\n nfo_dict['日'] = '01'\r\n # 片长 150 分钟 \r\n runtimeg = re.search(r'長度: (.+?)分鐘', bav_html)\r\n if str(runtimeg) != 'None':\r\n nfo_dict['片长'] = runtimeg.group(1)\r\n else:\r\n nfo_dict['片长'] = '0'\r\n # 导演 >導演: 宮藤春男<\r\n directorg = re.search(r'導演: (.+?)<', bav_html)\r\n if str(directorg) != 'None':\r\n nfo_dict['导演'] = directorg.group(1)\r\n else:\r\n nfo_dict['导演'] = '未知导演'\r\n # 演员们 和 # 第一个演员\r\n # \r\n # \r\n # actors = re.findall(r' ', bav_html)\r\n actors = re.findall(r'/star/.+?\"> ', bav_html)\r\n # print(actors)\r\n if len(actors) != 0:\r\n if len(actors) > 7:\r\n actors = actors[:7]\r\n nfo_dict['首个女优'] = actors[0]\r\n nfo_dict['全部女优'] = ' '.join(actors)\r\n else:\r\n nfo_dict['首个女优'] = nfo_dict['全部女优'] = '未知演员'\r\n actors = ['未知演员']\r\n nfo_dict['标题'] = nfo_dict['标题'].rstrip(nfo_dict['全部女优'])\r\n # 特点 自慰 \r\n genres = re.findall(r'(.+?) ', bav_html)\r\n genres = [i for i in genres if i != '字幕' and i != '高清' and i != '高畫質']\r\n if nfo_dict['是否中字']:\r\n genres.append('中文字幕')\r\n # DVD封面cover\r\n cover_url = ''\r\n coverg = re.search(r' ', bav_html) # 封面图片的正则对象\r\n if str(coverg) != 'None':\r\n cover_url = coverg.group(1)\r\n # 系列: 悪質シロウトナンパ \r\n seriesg = re.search(r'系列: (.+?) ', bav_html) # 封面图片的正则对象\r\n if str(seriesg) != 'None':\r\n series = nfo_dict['系列'] = seriesg.group(1)\r\n else:\r\n series = ''\r\n nfo_dict['系列'] = '未知系列'\r\n # arzon的简介 #########################################################\r\n plot = ''\r\n if if_nfo == '是' and if_plot == '是':\r\n while 1:\r\n arz_search_url = 'https://www.arzon.jp/itemlist.html?t=&m=all&s=&q=' + nfo_dict['车牌']\r\n print(' >正在查找简介:', arz_search_url)\r\n arzon_list[0] = arz_search_url\r\n try:\r\n search_html = get_arzon_html(arzon_list)\r\n except:\r\n print(' >尝试打开“', arz_search_url, '”搜索页面失败,正在尝试第二次打开...')\r\n try:\r\n search_html = get_arzon_html(arzon_list)\r\n print(' >第二次尝试成功!')\r\n except:\r\n fail_times += 1\r\n fail_message = ' >第' + str(\r\n fail_times) + '个失败!连接arzon失败:' + arz_search_url + ',' + relative_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n plot = '【连接arzon失败!看到此提示请重新整理nfo!】'\r\n break # 跳出while\r\n if plot == '':\r\n # 打开“', arz_url, '”第' + str(i+1) + '个搜索结果失败,正在尝试第二次打开...')\r\n try:\r\n jav_html = get_arzon_html(arzon_list)\r\n print(' >第二次尝试成功!')\r\n except:\r\n fail_times += 1\r\n fail_message = ' >第' + str(\r\n fail_times) + '个失败!无法进入第' + str(i+1) + '个搜索结果:' + arz_url + ',' + relative_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n plot = '【连接arzon失败!看到此提示请重新整理nfo!】'\r\n break # 跳出for AVs\r\n if plot == '':\r\n # 在该arz_url网页上查找简介\r\n plotg = re.search(r'作品紹介 ([\\s\\S]*?)', jav_html)\r\n # 成功找到plot\r\n if str(plotg) != 'None':\r\n plot_br = plotg.group(1)\r\n plot = ''\r\n for line in plot_br.split(' '):\r\n line = line.strip()\r\n plot += line\r\n plot = plot.replace('\\n', '').replace('&', '和').replace('\\\\', '#')\\\r\n .replace('/', '#').replace(':', ':').replace('*', '#').replace('?', '?')\\\r\n .replace('\"', '#').replace('<', '【').replace('>', '】')\\\r\n .replace('|', '#').replace('<', '【').replace('>', '】')\\\r\n .replace('〈', '【').replace('〉', '】').replace('&', '和').replace('\\t', '').replace('\\r', '')\r\n break # 跳出for AVs\r\n # 几个搜索结果查找完了,也没有找到简介\r\n if plot == '':\r\n plot = '【arzon有该影片,但找不到简介】'\r\n fail_times += 1\r\n fail_message = ' >arzon有' + str(results_num) + '个搜索结果:' + arz_search_url + ',但找不到简介!:' + relative_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n break # 跳出while\r\n # arzon搜索页面实际是18岁验证\r\n else:\r\n adultg = re.search(r'18歳未満', search_html)\r\n if str(adultg) != 'None':\r\n fail_times += 1\r\n fail_message = ' >第' + str(\r\n fail_times) + '个失败!arzon成人验证,请重启程序:' + relative_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n os.system('pause')\r\n else: # 不是成人验证,也没有简介\r\n fail_times += 1\r\n fail_message = ' >第' + str(\r\n fail_times) + '个失败!arzon找不到该影片,可能被下架:' + arz_search_url + ',' + relative_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n plot = '【影片下架,再无简介】'\r\n break # 跳出while\r\n if if_tran == '是':\r\n plot = tran(ID, SK, plot, t_lang)\r\n #######################################################################\r\n # 1重命名视频\r\n new_mp4 = file[:-len(video_type)].rstrip(' ')\r\n if if_mp4 == '是': # 新文件名\r\n new_mp4 = ''\r\n for j in rename_mp4_list:\r\n new_mp4 += nfo_dict[j]\r\n new_mp4 = new_mp4.rstrip(' ')\r\n cd_msg = ''\r\n if cars_dic[car_num] > 1: # 是CD1还是CDn?\r\n cd_msg = '-cd' + str(srt.episodes)\r\n new_mp4 += cd_msg\r\n # rename mp4\r\n os.rename(root + '\\\\' + file, root + '\\\\' + new_mp4 + video_type)\r\n # file发生了变化\r\n file = new_mp4 + video_type\r\n print(' >修改文件名' + cd_msg + '完成')\r\n if subt_name and if_rename_subt == '是':\r\n os.rename(root + '\\\\' + subt_name, root + '\\\\' + new_mp4 + subt_type)\r\n subt_name = new_mp4 + subt_type\r\n print(' >修改字幕名完成')\r\n\r\n # nfo_dict['视频']用于图片的命名\r\n nfo_dict['视频'] = new_mp4\r\n\r\n # 1.5 归类影片,只针对影片\r\n if if_classify == '是' and file_folder != '文件夹':\r\n # 需要归类影片,针对这个影片\r\n class_root = classify_root + '\\\\'\r\n # 移动的目标文件夹\r\n for j in classify_list:\r\n class_root += nfo_dict[j].rstrip(' .') # C:\\\\Users\\\\JuneRain\\\\Desktop\\\\测试文件夹\\\\1\\\\葵司\\\\\r\n new_root = class_root # 新的影片的目录路径,C:\\\\Users\\\\JuneRain\\\\Desktop\\\\测试文件夹\\\\1\\\\葵司\\\\\r\n new_folder = new_root.split('\\\\')[-1] # 新的影片的目录名称,变成了目标目录“葵司”\r\n if not os.path.exists(new_root): # 不存在目标文件夹\r\n os.makedirs(new_root)\r\n jav_new_path = new_root + '\\\\' + file # 新的影片路径\r\n if not os.path.exists(jav_new_path): # 目标文件夹没有相同的影片\r\n os.rename(root + '\\\\' + file, jav_new_path)\r\n print(' >归类影片文件完成')\r\n if subt_name:\r\n os.rename(root + '\\\\' + subt_name, new_root + '\\\\' + subt_name)\r\n print(' >归类字幕文件完成')\r\n else:\r\n fail_times += 1\r\n fail_message = ' >第' + str(\r\n fail_times) + '个失败!归类失败,重复的影片,归类的目标文件夹已经存在相同的影片:' + jav_new_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n continue\r\n else:\r\n new_root = root # 当前影片的目录路径,在下面的重命名操作中将发生变化\r\n new_folder = root.split('\\\\')[-1] # 当前影片的目录名称,在下面的重命名操作中即将发生变化\r\n\r\n # 2重命名文件夹\r\n if if_folder == '是':\r\n # 新文件夹名rename_folder\r\n new_folder = ''\r\n for j in rename_folder_list:\r\n new_folder += (nfo_dict[j])\r\n new_folder = new_folder.rstrip(' .')\r\n if separate_folder:\r\n if cars_dic[car_num] == 1 or (\r\n cars_dic[car_num] > 1 and cars_dic[car_num] == srt.episodes): # 同一车牌有多部,且这是最后一部,才会重命名\r\n newroot_list = root.split('\\\\')\r\n del newroot_list[-1]\r\n upper2_root = '\\\\'.join(newroot_list)\r\n new_root = upper2_root + '\\\\' + new_folder # 当前文件夹就会被重命名\r\n if not os.path.exists(new_root) or new_root == root: # 目标影片文件夹不存在,或者目标影片文件夹存在,但就是现在的文件夹,即新旧相同\r\n # 修改文件夹\r\n os.rename(root, new_root)\r\n print(' >重命名文件夹完成')\r\n else: # 已经有一个那样的文件夹了\r\n fail_times += 1\r\n fail_message = ' >第' + str(\r\n fail_times) + '个失败!重命名文件夹失败,重复的影片,已存在相同文件夹:' + relative_path + file + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n continue\r\n else:\r\n if not os.path.exists(root + '\\\\' + new_folder): # 已经存在目标文件夹\r\n os.makedirs(root + '\\\\' + new_folder)\r\n # 放进独立文件夹\r\n os.rename(root + '\\\\' + file, root + '\\\\' + new_folder + '\\\\' + file) # 就把影片放进去\r\n new_root = root + '\\\\' + new_folder # 在当前文件夹下再创建新文件夹\r\n print(' >创建独立的文件夹完成')\r\n if subt_name:\r\n os.rename(root + '\\\\' + subt_name, root + '\\\\' + new_folder + '\\\\' + subt_name) # 就把字幕放进去\r\n print(' >移动字幕到独立文件夹')\r\n\r\n # 更新一下relative_path\r\n relative_path = '\\\\' + new_root.lstrip(path) + '\\\\' + file # 影片的相对于所选文件夹的路径,用于报错\r\n # 3写入nfo开始\r\n if if_nfo == '是':\r\n cus_title = ''\r\n for i in title_list:\r\n cus_title += nfo_dict[i]\r\n # 开始写入nfo,这nfo格式是参考的emby的nfo\r\n info_path = new_root + '\\\\' + new_mp4 + '.nfo' #nfo存放的地址\r\n f = open(info_path, 'w', encoding=\"utf-8\")\r\n f.write(\"\\n\"\r\n \"\\n\"\r\n \" \" + plot + \" \\n\"\r\n \" \" + cus_title + \" \\n\"\r\n \" \" + nfo_dict['导演'] + \" \\n\"\r\n \" \" + nfo_dict['发行年份'] + \" \\n\"\r\n \" NC-17 \\n\" \r\n \" NC-17 \\n\"\r\n \" JP \\n\"\r\n \" \" + nfo_dict['发行年月日'] + \" \\n\"\r\n \" \" + nfo_dict['发行年月日'] + \" \\n\"\r\n \" \" + nfo_dict['片长'] + \" \\n\"\r\n \" 日本 \\n\"\r\n \" \" + nfo_dict['片商'] + \" \\n\"\r\n \" \" + nfo_dict['车牌'] + \" \\n\"\r\n \" \" + nfo_dict['车牌'] + \" \\n\"\r\n \" \" + series + \" \\n\")\r\n if simp_trad == '简':\r\n for i in genres:\r\n f.write(\" \" + gen_dict[i] + \" \\n\")\r\n if series:\r\n f.write(\" 系列:\" + series + \" \\n\")\r\n f.write(\" 片商:\" + nfo_dict['片商'] + \" \\n\")\r\n for i in genres:\r\n f.write(\" \" + gen_dict[i] + \" \\n\")\r\n if series:\r\n f.write(\" 系列:\" + series + \" \\n\")\r\n f.write(\" 片商:\" + nfo_dict['片商'] + \" \\n\")\r\n else:\r\n for i in genres:\r\n f.write(\" \" + i + \" \\n\")\r\n if series:\r\n f.write(\" 系列:\" + series + \" \\n\")\r\n f.write(\" 片商:\" + nfo_dict['片商'] + \" \\n\")\r\n for i in genres:\r\n f.write(\" \" + i + \" \\n\")\r\n if series:\r\n f.write(\" 系列:\" + series + \" \\n\")\r\n f.write(\" 片商:\" + nfo_dict['片商'] + \" \\n\")\r\n for i in actors:\r\n f.write(\" \\n \" + i + \" \\n Actor \\n \\n\")\r\n f.write(\" \\n\")\r\n f.close()\r\n print(' >nfo收集完成')\r\n\r\n # 4需要下载三张图片\r\n if if_jpg == '是':\r\n # fanart和poster路径\r\n fanart_path = new_root + '\\\\'\r\n poster_path = new_root + '\\\\'\r\n for i in fanart_list:\r\n fanart_path += nfo_dict[i]\r\n for i in poster_list:\r\n poster_path += nfo_dict[i]\r\n # 下载 海报\r\n print(' >正在下载封面:', cover_url)\r\n cover_list[0] = 0\r\n cover_list[1] = cover_url\r\n cover_list[2] = fanart_path\r\n try:\r\n download_pic(cover_list)\r\n print(' >fanart.jpg下载成功')\r\n except:\r\n print(' >尝试下载fanart失败,正在尝试第二次下载...')\r\n try:\r\n download_pic(cover_list)\r\n print(' >第二次下载成功')\r\n except:\r\n fail_times += 1\r\n fail_message = ' >第' + str(fail_times) + '个失败!下载fanart.jpg失败:' + cover_url + ',' + relative_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n continue\r\n # 下载 poster\r\n # 默认的 全标题.jpg封面\r\n # 裁剪 海报\r\n img = Image.open(fanart_path)\r\n w, h = img.size # fanart的宽 高\r\n ex = int(w * 0.52625) # 0.52625是根据emby的poster宽高比较出来的\r\n poster = img.crop((ex, 0, w, h)) # (ex,0)是左下角(x,y)坐标 (w, h)是右上角(x,y)坐标\r\n poster.save(poster_path, quality=95) # quality=95 是无损crop,如果不设置,默认75\r\n print(' >poster.jpg裁剪成功')\r\n\r\n # 5收集女优头像\r\n if if_sculpture == '是':\r\n if actors[0] == '未知演员':\r\n print(' >未知演员')\r\n else:\r\n for each_actor in actors:\r\n exist_actor_path = '女优头像\\\\' + each_actor + '.jpg'\r\n jpg_type = '.jpg'\r\n if not os.path.exists(exist_actor_path): # 女优jpg图片还没有\r\n exist_actor_path = '女优头像\\\\' + each_actor + '.png'\r\n if not os.path.exists(exist_actor_path): # 女优png图片还没有\r\n fail_times += 1\r\n fail_message = ' >第' + str(\r\n fail_times) + '个失败!没有女优头像:' + each_actor + ',' + relative_path + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n config_actor = configparser.ConfigParser()\r\n config_actor.read('【缺失的女优头像统计For Kodi】.ini', encoding='utf-8-sig')\r\n try:\r\n each_actor_times = config_actor.get('缺失的女优头像', each_actor)\r\n config_actor.set(\"缺失的女优头像\", each_actor, str(int(each_actor_times) + 1))\r\n except:\r\n config_actor.set(\"缺失的女优头像\", each_actor, '1')\r\n config_actor.write(open('【缺失的女优头像统计For Kodi】.ini', \"w\", encoding='utf-8-sig'))\r\n continue\r\n else:\r\n jpg_type = '.png'\r\n actors_path = new_root + '\\\\.actors\\\\'\r\n if not os.path.exists(actors_path):\r\n os.makedirs(actors_path)\r\n shutil.copyfile('女优头像\\\\' + each_actor + jpg_type,\r\n actors_path + each_actor + jpg_type)\r\n print(' >女优头像收集完成:', each_actor)\r\n\r\n # 6归类影片,针对文件夹\r\n if if_classify == '是' and file_folder == '文件夹' and (\r\n cars_dic[car_num] == 1 or (cars_dic[car_num] > 1 and cars_dic[car_num] == srt.episodes)):\r\n # 需要移动文件夹,且,是该影片的最后一集\r\n if separate_folder and classify_root.startswith(root):\r\n print(' >无法归类,请选择该文件夹的上级目录作它的归类根目录', root.lstrip(path))\r\n continue\r\n class_root = classify_root + '\\\\'\r\n # 移动的目标文件夹\r\n for j in classify_list:\r\n class_root += nfo_dict[j].rstrip(' .') # C:\\\\Users\\\\JuneRain\\\\Desktop\\\\测试文件夹\\\\1\\\\葵司\\\\\r\n new_new_root = class_root + new_folder # 移动的目标文件夹 C:\\\\Users\\\\JuneRain\\\\Desktop\\\\测试文件夹\\\\1\\\\葵司\\\\【葵司】AVOP-127\r\n if not os.path.exists(new_new_root): # 不存在目标目录\r\n os.makedirs(new_new_root)\r\n jav_files = os.listdir(new_root)\r\n for i in jav_files:\r\n os.rename(new_root + '\\\\' + i, new_new_root + '\\\\' + i)\r\n os.rmdir(new_root)\r\n print(' >归类文件夹完成')\r\n else:\r\n # print(traceback.format_exc())\r\n fail_times += 1\r\n fail_message = ' >第' + str(fail_times) + '个失败!归类失败,重复的影片,归类的根目录已存在相同文件夹:' + new_new_root + '\\n'\r\n print(fail_message, end='')\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n continue\r\n\r\n except:\r\n fail_times += 1\r\n fail_message = ' >第' + str(fail_times) + '个失败!发生错误,如一直在该影片报错请截图并联系作者:' + relative_path + '\\n' + traceback.format_exc() + '\\n'\r\n fail_list.append(fail_message)\r\n write_fail(fail_message)\r\n continue\r\n # 完结撒花\r\n print('\\n当前文件夹完成,', end='')\r\n if fail_times > 0:\r\n print('失败', fail_times, '个! ', path, '\\n')\r\n if len(fail_list) > 0:\r\n for fail in fail_list:\r\n print(fail, end='')\r\n print('\\n“【记得清理它】失败记录.txt”已记录错误\\n')\r\n else:\r\n print('没有处理失败的AV,干得漂亮! ', path, '\\n')\r\n\r\n start_key = input('回车继续选择文件夹整理:')\r\n","sub_path":"pre_versions/1.0.3/youma_javbus.py","file_name":"youma_javbus.py","file_ext":"py","file_size_in_byte":67706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"320676280","text":"from __future__ import print_function\r\nimport os\r\nfrom PIL import Image\r\n\r\nall_files = os.listdir(os.curdir) #获取所有文件\r\nfor infile in all_files: \r\n f, e = os.path.splitext(infile) #分离文件名与扩展名(f=name,e=extension)\r\n outfile = f + '.png'\r\n if infile != outfile:\r\n try:\r\n Image.open(infile).save(outfile) #save()第二个参数指定图片格式\r\n except IOError:\r\n print('cannot convert', infile)\r\n","sub_path":"ztcooper/0000/jpg2png.py","file_name":"jpg2png.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"232964513","text":"def main():\n import argparse\n import os\n import subprocess\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--port', '-p', help='Port to run the API webserver on', type=int, default=8000)\n parser.add_argument(\n '--prom_addr', '-a', help='Prometheus address connected to Poseidon, i.e. \"prometheus:9090\"', default='prometheus:9090')\n args = parser.parse_args()\n\n os.environ['PROM_ADDR'] = args.prom_addr\n process = subprocess.Popen(['gunicorn', '-b :'+str(args.port), '-k eventlet', '-w 4', '--reload', 'poseidon_api.api'],\n stdout=subprocess.PIPE,\n universal_newlines=True)\n\n while True:\n output = process.stdout.readline()\n print(output.strip())\n return_code = process.poll()\n if return_code is not None:\n for output in process.stdout.readlines():\n print(output.strip())\n break\n","sub_path":"src/api/api/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"486234146","text":"# -*- coding: utf-8 -*- \n# @Time : 2020/10/14 11:01 \n# @Author : 张丽雯 \n# @File : test_cleancase.py \n# @中文描述 : 清洁配置用例\nimport sys\nimport pytest\nfrom DataApp.CleanData import *\nfrom src.public.Logger import *\nfrom src.pageobjectAPP.pageClean import *\nfrom src.public.common.Close_current_tab import Close_current_tab\n\n\nclass Test_Clean:\n def test_clean_login(self):\n login_clean()\n assert new_page_source('清洁配置')\n\n # 新增清洁配置\n # @pytest.mark.skip\n def test_add_clean(self):\n log = Log()\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n clean_add(add_code1,name,ruletype)\n assert name in new_get_text('//div[@role=\"row\" and @row-index=\"0\"]//div[contains(.,\"clean\")]')\n\n #筛选\n def test_search_clean(self):\n clean_search_web(text)\n assert new_page_source(text)\n\n #编辑清洁配置\n def test_edit_clean(self):\n log = Log()\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n clean_edit('xiugai','物料')\n assert 'xiugai' in new_get_text('//div[@role=\"row\" and @row-index=\"0\"]//div[contains(.,\"xiugai\")]')\n\n # 删除清洁配置\n def test_delete_clean(self):\n log = Log()\n log.info(\"开始执行用例%s\" % sys._getframe().f_code.co_name)\n clean_delete()\n assert (is_text_present('xiugai'),'删除失败!')\n Close_current_tab()\n","sub_path":"TestcaseApp/Weigh/test_clean.py","file_name":"test_clean.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"100149692","text":"#!/usr/bin/env python\n\nimport rospy\nfrom crazyflie.srv import *\n\nif __name__ == \"__main__\":\n rospy.init_node('crazyflie_add', anonymous=True)\n uri = rospy.get_param(\"~uri\")\n tf_prefix = rospy.get_param(\"~tf_prefix\")\n roll_trim = float(rospy.get_param(\"~roll_trim\", \"0\"))\n pitch_trim = float(rospy.get_param(\"~pitch_trim\", \"0\"))\n enable_logging = rospy.get_param(\"~enable_logging\", \"True\")\n rospy.loginfo(\"wait_for_service /add_crazyflie\")\n rospy.wait_for_service('/add_crazyflie')\n rospy.loginfo(\"found /add_crazyflie\")\n add_crazyflie = rospy.ServiceProxy('/add_crazyflie', AddCrazyflie)\n add_crazyflie(uri, tf_prefix, roll_trim, pitch_trim, enable_logging)\n","sub_path":"crazyflie/scripts/crazyflie_add.py","file_name":"crazyflie_add.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"535778801","text":"#\n# Copyright (c) 2011-2018, Hortonworks Inc. All rights reserved.\n#\n# Except as expressly permitted in a written agreement between your\n# company and Hortonworks, Inc, any use, reproduction, modification,\n# redistribution, sharing, lending or other exploitation of all or\n# any part of the contents of this file is strictly prohibited.\n#\n#\nimport os\nimport json\nfrom taskreporter.taskreporter import TaskReporter\nfrom beaver.component.atlas_resources.business_catalog.baseREST import BaseAPI\nfrom beaver.component.atlas_resources.atlas import Atlas\n\n\nclass TermAPI(BaseAPI):\n def __init__(self):\n BaseAPI.__init__(self, 'api/atlas/v2/glossary/term')\n\n @TaskReporter.report_test()\n def create_terms(self, body, code=200):\n url = os.path.join(self.base_url, 'api/atlas/v2/glossary/terms')\n response, status = Atlas.http_put_post_request(url=url, data=json.dumps(body))\n assert status == code\n return response\n\n @TaskReporter.report_test()\n def associate_term_to_entities(self, guid, entity_guids_list, code=204):\n url = os.path.join(self.base_url, 'api/atlas/v2/glossary/terms', guid, \"assignedEntities\")\n body = list()\n for each in entity_guids_list:\n body.append({\"guid\": each})\n _response, status = Atlas.http_put_post_request(url=url, data=json.dumps(body))\n assert status == code\n\n @TaskReporter.report_test()\n def disassociate_term_to_entities(self, guid, entity_guids_dict, code=204):\n url = os.path.join(self.base_url, 'api/atlas/v2/glossary/terms', guid, \"assignedEntities\")\n body = list()\n for entity_guid, relationship_guid in entity_guids_dict.iteritems():\n body.append({\"guid\": entity_guid, \"relationshipGuid\": relationship_guid})\n status = Atlas.http_delete_request(url=url, body=json.dumps(body))\n assert status == code\n\n @TaskReporter.report_test()\n def get_assigned_entities(self, guid, code=200):\n url = os.path.join(self.base_url, 'api/atlas/v2/glossary/terms', guid, \"assignedEntities\")\n response, status = Atlas.http_get_request(url=url)\n assert status == code\n return response\n\n @TaskReporter.report_test()\n def get_related_terms(self, guid, code=200):\n url = os.path.join(self.base_url, 'api/atlas/v2/glossary/terms', guid, \"related\")\n response, status = Atlas.http_get_request(url=url)\n assert status == code\n return response\n","sub_path":"beaver/component/atlas_resources/business_catalog/termREST.py","file_name":"termREST.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"207498413","text":"\n# Jenkins activator job parameters\nJENKINS_TOKEN = 'activatorbuild'\nJENKINS_DEPLOY_ACTIVATOR_JOB = 'activator-pipeline'\nJENKINS_DEPLOY_ACTIVATOR_JOB_WITH_JSON = 'activator-pipeline-json'\nDEPLOYMENT_PROJECT_ID = \"projectid\"\nACTIVATOR_GIT_REPO_URL = \"repourl\"\nACTIVATOR_GIT_REPO_BRANCH = \"repobranch\"\nACTIVATOR_PARAMS = \"activator_params\"\nENVIRONMENT_PARAMS = \"environment_params\"\nJOB_UNIQUE_ID = \"job_unique_id\"\n\n\n\n","sub_path":"src/main/python/tranquilitybase/gcpdac/celery_worker/tasks/jenkins/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"227576200","text":"# stdlib\nfrom typing import Any\nfrom typing import List as TypeList\nfrom typing import Optional\nfrom typing import Tuple as TypeTuple\n\n# third party\nimport numpy as np\nfrom scipy import optimize\nfrom sympy.core.basic import Basic as BasicSymbol\n\n# relative\nfrom ...common import UID\nfrom ..entity import Entity\nfrom ..search import create_lookup_tables_for_symbol\nfrom ..search import create_searchable_function_from_polynomial\nfrom ..search import max_lipschitz_via_jacobian\nfrom ..search import minimize_function\nfrom ..search import ssid2obj\nfrom .abstract.intermediate_scalar import IntermediateScalar\nfrom .abstract.scalar import Scalar\n\n\nclass IntermediateGammaScalar(IntermediateScalar):\n \"\"\"\n A Superclass for Scalars with data from multiple entities (GammaScalars).\n Most importantly, this is where all of the operations (+/-/*/div) are implemented,\n as well as the various methods with which to perform the search for the max Lipschitz.\n \"\"\"\n\n def __init__(\n self,\n poly: BasicSymbol,\n min_val: float,\n max_val: float,\n id: Optional[UID] = None,\n ) -> None:\n self.poly = poly\n self.id = id if id else UID()\n self._min_val = min_val\n self._max_val = max_val\n\n # GammaScalar +/-/*/div other ---> GammaScalar\n def __add__(self, other: Any) -> IntermediateScalar:\n if isinstance(other, Scalar):\n # relative\n from .intermediate_phi_scalar import IntermediatePhiScalar\n\n if isinstance(other, IntermediatePhiScalar):\n other = other.gamma\n return IntermediateGammaScalar(\n poly=self.poly + other.poly,\n min_val=self.min_val + other.min_val,\n max_val=self.max_val + other.max_val,\n )\n return IntermediateGammaScalar(\n poly=self.poly + other,\n min_val=self.min_val + other,\n max_val=self.max_val + other,\n )\n\n def __sub__(self, other: Any) -> IntermediateScalar:\n if isinstance(other, Scalar):\n # relative\n from .intermediate_phi_scalar import IntermediatePhiScalar\n\n if isinstance(other, IntermediatePhiScalar):\n other = other.gamma\n return IntermediateGammaScalar(\n poly=self.poly - other.poly,\n min_val=self.min_val - other.min_val,\n max_val=self.max_val - other.max_val,\n )\n return IntermediateGammaScalar(\n poly=self.poly - other,\n min_val=self.min_val - other,\n max_val=self.max_val - other,\n )\n\n def __mul__(self, other: Any) -> IntermediateScalar:\n if isinstance(other, Scalar):\n # relative\n from .intermediate_phi_scalar import IntermediatePhiScalar\n\n if isinstance(other, IntermediatePhiScalar):\n other = other.gamma\n\n max_val = max(\n self.min_val * other.min_val,\n self.min_val * other.max_val,\n self.max_val * other.min_val,\n self.max_val * other.max_val,\n )\n\n min_val = min(\n self.min_val * other.min_val,\n self.min_val * other.max_val,\n self.max_val * other.min_val,\n )\n\n return IntermediateGammaScalar(\n poly=self.poly * other.poly, max_val=max_val, min_val=min_val\n )\n\n max_val = max(\n self.min_val * other,\n self.max_val * other,\n )\n\n min_val = min(\n self.min_val * other,\n self.max_val * other,\n )\n\n return IntermediateGammaScalar(\n poly=self.poly * other, min_val=min_val, max_val=max_val\n )\n\n def max_lipschitz_via_explicit_search(\n self, force_all_searches: bool = False\n ) -> TypeTuple[TypeList[optimize.OptimizeResult], np.float64]:\n\n r1 = np.array([x.poly for x in self.input_scalars]) # type: ignore\n\n # relative\n from .gamma_scalar import GammaScalar\n\n r2_diffs = np.array(\n [\n GammaScalar(x.min_val, x.value, x.max_val, entity=x.entity).poly # type: ignore\n for x in self.input_scalars\n ]\n )\n r2 = r1 + r2_diffs\n\n fr1 = self.poly\n fr2 = self.poly.copy().subs({x[0]: x[1] for x in list(zip(r1, r2))})\n\n left = np.sum(np.square(fr1 - fr2)) ** 0.5\n right = np.sum(np.square(r1 - r2)) ** 0.5\n\n C = -left / right\n\n i2s, s2i = create_lookup_tables_for_symbol(C)\n search_fun = create_searchable_function_from_polynomial(\n poly=C, symbol2index=s2i\n )\n\n r1r2diff_zip = list(zip(r1, r2_diffs))\n\n s2range = {}\n for _input_scalar, _additive_counterpart in r1r2diff_zip:\n input_scalar = ssid2obj[_input_scalar.name]\n additive_counterpart = ssid2obj[_additive_counterpart.name]\n\n s2range[input_scalar.ssid] = (input_scalar.min_val, input_scalar.max_val)\n s2range[additive_counterpart.ssid] = (\n input_scalar.min_val,\n input_scalar.max_val,\n )\n\n rranges = list()\n for _, symbol in enumerate(i2s):\n rranges.append(s2range[symbol])\n\n r2_indices_list = list()\n min_max_list = list()\n for r2_val in r2:\n r2_syms = [ssid2obj[x.name] for x in r2_val.free_symbols]\n r2_indices = [s2i[x.ssid] for x in r2_syms]\n\n r2_indices_list.append(r2_indices)\n min_max_list.append((r2_syms[0].min_val, r2_syms[0].max_val))\n\n functions = list()\n for i in range(2):\n f1 = (\n lambda x, i=i: x[r2_indices_list[i][0]]\n + x[r2_indices_list[i][1]]\n + min_max_list[i][0]\n )\n f2 = (\n lambda x, i=i: -(x[r2_indices_list[i][0]] + x[r2_indices_list[i][1]])\n + min_max_list[i][1]\n )\n\n functions.append(f1)\n functions.append(f2)\n\n constraints = [{\"type\": \"ineq\", \"fun\": f} for f in functions]\n\n def non_negative_additive_terms(symbol_vector: np.ndarray) -> np.float64:\n out = 0\n for index in [s2i[x.name] for x in r2_diffs]:\n out += symbol_vector[index] ** 2\n # there's a small bit of rounding error from this constraint - this should\n # only be used as a double check or as a backup!!!\n return out ** 0.5 - 1 / 2 ** 16\n\n constraints.append({\"type\": \"ineq\", \"fun\": non_negative_additive_terms})\n results = minimize_function(\n f=search_fun,\n rranges=rranges,\n constraints=constraints,\n force_all_searches=force_all_searches,\n )\n\n return results, C\n\n def max_lipschitz_via_jacobian(\n self,\n input_entity: Optional[Entity] = None,\n data_dependent: bool = True,\n force_all_searches: bool = False,\n try_hessian_shortcut: bool = False,\n ) -> TypeList[optimize.OptimizeResult]:\n return max_lipschitz_via_jacobian(\n scalars=[self],\n input_entity=input_entity,\n data_dependent=data_dependent,\n force_all_searches=force_all_searches,\n try_hessian_shortcut=try_hessian_shortcut,\n ) # type: ignore\n\n @property\n def max_lipschitz(self) -> float:\n result = self.max_lipschitz_via_jacobian()[0][-1]\n if isinstance(result, float):\n return -result\n else:\n return -float(result.fun)\n\n def max_lipschitz_wrt_entity(self, entity: Entity) -> float:\n result = self.max_lipschitz_via_jacobian(input_entity=entity)[0][-1]\n if isinstance(result, float):\n return -result\n else:\n return -float(result.fun)\n","sub_path":"packages/syft/src/syft/core/adp/scalar/intermediate_gamma_scalar.py","file_name":"intermediate_gamma_scalar.py","file_ext":"py","file_size_in_byte":7918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"440308477","text":"import socket\n\n'''\nA work in progress. Currently debating whether to use it or not.\nIt does what it says on the tin: handles transfer of data over TCP\n'''\n\ndef createServerSocket(hostname='127.0.0.1', port=80):\n '''\n Create a server socket from hostname/IP address & port number.\n If no arguments are passed, a local server socket will be established.\n '''\n serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n serversocket.bind((hostname, port))\n # Start listening\n serversocket.listen()","sub_path":"tcpcommunication.py","file_name":"tcpcommunication.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"57228154","text":"import json\nimport xml.etree.ElementTree as et\nimport logging\nlogging.basicConfig(filename='out.log', level=logging.DEBUG,format='%(asctime)s %(message)s')\n\n\nclass Song:\n # Constructor to create a Song object.\n def __init__(self, songId, title, artist, genre, year):\n self.songId = songId\n self.title = title\n self.artist = artist\n self.genre = genre\n self.year = year\n logging.info(\"-- Factory: Song Object Constructed for songId: {}\".format(self.songId))\n\nclass SongSerializer:\n \n def serialize(self, song, format):\n serializer = self._get_serializer(format)\n logging.info(\"-- Factory: Song Object Serialized for songId: {}\".format(self.songId))\n return serializer(song)\n\n def _get_serializer(self, format):\n if format == 'JSON':\n return self._serialize_to_json\n elif format == 'XML':\n return self._serialize_to_xml\n else:\n raise ValueError(format)\n\n\n def _serialize_to_json(self, song):\n payload = {\n \"id\" : song.songId,\n \"title\": song.title,\n \"artist\": song.artist,\n \"genre\": song.genre,\n \"year\": song.year\n }\n logging.info(\"-- Factory: Song Object Converted to JSON for songId: {}\".format(self.songId))\n return json.dumps(payload)\n\n def _serialize_to_xml(self, song):\n song_element = et.Element('song', attrib={'id': song.songId})\n\n title = et.SubElement(song_element, 'title')\n title.text = song.title\n\n artist = et.SubElement(song_element, 'artist')\n artist.text = song.artist\n\n genre = et.SubElement(song_element, 'genre')\n genre.text = song.genre\n\n year = et.SubElement(song_element, 'year')\n year.text = song.year\n\n logging.info(\"-- Factory: Song Object Converted to XML for songId: {}\".format(self.songId))\n return et.tostring(song_element, encoding='unicode')","sub_path":"serializer_factory.py","file_name":"serializer_factory.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"293906867","text":"import getpass\nimport logging\nimport pickle\nimport sys\nimport time\n\nimport mysql.connector\nimport pandas as pd\nimport pymysql\nimport sqlalchemy\nfrom openmap.util.log import logger\nfrom mysql.connector import errorcode\n\n# logger = logging.getLogger(__name__)\n\n__version__ = '0.1'\n__author__ = 'Conrard TETSASSI'\n__maintainer__ = 'Conrard TETSASSI'\n__email__ = 'giresse.feugmo@gmail.com'\n__status__ = 'Development'\n\n\ndef countdown(sleeptime):\n for remaining in range(sleeptime, 0, -1):\n sys.stdout.write('\\r')\n sys.stdout.write(\n '{:4d} seconds remaining before next refresh.'.format(remaining))\n sys.stdout.flush()\n time.sleep(1)\n sys.stdout.write('\\n')\n\n\nclass RemoteDB:\n \"\"\"Client to interact with a sql data base \"\"\"\n\n def __init__(self, host, user, port, dbname, password=None):\n self.host = host\n self.user = user\n self.port = port\n self.dbname = dbname\n self.password = password # getpass.getpass()\n self.conn = None\n self.cursor = None\n\n @logger.catch\n def _connect(self):\n \"\"\"Open connection to remote database server. \"\"\"\n if self.password is None:\n self.password = getpass.getpass(\n prompt='Enter the database Password: ', stream=None)\n\n if self.conn is None:\n try:\n logger.info('Opening connection to sql database')\n # self.conn = mysql.connector.connect(host=self.host,\n # user=self.user,\n # port=self.port,\n # password=self.password,\n # database=self.dbname)\n self.conn = pymysql.connect(\n host=self.host, user=self.user, port=self.port, passwd=self.password, db=self.dbname\n )\n logger.info(\n 'Connection established to server: database [{}]'.format(self.dbname))\n # except mysql.connector.Error as error:\n except pymysql.Error as error:\n logger.error(\n 'Authentication to MySQL table failed : {}'.format(error))\n raise error\n except TimeoutError as e:\n logger.error(f'Timeout.. trying again.')\n # continue\n return self.conn\n\n # self.conn = self._connect()\n\n @logger.catch\n def disconnect(self):\n \"\"\"Close connection to the database server\"\"\"\n try:\n self.cursor.close()\n except Exception as err:\n logger.error(f'{err}')\n\n try:\n self.conn.close()\n self.conn = None\n logger.warning(f'database disconnected')\n except Exception as err:\n logger.error(f'{err}')\n\n @logger.catch\n def checkDbExists(self, DB_NAME=None, dbcon=None):\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n self.cursor = dbcon.cursor()\n\n if DB_NAME is None:\n DB_NAME = self.dbname\n\n self.cursor.execute('SHOW DATABASES')\n\n db_list = [name[0] for name in self.cursor]\n if DB_NAME in db_list:\n self.cursor.close()\n return True\n\n self.cursor.close()\n return False\n\n @logger.catch\n def checkTableExists(self, tablename, DB_NAME=None, dbcon=None):\n \"\"\"\n :param tablename:\n :param dbcon:\n :return:\n \"\"\"\n if DB_NAME is None:\n DB_NAME = self.dbname\n\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n self.cursor = dbcon.cursor()\n\n self.cursor.execute(\n \"SELECT COUNT(*) FROM information_schema.tables WHERE table_name = '{0}'\".format(\n tablename.replace('\\'', '\\'\\'')\n )\n )\n if self.cursor.fetchone()[0] == 1:\n self.cursor.close()\n logger.info('Table [{}] found in the database [{}]'.format(\n tablename, DB_NAME))\n return True\n\n self.cursor.close()\n logger.info('Table [{}] not found in the database [{}]'.format(\n tablename, DB_NAME))\n return False\n\n @logger.catch\n def checkColumnExists(self, tablename, colname, dbcon=None):\n \"\"\"\n :param tablename:\n :param dbcon:\n :return:\n \"\"\"\n\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n self.cursor = dbcon.cursor()\n\n try:\n sql = f'SHOW columns FROM {tablename}'\n self.cursor.execute(sql)\n colnames = [column[0] for column in self.cursor.fetchall()]\n self.cursor.close()\n if colname in colnames:\n return True\n return False\n except Exception as err:\n logger.error(f' {err}')\n # exit(1)\n\n @logger.catch\n def create_database(self, DB_NAME=None, dbcon=None):\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n self.cursor = dbcon.cursor()\n if DB_NAME is None:\n DB_NAME = self.dbname\n\n try:\n self.cursor.execute(\n \"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'\".format(DB_NAME))\n except pymysql.Error as err:\n logger.info(' {}'.format(err))\n # print(\" {}\".format(err))\n # exit(0)\n\n try:\n self.cursor.execute('USE {}'.format(DB_NAME))\n except pymysql.Error as err:\n logger.info('Database {} does not exists.'.format(DB_NAME))\n # print(\"Database {} does not exists.\".format(DB_NAME))\n if err.errno == errorcode.ER_BAD_DB_ERROR:\n # create_database(self.cursor)\n # print(\"Database {} created successfully.\".format(DB_NAME))\n logger.info(\n 'Database {} created successfully.'.format(DB_NAME))\n dbcon.database = DB_NAME\n else:\n logger.error(f' {err}')\n # print(err)\n # exit(1)\n\n @logger.catch\n def create_table(self, table_name, table_description, DB_NAME=None, dbcon=None, drop=False):\n \"\"\"\n :param table_name:\n :param table_description:\n :param dbcon:\n :param drop:\n :return:\n \"\"\"\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n self.cursor = dbcon.cursor()\n\n if DB_NAME is None:\n DB_NAME = self.dbname\n\n try:\n logger.info('Creating table [{}]: '.format(table_name))\n self.cursor.execute(table_description)\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:\n if drop:\n logger.info('Dropping table [{}]: '.format(table_name))\n self.cursor.execute(\n 'DROP TABLE IF EXISTS {}'.format(table_name))\n else:\n logger.error(f'Table [{table_name}] already exists.')\n else:\n logger.error(f'{err.msg}')\n else:\n logger.info('Table created ')\n\n self.cursor.close()\n # dbcon.close()\n\n @logger.catch\n def df_to_sql(self, df, tablename, dbcon=None):\n \"\"\"\n use the sqlalchemy package to upload a Dataframe\n :param df: Dataframe\n :param tablename:\n :param dbcon:\n :return:\n \"\"\"\n\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n\n engine = sqlalchemy.create_engine(\n 'mysql+pymysql://{user}:{pw}@{host}/{db}'.format(\n host=self.host, db=self.dbname, user=self.user, pw=self.password\n )\n )\n\n try:\n logger.info(f'Writing [{tablename}] table to aws')\n df.to_sql(\n name=tablename,\n con=engine,\n if_exists='append',\n index=False,\n # It means index of DataFrame will save. Set False to ignore\n # the index of DataFrame.\n chunksize=1000,\n ) # Just means chunksize. If DataFrame is big will need this param\n\n except ValueError as vx:\n logger.error(f'{vx}')\n\n except Exception as ex:\n logger.error(f'{ex}')\n\n else:\n logger.info(f'Table {tablename} created successfully')\n\n finally:\n self.cursor.close()\n\n @logger.catch\n def insert_Dataframe_to_DB(self, df, tablename, dbcon=None):\n \"\"\" Insert a entire data frame into sql table\"\"\"\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n self.cursor = dbcon.cursor()\n\n # creating column list for insertion\n cols = '`,`'.join([str(i) for i in df.columns.tolist()])\n\n # Insert DataFrame recrds one by one.\n for i, row in df.iterrows():\n sql = f'INSERT INTO `{tablename}` (`' + cols + \\\n '`) VALUES (' + '%s,' * (len(row) - 1) + '%s)'\n self.cursor.execute(sql, tuple(row))\n\n # the connection is not necesserly autocommitted(pymysql,\n # mysql-connection) , so we must commit to save our changes\n try:\n dbcon.commit()\n except BaseException:\n pass\n finally:\n self.cursor.close()\n\n @logger.catch\n def df_to_sqltable(self, df, tablename, DB_NAME=None, dbcon=None, drop=False):\n \"\"\"\n :param df: DataFrame to upload\n :param tablename: name of the table\n :param DB_NAME:\n :param dbcon:\n :param drop: drop the table if exists\n :return:\n \"\"\"\n\n colms = ['`' + i + '`' for i in df.columns.tolist()]\n types = [str(df[col].dtypes) for col in df.columns.tolist()]\n # if isinstance(row[prop], (np.ndarray, np.generic)):\n for i, typ in enumerate(types):\n if typ == 'object':\n types[i] = 'varchar(255)'\n elif typ == 'float64' or 'float32':\n types[i] = 'FLOAT' # 'DECIMAL(12, 6)'\n elif typ == 'int64' or 'int32':\n types[i] = 'INT'\n\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n self.cursor = dbcon.cursor()\n\n if DB_NAME is None:\n DB_NAME = self.dbname\n\n description = [' '.join([i, j]) for i, j in zip(colms, types)]\n\n description = ','.join([str(i) for i in description])\n sql = f'CREATE TABLE {tablename} (' + description + ')'\n\n try:\n logger.info('Creating table [{}]: '.format(tablename))\n self.cursor.execute(sql)\n\n # creating column list for insertion\n cols = '`,`'.join([str(i) for i in df.columns.tolist()])\n\n # Insert DataFrame recrds one by one.\n for i, row in df.iterrows():\n sql = f'INSERT INTO `{tablename}` (`' + cols + \\\n '`) VALUES (' + '%s,' * (len(row) - 1) + '%s)'\n self.cursor.execute(sql, tuple(row))\n try:\n dbcon.commit()\n except BaseException:\n pass\n\n logger.info(\n 'Table [{}] has been created successfully'.format(tablename))\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:\n if drop:\n logger.info('Dropping table [{}]: '.format(tablename))\n self.cursor.execute(\n 'DROP TABLE IF EXISTS {}'.format(tablename))\n self.cursor.execute(\n f' CREATE TABLE {tablename} (' + description + ')}')\n\n # creating column list for insertion\n cols = '`,`'.join([str(i) for i in df.columns.tolist()])\n\n # Insert DataFrame recrds one by one.\n for i, row in df.iterrows():\n sql = f'INSERT INTO `{tablename}` (`' + cols + \\\n '`) VALUES (' + '%s,' * (len(row) - 1) + '%s)'\n self.cursor.execute(sql, tuple(row))\n try:\n dbcon.commit()\n except BaseException:\n pass\n\n logger.info(\n 'Table [{}] has been created successfully'.format(tablename))\n else:\n logger.error(f'Table [{tablename}] already exists.')\n else:\n logger.error(f' {err.msg}')\n\n self.cursor.close()\n # dbcon.close()\n\n @logger.catch\n def read_table_to_df(self, tablename, dbcon=None):\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n\n try:\n pandas_df = pd.read_sql(\n 'SELECT * FROM {}'.format(tablename), dbcon)\n except ValueError as vx:\n logger.error(f'{vx}')\n\n except Exception as ex:\n logger.error(f'{ex}')\n\n else:\n logger.info(f'Table {tablename} loaded successfully to Dataframe')\n\n finally:\n self.cursor.close()\n return pandas_df\n\n @logger.catch\n def load_table_to_pandas(self, tablename, dbcon=None):\n \"\"\"\n :param tablename: name of the table\n :param dbcon: connection to the database\n :return: pandas dataframe\n \"\"\"\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n\n pandas_df = pd.read_sql('select * from {} '.format(tablename), dbcon)\n\n for col in pandas_df.columns:\n try:\n pandas_df[col] = pandas_df.apply(\n lambda x: pickle.loads(x[col]), axis=1)\n except BaseException:\n continue\n\n for col in pandas_df.columns:\n try:\n pandas_df[col] = pandas_df.apply(\n lambda x: x[col].decode(), axis=1)\n except BaseException:\n continue\n\n return pandas_df\n\n @logger.catch\n def get_columns_name(self, table_name, dbcon=None):\n \"\"\"\n\n :param table_name:\n :param dbcon:\n :return: Column Names\n \"\"\"\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n try:\n self.cursor = dbcon.cursor()\n sql_select_query = 'select * from {}'.format(table_name)\n self.cursor.execute(sql_select_query)\n field_names = [i[0] for i in self.cursor.description]\n except Exception as ex:\n logger.error(f'{ex}')\n finally:\n self.cursor.close()\n return field_names\n\n # def get_value(self,tablename, colame, id_col,rowname, dbcon=None):\n # \"\"\"\n #\n # :param tablename:\n # :param colame:\n # :param rowname:\n # :param dbcon:\n # :return: the value value of colame/rowname,\n # \"\"\"\n # if dbcon is None:\n # self.conn = self._connect()\n # dbcon = self.conn\n # try:\n # self.cursor = dbcon.cursor()\n # sql = f\"SELECT {colame} FROM {tablename} WHERE {id_col}={rowname}\"\n # self.cursor.execute(sql)\n # myresult = self.cursor.fetchall()\n # except Exception as ex:\n # logger.error(f\"{ex}\")\n # finally:\n # self.cursor.close()\n # return myresult\n\n # def get_structrure(self, tablename, struc_id, dbcon=None):\n # \"\"\"\n # :param tablename:\n # :param struc_id: list of id to fecth\n # :param dbcon:\n # :return: return a list of Ase Atoms class\n # \"\"\"\n #\n # if dbcon is None:\n # self.conn = self._connect()\n # dbcon = self.conn\n #\n # field_names = self.get_columns_name(tablename, dbcon)\n #\n # self.cursor = dbcon.cursor()\n # atms = []\n # sql_select_query = \"select * from {} where id = %s\".format(tablename)\n # for struc in struc_id:\n # self.cursor.execute(sql_select_query, (struc_id,))\n # record = self.cursor.fetchall()\n # numbers = pickle.loads(record[0][field_names.index('numbers')])\n # positions = pickle.loads(record[0][field_names.index('positions')])\n # cell = pickle.loads(record[0][field_names.index('cell')])\n # #pbc = pickle.loads(record[0][field_names.index('pbc')])\n #\n # atm = Atoms(numbers=numbers, positions=positions, cell=cell)\n # atms.append(atm)\n # self.cursor.close()\n # return atms\n @logger.catch\n def get_value(self, tablename, colname, id_col, rowname, dbcon=None):\n \"\"\"\n :param tablename: name of the table\n :param colname: column to check\n :param id_col: name of the column with structure id\n :param rowname: id of the structure == row\n :param dbcon: connection to db\n :return: return value of column [colname] at row [rowname]\n \"\"\"\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n\n self.cursor = dbcon.cursor()\n try:\n sql_select_query = f\"select {colname} from {tablename} where {id_col} ='{rowname}' \"\n self.cursor.execute(sql_select_query)\n record = self.cursor.fetchone()\n return record[0]\n except Exception as ex:\n logger.error(f'{ex}')\n # raise Exception(f\"{ex}\")\n finally:\n self.cursor.close()\n\n @logger.catch\n def add_column(self, tablename, colname, coltype, dbcon=None):\n \"\"\"\n add column in a table\n :param tablename:\n :param colname:\n :param coltype: type off the colunm to add\n :param dbcon:\n :return:\n \"\"\"\n\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n try:\n self.cursor = dbcon.cursor()\n sql = f'ALTER TABLE {tablename} ADD {colname} {coltype}'\n self.cursor.execute(sql)\n logging.info(\n f'Table [{tablename}] altered with column [{colname}]')\n except Exception as ex:\n logger.error(f'{ex}')\n finally:\n self.cursor.close()\n\n @logger.catch\n def drop_column(self, tablename, colname, dbcon=None):\n \"\"\"\n drop a column in a table\n :param tablename:\n :param colname:\n :param dbcon:\n :return:\n \"\"\"\n\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n try:\n self.cursor = dbcon.cursor()\n sql = f'ALTER TABLE {tablename} DROP COLUMN {colname}'\n self.cursor.execute(sql)\n logging.info(f' column [{colname}] in table [{tablename}]')\n except Exception as ex:\n logger.error(f'{ex}')\n finally:\n self.cursor.close()\n\n @logger.catch\n def insert_value(self, tablename, colname, val, id_col, struc_id, dbcon=None):\n \"\"\"\n :param tablename:\n :param colname:\n :param val:\n :param id_col:\n :param struc_id:\n :param dbcon:\n :return:\n \"\"\"\n\n if dbcon is None:\n self.conn = self._connect()\n dbcon = self.conn\n try:\n self.cursor = dbcon.cursor()\n sql = f\"UPDATE {tablename} SET {colname}= {val} WHERE {id_col}='{struc_id}'\"\n self.cursor.execute(sql)\n except Exception as ex:\n logger.error(f'{ex}')\n finally:\n dbcon.commit()\n self.cursor.close()\n\n @logger.catch\n def monitoring(self, jobs, tablename, colname, id_col, sleeptime=120, dbcon=None):\n \"\"\"\n :param jobs: list of dictionary with job information\n :return:\n \"\"\"\n # if dbcon is None:\n # self.disconnect()\n # self.conn = self._connect()\n # dbcon = self.conn\n # self.cursor = dbcon.cursor()\n\n status_list = [None for job in jobs]\n while not all(status is not None for status in status_list):\n self.disconnect()\n status_list = [self.get_value(\n tablename, colname, id_col, job) for job in jobs]\n for job, status in zip(jobs, status_list):\n if status is not None:\n logger.info(f'{job}: COMPLETED')\n else:\n logger.info(f'{job}: PENDING')\n #\n if all(status is not None for status in status_list):\n logger.info(f'All Jobs COMPLETED')\n continue\n else:\n countdown(sleeptime)\n\n return status_list\n","sub_path":"openmap/data_wrapper/mysql_db.py","file_name":"mysql_db.py","file_ext":"py","file_size_in_byte":21102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"543802091","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom tf_agents.agents.dqn import dqn_agent\nfrom tf_agents.utils import common\n\ntf.compat.v1.enable_v2_behavior()\n\n\nfrom dqn_my_env import MyTFEnv\nfrom tf_agents.networks import q_network\n\n\nclass MyAgent(dqn_agent.DqnAgent):\n def __init__(self, learning_rate, fc_layer_units, fc_layer_depth, verbose_env=False, show_summary=False):\n tf.random.set_seed(123123)\n \n self._tf_env = MyTFEnv(verbose_env=verbose_env)\n action_spec = self._tf_env.action_spec()\n num_actions = action_spec.maximum - action_spec.minimum + 1 # As our action spec is defined on N \n observation_spec = self._tf_env.observation_spec()\n time_step_spec = self._tf_env.time_step_spec()\n \n preprocessing_layers = {\n 'price':tf.keras.layers.Flatten(),\n 'pos':tf.keras.layers.Dense(2),\n 'pos_price':tf.keras.layers.Dense(2),\n 'time':tf.keras.layers.Dense(1)\n }\n\n self._q_network = q_network.QNetwork(\n input_tensor_spec=observation_spec,\n action_spec= action_spec,\n preprocessing_layers=preprocessing_layers,\n preprocessing_combiner= tf.keras.layers.Concatenate(axis=-1),\n fc_layer_params = (fc_layer_units,) * fc_layer_depth\n )\n\n \n\n \n super().__init__(\n time_step_spec,\n action_spec,\n q_network=self._q_network,\n optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate),\n td_errors_loss_fn= common.element_wise_squared_loss\n )\n self._q_network.summary()\n self._q_network._encoder.summary()\n if show_summary:\n input()\n \n\n def reset_ep_counter(self):\n self._tf_env.reset_ep_counter()\n","sub_path":"dqn_my_agent.py","file_name":"dqn_my_agent.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"71535977","text":"import common\r\nimport common.menu_utils\r\nimport NERO.agent\r\nimport NERO.client as client\r\nimport NERO.constants as constants\r\nimport NERO_Battle.module as module\r\nimport OpenNero\r\n\r\ndef ModMain(mode = \"\"):\r\n module.getMod() # initialize the NERO_Battle module.\r\n client.ClientMain()\r\n\r\ndef ModTick(dt):\r\n if OpenNero.getAppConfig().rendertype == 'null':\r\n return\r\n script_server = module.getServer()\r\n data = script_server.read_data()\r\n while data:\r\n module.parseInput(data.strip())\r\n data = script_server.read_data()\r\n\r\ndef Match(team0, team1):\r\n '''Run a single battle between two population files.'''\r\n mod = module.getMod()\r\n mod.load_team(team0, constants.OBJECT_TYPE_TEAM_0)\r\n mod.load_team(team1, constants.OBJECT_TYPE_TEAM_1)\r\n mod.set_speedup(100)\r\n OpenNero.enable_ai()\r\n","sub_path":"OpenNERO.app/Contents/Resources/NERO_Battle/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"257531153","text":"import random\nimport datetime as dt\n\nfrom pycalver import version\nfrom pycalver import patterns\n\n\ndef test_bump_beta():\n cur_version = \"v201712.0001-beta\"\n assert cur_version < version.incr(cur_version)\n assert version.incr(cur_version).endswith(\"-beta\")\n assert version.incr(cur_version, release=\"alpha\").endswith(\"-alpha\")\n assert version.incr(cur_version, release=\"final\").endswith(\"0002\")\n\n\ndef test_bump_final():\n cur_version = \"v201712.0001\"\n assert cur_version < version.incr(cur_version)\n assert version.incr(cur_version).endswith(\".0002\")\n assert version.incr(cur_version, release=\"alpha\").endswith(\"-alpha\")\n\n assert version.incr(cur_version, release=\"final\").endswith(\".0002\")\n\n pre_version = cur_version + \"-beta\"\n assert version.incr(pre_version, release=\"final\").endswith(\".0002\")\n\n\ndef test_bump_future():\n \"\"\"Test that versions don't go back in time.\"\"\"\n future_date = dt.datetime.today() + dt.timedelta(days=300)\n future_calver = future_date.strftime(\"v%Y%m\")\n cur_version = future_calver + \".0001\"\n new_version = version.incr(cur_version)\n assert cur_version < new_version\n\n\ndef test_bump_random(monkeypatch):\n cur_date = dt.date(2016, 1, 1) + dt.timedelta(days=random.randint(1, 2000))\n cur_version = cur_date.strftime(\"v%Y%m\") + \".0001-dev\"\n\n monkeypatch.setattr(version, 'TODAY', cur_date)\n\n for i in range(1000):\n cur_date += dt.timedelta(days=int((1 + random.random()) ** 10))\n new_version = version.incr(\n cur_version, release=random.choice([None, \"alpha\", \"beta\", \"rc\", \"final\", \"post\"])\n )\n assert cur_version < new_version\n cur_version = new_version\n\n\ndef test_parse_version_info():\n version_str = \"v201712.0001-alpha\"\n version_nfo = version.parse_version_info(version_str)\n\n # assert version_nfo.pep440_version == \"201712.1a0\"\n # assert version_nfo.version == \"v201712.0001-alpha\"\n assert version_nfo.year == 2017\n assert version_nfo.month == 12\n assert version_nfo.bid == \"0001\"\n assert version_nfo.tag == \"alpha\"\n\n version_str = \"v201712.0001\"\n version_nfo = version.parse_version_info(version_str)\n\n # assert version_nfo.pep440_version == \"201712.1\"\n # assert version_nfo.version == \"v201712.0001\"\n assert version_nfo.year == 2017\n assert version_nfo.month == 12\n assert version_nfo.bid == \"0001\"\n assert version_nfo.tag == \"final\"\n\n\ndef test_readme_pycalver1():\n version_str = \"v201712.0001-alpha\"\n version_info = patterns.PYCALVER_RE.match(version_str).groupdict()\n\n assert version_info == {\n 'pycalver' : \"v201712.0001-alpha\",\n 'vYYYYMM' : \"v201712\",\n 'year' : \"2017\",\n 'month' : \"12\",\n 'build' : \".0001\",\n 'build_no' : \"0001\",\n 'release' : \"-alpha\",\n 'release_tag': \"alpha\",\n }\n\n\ndef test_readme_pycalver2():\n version_str = \"v201712.0033\"\n version_info = patterns.PYCALVER_RE.match(version_str).groupdict()\n\n assert version_info == {\n 'pycalver' : \"v201712.0033\",\n 'vYYYYMM' : \"v201712\",\n 'year' : \"2017\",\n 'month' : \"12\",\n 'build' : \".0033\",\n 'build_no' : \"0033\",\n 'release' : None,\n 'release_tag': None,\n }\n\n\ndef test_parse_error_empty():\n try:\n version.parse_version_info(\"\")\n assert False\n except version.PatternError as err:\n pass\n\n\ndef test_parse_error_noprefix():\n try:\n version.parse_version_info(\"201809.0002\")\n assert False\n except version.PatternError as err:\n pass\n\n\ndef test_parse_error_nopadding():\n try:\n version.parse_version_info(\"v201809.2b0\")\n assert False\n except version.PatternError as err:\n pass\n\n\ndef test_part_field_mapping():\n a_names = set(version.PATTERN_PART_FIELDS.keys())\n b_names = set(patterns.PART_PATTERNS.keys())\n c_names = set(patterns.COMPOSITE_PART_PATTERNS.keys())\n\n extra_names = a_names - b_names\n assert not any(extra_names)\n missing_names = b_names - a_names\n assert missing_names == c_names\n\n a_fields = set(version.PATTERN_PART_FIELDS.values())\n b_fields = set(version.VersionInfo._fields)\n\n assert a_fields == b_fields\n","sub_path":"test/test_version.py","file_name":"test_version.py","file_ext":"py","file_size_in_byte":4295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"23396435","text":"from __future__ import absolute_import\nfrom __future__ import division\n\nfrom utils_common import *\nfrom utils_io import *\nimport re\nimport numpy as np\nimport itertools\n\nlog = LoggerManager.get_logger('main')\n\n# Special symbols\n_PAD = b\"_PAD\"\n_GO = b\"_GO\"\n_EOS = b\"_EOS\"\n_UNK = b\"_UNK\"\nSTART_VOCAB = [_PAD, _GO, _EOS, _UNK]\n\nPAD_ID = 0\nGO_ID = 1\nEOS_ID = 2\nUNK_ID = 3\n\n# Regular expressions used to tokenize.\n_RE_WORD_SPLIT = re.compile(r\"([.,!?\\\"':;)(])\")\n_RE_DIGIT = re.compile(r\"-?\\d*([-.,/]?\\d+)+\")\n_BAD_CHARS = set('.*\\\\-~=+#/$%^&_`:') # must escape dash!!\n# _RE_REMOVE_TRAILING = re.compile(\"([^{0}]*)[{0}]+\".format(_BAD_CHARS))\n# _RE_REMOVE_PRECEDING = re.compile(\"[{0}]+([^{0}]*)\".format(_BAD_CHARS))\n\n\ndef replace_digit(word, substitue=''):\n return re.sub(_RE_DIGIT, substitue, word)\n\n\ndef remove_bad_char(word):\n \"\"\"\n Does not remove a single special symbol. \n Remove the preceding and trailing bad chars.\n \"\"\"\n if word in _BAD_CHARS:\n return word\n # string char position pointers\n start = 0\n end = len(word)\n while start < end and word[start] in _BAD_CHARS:\n start += 1\n if start == end:\n return '' # the whole string is crap\n while word[end - 1] in _BAD_CHARS:\n assert end > start\n end -= 1\n return word[start:end]\n\n\nHYPHEN = '##AT##-##AT##'\n\ndef space_tokenizer(sentence):\n# for segment in sentence.strip().split():\n# words.extend(re.split(_RE_WORD_SPLIT, segment))\n return sentence.strip().split()\n\n\ndef basic_tokenizer(sentence):\n \"\"\"\n Assume that the sentence is properly tokenized, e.g. punctuations have \n already been separated by space.\n Lower-case everything.\n \"\"\"\n words = space_tokenizer(sentence)\n processed_words = []\n # remove trailing periods and preceding dash\n for w in words:\n if not w: continue\n w = w.lower()\n w = remove_bad_char(w)\n w = replace_digit(w, substitue='')\n if w:\n processed_words.append(w)\n return processed_words\n\n\ndef hyphen_tokenizer(sentence):\n \"\"\"\n Follows the convention here: http://nlp.stanford.edu/projects/nmt/\n Applies hyphen substitution on top of `basic_tokenizer`\n E.g. misty-eyed => misty ##AT##-##AT## eyed\n Lower-case everything.\n \"\"\"\n words = space_tokenizer(sentence)\n processed_words = []\n # remove trailing periods and preceding dash\n for w in words:\n if not w: continue\n if w != HYPHEN:\n w = w.lower()\n w = remove_bad_char(w)\n w = replace_digit(w, substitue='')\n if '-' in w and w != HYPHEN:\n # merry-go-round => merry HYPHEN go HYPHEN round\n w = w.split('-')\n w = itertools.chain.from_iterable(zip(w, [HYPHEN]*len(w)))\n w = list(w)[:-1]\n processed_words.extend(w)\n elif w: # any other non-empty string\n processed_words.append(w)\n return processed_words\n\n\ndef create_vocab(vocab_path, data_path, max_vocab_size,\n regenerate=False, \n tokenizer=None, \n alphabetical=True):\n \"\"\"Create vocabulary file (if it does not exist yet) from data file.\n\n Data file is assumed to contain one sentence per line. Each sentence is\n tokenized and digits are normalized.\n Vocabulary contains the most-frequent tokens up to max_vocab_size.\n We write it to vocab_path in a one-token-per-line format, so that later\n token in the first line gets id=0, second line gets id=1, and so on.\n\n Args:\n vocab_path: path where the vocabulary will be created.\n data_path: data file that will be used to create vocabulary.\n max_vocab_size: limit on the size of the created vocabulary.\n regenerate: regenerate vocab file even if it exists\n tokenizer: a function to use to tokenize each data sentence;\n if None, basic_tokenizer will be used.\n alphebetical: arrange the vocab in alphabetical order, otherwise \n arrange by descending token frequency\n \"\"\"\n if f_exists(vocab_path):\n log.info('Vocabulary {} already created.', vocab_path)\n if regenerate:\n log.warning('regenerate=True: force regeneration of vocabulary.')\n else:\n return\n\n log.info(\"Creating vocabulary {} from data {}\", vocab_path, data_path)\n vocab = {}\n with open(data_path, mode='r') as f:\n counter = 0\n for line in f:\n counter += 1\n if is_div(counter, 100000):\n log.info2(\" processing line {}\", counter)\n words = tokenizer(line) if tokenizer else hyphen_tokenizer(line)\n for word in words:\n if word in vocab:\n vocab[word] += 1\n else:\n vocab[word] = 1\n vocab_list = sorted(vocab, key=vocab.get, reverse=True)\n # max_vocab_size includes START_VOCAB\n vocab_list = vocab_list[:max_vocab_size-len(START_VOCAB)]\n if alphabetical:\n vocab_list = sorted(vocab_list)\n vocab_list = START_VOCAB + vocab_list\n assert len(vocab_list) <= max_vocab_size\n with open(vocab_path, mode='w') as vocab_file:\n for w in vocab_list:\n vocab_file.write(w + b\"\\n\")\n\n\ndef load_vocab(vocab_path):\n \"\"\"Load vocabulary dict from file.\n\n We assume the vocabulary is stored one-item-per-line, so a file:\n dog\n cat\n will result in a vocabulary {\"dog\": 0, \"cat\": 1}, and this function will\n also return the reversed-vocabulary [\"dog\", \"cat\"].\n\n Args:\n vocab_path: path to the file containing the vocabulary.\n\n Returns:\n a pair: the vocabulary (a dictionary mapping string to integers), and\n the reversed vocabulary (a list, which reverses the vocabulary mapping).\n\n Raises:\n ValueError: if the provided vocab_path does not exist.\n \"\"\"\n if f_exists(vocab_path):\n rev_vocab = []\n with open(vocab_path, mode='r') as f:\n rev_vocab.extend(f.readlines())\n rev_vocab = [line.strip() for line in rev_vocab]\n vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])\n return vocab, rev_vocab\n else:\n raise ValueError(\"Vocabulary file {} not found.\".format(vocab_path))\n\n\ndef sentence_to_token_ids(sentence, vocab, tokenizer=None):\n \"\"\"Convert a string to list of integers representing token-ids.\n\n Args:\n sentence: the sentence in bytes format to convert to token-ids.\n vocab: a dictionary mapping tokens to integers.\n tokenizer: a function to use to tokenize each sentence;\n if None, basic_tokenizer will be used.\n\n Returns:\n a list of integers, the token-ids for the sentence.\n \"\"\"\n words = tokenizer(sentence) if tokenizer else hyphen_tokenizer(sentence)\n return [vocab.get(w, UNK_ID) for w in words]\n\n\ndef data_to_token_ids(data_path, target_path, vocab,\n regenerate=False, \n tokenizer=None, \n normalize_digits=False):\n \"\"\"Tokenize data file and turn into token-ids using given vocabulary file.\n\n This function loads data line-by-line from data_path, calls the above\n sentence_to_token_ids, and saves the result to target_path. See comment\n for sentence_to_token_ids on the details of token-ids format.\n\n Args:\n data_path: path to the data file in one-sentence-per-line format.\n target_path: path where the file with token-ids will be created.\n vocab: vocab dictionary from load_vocab().\n regenerate: regenerate token ID file even if it exists\n tokenizer: a function to use to tokenize each sentence;\n if None, basic_tokenizer will be used.\n normalize_digits: Boolean; if true, all digits are replaced by 0s.\n \"\"\"\n if f_exists(target_path):\n log.info('Token ID corpus {} already created.', target_path)\n if regenerate:\n log.warning('regenerate=True: force regeneration of token ID corpus.')\n else:\n return\n\n log.info(\"Tokenizing data in {}\", data_path)\n with open(data_path, mode='r') as data_file:\n with open(target_path, mode=\"w\") as tokens_file:\n counter = 0\n for line in data_file:\n counter += 1\n if is_div(counter, 100000):\n log.info(\" tokenizing line {}\", counter)\n token_ids = sentence_to_token_ids(line, vocab, tokenizer)\n tokens_file.write(\" \".join([str(tok) for tok in token_ids]) + \"\\n\")\n\n\ndef token_ids_to_sentence(tokens, rev_vocab, stop_at_eos=True):\n \"\"\"Convert a string to list of integers representing token-ids.\n\n Args:\n tokens: list of int tokens\n rev_vocab: a dictionary (list) mapping integers to tokens.\n stop_at_eos: discard anything after EOS.\n\n Returns:\n sentence\n \"\"\"\n if not isinstance(tokens, list):\n tokens = list(tokens)\n if stop_at_eos and EOS_ID in tokens: \n tokens = tokens[:tokens.index(EOS_ID)]\n return ' '.join([rev_vocab[tok] for tok in tokens])\n\n\n@deprecated('Use LineAccessFile for much better memory management.')\ndef get_raw_data(data_path, max_data_lines=None, \n length_cutoff=30, length_discard=50):\n \"\"\"\n Args:\n max_data_lines: max number of lines to process in training data\n length_cutoff: cut off the line beyond this length (shorten), \n this value is typically num_word_step\n length_discard: discard any lines with more than this many tokens (skip)\n \n Returns:\n List of list of word ids, each sub-list represents a sentence\n \"\"\"\n assert length_cutoff < length_discard\n raw_data = []\n counter = 0\n for l in open(data_path, 'r'):\n if (not max_data_lines or counter < max_data_lines):\n counter += 1\n if is_div(counter, 100000):\n log.info2(\" fetching raw data line {}\", counter)\n sys.stdout.flush()\n ids = map(int, l.strip().split())\n if len(ids) <= length_discard:\n raw_data.append(ids[:length_cutoff])\n return raw_data\n \n\ndef shard_corpus_file(file_path, \n split_portions,\n block_size, \n shuffle=True,\n aux_regenerate=False):\n \"\"\"\n Split a giant corpus randomly into training and validation.\n The sharded file will save to the same folder with `.0`, `.1` ... mode.\n \n Args:\n file_path\n block_size: split by `block_size` number of lines.\n split_portions: if N shards, specify N-1 portions. \n The last shard will be 1 - sum(portions).\n shuffle: if True, randomly shuffle the blocks before sharding.\n regenerate_aux: regenerate auxiliary line file used by LineAccessFile\n \"\"\"\n #assert sum(split_portions) < 1.0, 'split portion should be N-1 and sum < 1.0'\n file_path = f_expand(file_path)\n laf = LineAccessFile(file_path,\n block_size=block_size,\n aux_regenerate=aux_regenerate)\n total_blocks = len(laf)\n shards = []\n for s in split_portions:\n shard = int(s * total_blocks)\n assert shard > 0, 'invalid shard length: {}'.format(shard)\n shards.append(shard)\n shards.append(total_blocks - sum(shards))\n shards=split_portions\n log.info('total blocks = {}, shards = {}', total_blocks, shards)\n \n indices = shuffled_indices(total_blocks)\n \n for n, shard in enumerate(shards):\n fname = '{}.{}'.format(file_path, n)\n log.info('writing to ' + fname)\n with TextFile(fname, 'w') as f:\n for index in indices[:shard]:\n f.write_n(laf[index]) # multiple lines in the block\n del indices[:shard]\n #assert len(indices) == 0\n\n\ndef shard_parallel_file_pairs(file_paths, \n split_portions, \n block_size,\n shuffle=True, \n aux_regenerate=False):\n \"\"\"\n Split a pair of parallel corpora randomly into training and validation.\n The sharded file will save to the same folder with `.0`, `.1` ... mode.\n \n Args:\n file_paths: list of 2 file paths for the parallel corpora. \n split_portions: if N shards, specify N-1 portions. \n The last shard will be 1 - sum(portions).\n shuffle: if True, randomly shuffle the blocks before sharding.\n regenerate_aux: regenerate auxiliary line file used by LineAccessFile\n \"\"\"\n assert sum(split_portions) < 1.0, 'split portion should be N-1 and sum < 1.0'\n assert is_list_len(file_paths, 2), '[en_file_path, fo_file_path]'\n lafs = []\n apply_map(f_expand, file_paths)\n for file_path in file_paths:\n lafs.append(LineAccessFile(file_path, \n block_size=block_size, \n aux_mode=LoadMode.InMem,\n aux_regenerate=aux_regenerate))\n assert len(lafs[0]) == len(lafs[1]), \\\n 'Parallel corpora should have the same number of sentences.'\n total_blocks = len(lafs[0]) # each block is just once sentence\n shards = []\n for s in split_portions:\n shard = int(s * total_blocks)\n assert shard > 0, 'invalid shard length: {}'.format(shard)\n shards.append(shard)\n shards.append(total_blocks - sum(shards))\n# shards = [224204, 1000]\n log.info('total blocks = {}, shards = {}', total_blocks, shards)\n shards = cum_sum(shards)\n\n # parallel corpus must preserve the shard order\n indices = shuffled_indices(total_blocks)\n for file_path, laf in zip(file_paths, lafs):\n for i in range(len(shards)-1):\n fname = '{}.{}'.format(file_path, i)\n log.info('writing to ' + fname)\n with TextFile(fname, 'w') as f:\n for index in indices[shards[i]:shards[i+1]]:\n f.write_n(laf[index]) # multiple lines in the block\n\n\n# ========================================================\n# ================== corpus file locations ====================\nclass FileSpec(object):\n def __init__(self, spec_file):\n \"\"\"\n E.g. specify only the prefix\n {\n \"mono_en\": \"book-en\", # auto append: book-en_train/valid.txt\n \"mono_fo\": \"book-jp\",\n ...\n }\n or specify the full file names:\n {\n \"mono_en\": [\"book-en_mytrain.txt\", \"myvalid.txt\"],\n \"mono_fo\": [\"myjptrain.txt\", \"jpvalid.txt\"],\n ...\n }\n \n Required keys: mono_en, mono_fo, para_en, para_fo\n \"\"\"\n spec_file = f_expand(f_add_ext(spec_file, 'json'))\n assert f_exists(spec_file), spec_file + ' does not exist'\n self.spec = JsonWriter(spec_file)\n \n \n def _get_full_names(self, spec):\n # generate training and validation file names\n if is_sequence(spec):\n # user specifies both training and validation's full names\n assert len(spec) == 2, 'must be a list [.txt, .txt]'\n assert spec[0].endswith('.txt'), 'training file must end with .txt'\n assert spec[1].endswith('.txt'), 'validation file must end with .txt'\n return map(str, spec)\n else:\n assert isinstance(spec, basestring), \\\n 'data prefix must be string: {}'.format(spec)\n assert not spec.endswith('.txt'), \\\n '{} should be a prefix instead of a full filename.'.format(spec)\n if not spec:\n # file not specified\n return [None, None]\n else:\n return ['{}_train.txt'.format(spec),\n '{}_valid.txt'.format(spec)]\n\n @property\n def mono(self):\n \"\"\"\n Monolingual corpus file names.\n access by int index: [train/valid_mode][lang]\n \"\"\"\n assert 'mono_en' in self.spec\n assert 'mono_fo' in self.spec\n # transpose so that first dim is training mode and second is lang\n return zip(*[self._get_full_names(self.spec.mono_en), \n self._get_full_names(self.spec.mono_fo)])\n \n @property\n def para(self):\n \"\"\"\n Parallel corpus file names\n access by int index: [train/valid_mode][lang]\n \"\"\"\n assert 'para_en' in self.spec\n assert 'para_fo' in self.spec\n return zip(*[self._get_full_names(self.spec.para_en), \n self._get_full_names(self.spec.para_fo)])\n \n @property\n def vocab(self):\n \"\"\"\n Vocabulary prefixes for en and fo. \n \"\"\"\n assert 'vocab_en' in self.spec\n assert 'vocab_fo' in self.spec\n return [self.spec.vocab_en, self.spec.vocab_fo]\n\n\n# ========================================================\n# ========================================================\n# ==================== Corpus readers ====================\n# ========================================================\n\"Helper for Corpus iterator\"\nBlockInfo = collections.namedtuple('BlockInfo', \n ['batch_per_block',\n 'block_size',\n 'is_first_batch'])\n\n\n@PrefixProperty(['block_per_epoch'],\n prefix='_')\nclass AbstractCorpus(object):\n def __init__(self, folder, \n corpus_file, \n vocab_prefix,\n batch_size,\n block_size):\n \"\"\"\n Args:\n folder: can contain symbols like `~` for home dir, will be expanded\n corpus_file: text file, each line is a sentence.\n vocab_prefix: \n vocab file: vocab.{size}.txt\n ID file : .{size}.txt\n batch_size\n block_size: number of sentences per block. Ideally it should be a \n multiple of (batch_size * num_sentence_step)\n \"\"\"\n self.folder = folder\n self.corpus_path = self.get_path(corpus_file)\n self.vocab_prefix = vocab_prefix\n self.batch_size = batch_size\n self.block_size = block_size\n # processed (integerized) ID file\n self.ids_path = None\n self.reader = None\n\n \n def prepare(self, vocab_size, \n regenerate=False, \n tokenizer=None,\n load_mode=LoadMode.OnDisk,\n **reader_kwargs):\n \"\"\"\n Saves vocab dictionary to vocab{size}.txt\n Replace each word by their int ID and generates '.ids{size}.txt'\n\n Args:\n vocab_size: take the most frequent N words and treat all others as UNK\n regenerate\n - True: force regenerate vocab and IDs even if they already exist. \n - False: generate only when those files do not exist.\n tokenizer: function(string sentence) -> [list of string tokens]\n load_mode: LoadMode.OnDisk or .InMem\n *reader_kwargs: additional args to self.reader's constructor, \n i.e. OnDisk -> LineAccessFile or InMem -> InMemoryFile\n\n Returns:\n (vocab_path, ids_path)\n \"\"\"\n vocab_size = int(vocab_size)\n self.vocab_path = self.get_path(\"vocab.{}{}.txt\"\n .format(self.vocab_prefix, vocab_size))\n\n create_vocab(self.vocab_path, \n self.corpus_path, \n vocab_size, \n regenerate=regenerate,\n tokenizer=tokenizer)\n\n self.vocab, self.rev_vocab = load_vocab(self.vocab_path)\n assert len(self.vocab) == len(self.rev_vocab)\n\n # append this mode before file extension (.txt)\n mode = '.{}{}'.format(self.vocab_prefix, vocab_size)\n # Create token ids and save to e.g. corpus_train.en2000.txt\n self.ids_path = f_append_before_ext(self.corpus_path, mode)\n data_to_token_ids(self.corpus_path, \n self.ids_path,\n self.vocab, \n regenerate=regenerate,\n tokenizer=tokenizer)\n \n self.vocab_size = len(self.vocab)\n if self.vocab_size != vocab_size:\n log.warning('Actual len(corpus.vocab_size) {} != specified {}'\n .format(self.vocab_size, vocab_size))\n\n if load_mode == LoadMode.OnDisk:\n self.reader = LineAccessFile(self.ids_path,\n block_size=self.block_size,\n # aux_mode=LoadMode.InMem,\n **reader_kwargs)\n else:\n self.reader = InMemoryFile(self.ids_path,\n data_fmt=InMemoryFile.TEXT,\n block_size=self.block_size,\n **reader_kwargs)\n self._block_per_epoch = len(self.reader)\n\n\n @property\n def batch_per_epoch(self):\n raise NotImplementedError\n \n \n def __iter__(self):\n raise NotImplementedError('yield ({feed_dict}, BlockInfo)')\n\n\n def token_ids_to_sentence(self, tokens):\n \"\"\"\n Args:\n tokens: list of ints that represents a sentence\n \"\"\"\n return token_ids_to_sentence(tokens, self.rev_vocab)\n \n \n def get_path(self, fname):\n \"\"\"\n Return fully expanded path of fname\n Args:\n fname: if None, return None\n \"\"\"\n if fname is None:\n return None\n else:\n return f_join_expand(self.folder, fname)\n\n\n@circular_iterable\nclass NoneCorpus(AbstractCorpus):\n \" Placeholder, no-op corpus \"\n def __init__(self, *args, **kwargs):\n pass\n \n @overrides\n def prepare(self, *args, **kwargs):\n pass\n \n @overrides\n def __iter__(self):\n yield {}, BlockInfo(-1, -1, False)\n\n\nclass SentenceCorpus(AbstractCorpus):\n \"\"\"\n Prepare encoder_input and decoder_input of the sentence\n \"\"\"\n def __init__(self, folder, \n corpus_file, \n vocab_prefix,\n batch_size,\n block_size,\n num_word_step):\n AbstractCorpus.__init__(self, folder,\n corpus_file,\n vocab_prefix,\n batch_size,\n block_size)\n self.NW = num_word_step\n \n \n WRAP_PLACEHOLDER = -1 # for decoder_input generation\n\n def _wrap_around(self, data):\n \"\"\"\n data: a 2D numpy object array, every object is a list of sentence tokens.\n line i+1 is the continuation of line i. E.g:\n array([[0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [9, 10, 11],\n [12, 13, 14]], dtype=object)\n Returns: line wrapped around\n array([[0, 1, 2, 3],\n [3, 4, 5, 6],\n [6, 7, 8, 9],\n [9, 10, 11, 12],\n [12, 13, 14, WRAP_PLACEHOLDER]], dtype=object)\n \"\"\"\n _placeholder = np.empty((1,1), dtype=np.object)\n _placeholder[0][0] = self.WRAP_PLACEHOLDER\n wrap_column = data[1:, :1] # shape = (data.row-1) x 1\n wrap_column = np.concatenate((wrap_column, _placeholder), axis=0)\n return np.concatenate((data, wrap_column), axis=1)\n\n\n def _stack(self, arrays, dtype):\n \"\"\"\n stack along the sequence dim [batch_size x unroll_words x unroll_sentence]\n helper function for get_batch_tensor()\n \"\"\"\n return np.stack((np.array(A, dtype=dtype) for A in arrays), axis=-1)\n \n \n def batch_encoder_pad(self, sentences):\n \"batch of sentences, each sentence is irregular list of int IDs\"\n enc_padded = []\n for sentence in sentences:\n sentence = sentence + [EOS_ID]\n if len(sentence) > self.NW:\n sentence = sentence[:self.NW]\n # left pad and reverse 'sentence',\n padding = [PAD_ID] * (self.NW - len(sentence))\n enc_padded.append(list(reversed(sentence + padding)))\n return enc_padded\n\n\n def batch_decoder_pad(self, sentences):\n \"\"\"\n Batch of sentences, each sentence is irregular list of int IDs\n Returns: (decoder_input, weights)\n \"\"\"\n dec_padded = []\n target_weights = [] # [batch_size X num_word_step] for a single sentence\n for sentence in sentences:\n if sentence == self.WRAP_PLACEHOLDER:\n # last sentence of the last batch_len does not have a successor\n # set to all zeros as a placeholder.\n dec_padded.append([PAD_ID] * self.NW)\n target_weights.append([0] * self.NW)\n else:\n # if the sentence is more than the max length, truncate it\n # but don't append EOS.\n sentence = [GO_ID] + sentence + [EOS_ID]\n sentence = sentence[:self.NW]\n padding = [PAD_ID] * (self.NW - len(sentence))\n dec_padded.append(sentence + padding)\n # 0 for PAD only and 1 for everything else\n # corresponding target is decoder_inputs shifted forward by 1\n target_weights.append([1] * (len(sentence) - 1) \n + [0] * (len(padding) + 1))\n return dec_padded, target_weights\n\n\n def to_feed_dict(self, batch_tensors,\n names=['encoder_inputs', \n 'decoder_inputs', \n 'target_weights']):\n \"Process output from get_batch_tensor to named dict\"\n assert len(batch_tensors) == len(names)\n return AttributeDict(zip(names, batch_tensors))\n\n\nclass MonoStreamCorpus(SentenceCorpus):\n \"\"\"\n Monolingual corpus with stream of sentences to reconstruct themselves.\n E.g. BookCorpus of continuous English sentences in paragraphs\n \"\"\"\n def __init__(self, folder, \n corpus_file, \n vocab_prefix,\n batch_size,\n block_size,\n num_word_step,\n num_sentence_step,\n is_self_encode=False):\n \"\"\"\n Args:\n folder: can contain symbols like `~` for home dir, will be expanded\n corpus_file: text file, each line is a sentence.\n vocab_prefix: \n vocab file: vocab.{size}.txt\n ID file : .{size}.txt\n num_word_step: number of steps to unroll in the word-level RNN\n also the max number of words allowed in the encoder/decoder inputs\n num_sentence_step: number of steps to unroll in the sentence-level RNN\n batch_size\n is_self_encode: \n - True: decoder_input and encoder_input are based on the same \n sentence (self-encoding)\n - False: decoder_input is one sentence step ahead of encoder_input \n (predict the next sentence)\n block_size: number of sentences per block. Ideally it should be a \n multiple of (batch_size * num_sentence_step)\n \"\"\"\n SentenceCorpus.__init__(self, folder, \n corpus_file, \n vocab_prefix, \n batch_size, \n block_size,\n num_word_step)\n self.NS = num_sentence_step\n self.is_self_encode = is_self_encode\n if self.is_self_encode:\n log.warning('{}.is_self_encode=True: '\n 'decoder and encoder inputs are the same sentence.'\n .format(self.__class__))\n elif self.is_self_encode is not None:\n log.warning('{}.is_self_encode=False: '\n 'decoder input is one step further than encoder.'\n .format(self.__class__))\n \n @property\n @overrides\n def batch_per_epoch(self):\n \"\"\"\n Returns: total number of batches per epoch.\n Warning: will require reading the last block, might be a bit slow.\n \"\"\"\n bpb = (self.block_size // self.batch_size) // self.NS\n # last block might be smaller than self.block_size\n bpb_last = (len(self.reader[-1]) // self.batch_size) // self.NS\n return bpb * (self.block_per_epoch - 1) + bpb_last\n\n \n def load_deploy(self, text_sentences, batch_size, tokenizer=None):\n \"\"\"\n Args:\n text_sentences: list of raw strings of sentences to be tokenized\n it will be replicated `batch_size` times along the first dimension \n to satisfy the model input dim requirement.\n \n Returns: \n encoder_inputs [batch_size x num_word_step x num_sentence_step]\n NOTE: input reversed. \n \"\"\"\n encoder_inputs = np.zeros([self.NW, self.NS])\n id_sentences = [sentence_to_token_ids(s, self.vocab)\n for s in text_sentences]\n \n for i, sentence in enumerate(id_sentences):\n padding = [PAD_ID] * (self.NW - len(sentence))\n encoder_inputs[:, i] = list(reversed(sentence + padding))\n\n # every batch is the same\n return np.tile(encoder_inputs, (batch_size, 1, 1))\n\n\n def __iter__(self):\n \"\"\"\n Use the corpus object directly as an iterator.\n \n Yields: \n 2-tuple, tensor dim [batch_size x num_word_step x num_sentence_step]\n First is a dictionary, second is a BlockInfo.\n ({encoder_inputs: [_PAD _EOS reversed()], because reversed \n input can be better for learning (Cho,'14)\n decoder_inputs: [_GO _EOS _PAD]\n target_weights: same dim. one time step shifted forward from decoder_inputs},\n block_info)\n \n BlockInfo is a named tuple with:\n - batch_per_block: number of batches in this block. \n The last block might have fewer than self.batch_per_block.\n - block_size: number of sentences in this block.\n The last block might be smaller than self.block_size.\n - is_first_batch: needs to reset carried-over LSTM states.\n \"\"\"\n assert self.reader is not None, 'must call prepare() first'\n # shuffle blocks\n block_indices = shuffled_indices(self.block_per_epoch)\n for idx in block_indices:\n raw_data = self.reader[idx]\n # convert string line to list of ints\n raw_data = map(lambda s: map(int, s.strip().split()), raw_data)\n \n # length along the second dimension\n block_size = len(raw_data)\n batch_len = block_size // self.batch_size \n\n data = np.empty([self.batch_size, batch_len], dtype=object)\n # each line is of batch_len, row dim = batch_size\n for i in range(self.batch_size):\n data[i] = raw_data[batch_len * i : batch_len * (i + 1)]\n\n # number of batches per epoch\n batch_per_block = batch_len // self.NS\n \n if batch_per_block == 0:\n continue\n \n if is_div(batch_len, self.NS) and not self.is_self_encode:\n # When batch_len is a multiple of NS, the last NS in batch_len \n # will not have the next element. \n # wraps the data around with the lower right corner = PLACEHOLDER\n data = self._wrap_around(data)\n assert data.shape, (self.batch_size, batch_len + 1)\n \n for i in range(batch_per_block):\n block_info = BlockInfo(batch_per_block=batch_per_block,\n block_size=block_size,\n is_first_batch= (i == 0))\n batch_tensors = self.get_batch_tensor(data, i)\n yield self.to_feed_dict(batch_tensors), block_info\n \n \n def get_batch_tensor(self, data, i):\n # ragged arrays of batched enc and dec\n assert data.shape[0] == self.batch_size\n \n enc_ragged = data[:, i*self.NS: (i+1)*self.NS]\n if self.is_self_encode:\n dec_ragged = enc_ragged\n else:\n # decoder_input one sentence step ahead of encoder_input\n # last pos might go one sentence beyond if batch_len divides self.NS\n dec_ragged = data[:, i*self.NS + 1:(i+1)*self.NS + 1]\n \n enc_inputs = [enc_ragged[:,step] for step in range(self.NS)]\n apply_map(self.batch_encoder_pad, enc_inputs)\n \n dec_inputs = [dec_ragged[:,step] for step in range(self.NS)]\n dec_weight_pairs = map(self.batch_decoder_pad, dec_inputs)\n dec_inputs, target_weights = zip(*dec_weight_pairs)\n \n return (self._stack(enc_inputs, np.int32),\n self._stack(dec_inputs, np.int32),\n self._stack(target_weights, np.float32))\n \n \n# ========================================================\n# =================== For sentence vec ========================\n# ========================================================\nclass MonoCorpus(SentenceCorpus):\n def __init__(self, folder, \n corpus_file, \n vocab_prefix,\n batch_size,\n block_size,\n num_word_step,\n window=1,\n skip=1):\n \"\"\"\n Args (extra):\n window: default = 1, each word -> 2 x window context\n skip: default = 1, interval between the next center word\n \"\"\"\n SentenceCorpus.__init__(self, folder, \n corpus_file, \n vocab_prefix, \n batch_size, \n block_size,\n num_word_step)\n self.window = window\n self.skip = skip\n \n \n def batch_per_block(self, block_size):\n return ((block_size - 2 * self.window) // self.skip // self.batch_size)\n \n @property\n @overrides\n def batch_per_epoch(self):\n \"\"\"\n Returns: total number of batches per epoch.\n Warning: will require reading the last block, might be a bit slow.\n \"\"\"\n bpb = self.batch_per_block(self.block_size)\n # last block might be smaller than self.block_size\n bpb_last = self.batch_per_block(len(self.reader[-1]))\n return bpb * (self.block_per_epoch - 1) + bpb_last\n\n \n def __iter__(self):\n \"\"\"\n Use the corpus object directly as an iterator.\n \n Yields: \n 2-tuple\n ({encoder_inputs: [batch_size x num_word_step]\n decoder_inputs: [batch_size x num_word_step x (2 x window)]\n target_weights: [same as decoder_inputs]\n }, BlockInfo)\n ({encoder_inputs: [_PAD _EOS reversed()], because reversed \n input can be better for learning (Cho,'14)\n decoder_inputs: [_GO _EOS _PAD]\n target_weights: same dim. one time step shifted forward from decoder_inputs},\n block_info)\n \n BlockInfo is a named tuple with:\n - batch_per_block: number of batches in this block. \n The last block might have fewer than self.batch_per_block.\n - block_size: number of sentences in this block.\n The last block might be smaller than self.block_size.\n - is_first_batch\n \"\"\"\n assert self.reader is not None, 'must call prepare() first'\n\n offset_range = range(-self.window, self.window+1)\n # also include the original sentence in the middle\n# offset_range.remove(0) # e.g. [-3, -2, -1, 1, 2, 3]\n # shuffle blocks\n block_indices = shuffled_indices(self.block_per_epoch)\n for idx in block_indices:\n raw_data = self.reader[idx]\n # convert string line to list of ints\n raw_data = map(lambda s: map(int, s.strip().split()), raw_data)\n this_block_size = len(raw_data)\n batch_per_block = self.batch_per_block(this_block_size)\n\n if batch_per_block == 0:\n continue\n \n ptr = self.window # data pointer starts at the first center word\n for i in range(batch_per_block):\n decoder_inputs = {offset:[] for offset in offset_range}\n encoder_inputs = []\n for _ in range(self.batch_size):\n encoder_inputs.append(raw_data[ptr])\n # surrounding words\n for offset in offset_range:\n assert 0 <= ptr+offset < this_block_size\n decoder_inputs[offset].append(raw_data[ptr+offset])\n ptr += self.skip\n \n encoder_inputs = self.batch_encoder_pad(encoder_inputs)\n dec_weight_pairs = [self.batch_decoder_pad(decoder_inputs[offset])\n for offset in offset_range]\n dec_inputs, target_weights = zip(*dec_weight_pairs)\n block_info = BlockInfo(batch_per_block=batch_per_block,\n block_size=this_block_size,\n is_first_batch=(i == 0))\n feed_dict = self.to_feed_dict((np.array(encoder_inputs, np.int32),\n self._stack(dec_inputs, np.int32),\n self._stack(target_weights, np.float32)))\n yield feed_dict, block_info\n \n \n# ========================================================\n# ================== Parallel corpus =====================\n# ========================================================\nclass ParallelCorpus(SentenceCorpus):\n def __init__(self, folder, \n corpus_files, \n vocab_prefixes,\n batch_size,\n block_size,\n num_word_step):\n \"\"\"\n Each line of the corpus has two tokens separated by space. \n The first symbols is English and the second is foreign (fo). \n \n Args:\n mono_corpora: a two-tuple of MonoStreamCorpus, En and Fo. The corpora must\n have `vocab` field that maps string to int ID. \n \"\"\"\n assert is_list_len(corpus_files, 2), \\\n 'corpus files must have two items [en_corpus, fo_corpus]'\n assert is_list_len(vocab_prefixes, 2), \\\n 'prefixes must have two items [en_corpus, fo_corpus]'\n \n SentenceCorpus.__init__(self, folder, \n corpus_file='', \n vocab_prefix='', \n batch_size=batch_size, \n block_size=block_size,\n num_word_step=num_word_step)\n self.sub_corpora = []\n for l in [0, 1]:\n self.sub_corpora.append(\n SentenceCorpus(folder,\n corpus_files[l],\n vocab_prefixes[l],\n batch_size,\n block_size,\n num_word_step))\n \n\n @overrides\n def prepare(self, *args, **kwargs):\n for corpus in self.sub_corpora:\n corpus.prepare(*args, **kwargs)\n self.readers = [self.sub_corpora[i].reader for i in [0, 1]]\n self.vocab_size = max(self.sub_corpora[0].vocab_size,\n self.sub_corpora[1].vocab_size)\n # len(reader) == block_per_epoch\n assert len(self.readers[0]) == len(self.readers[1]), \\\n 'Parallel corpora must have the same number of sentences.' \n self._block_per_epoch = len(self.readers[0])\n \n @property\n @overrides\n def batch_per_epoch(self):\n \"\"\"\n Returns: total number of batches per epoch.\n Warning: will require reading the last block, might be a bit slow.\n \"\"\"\n bpb = self.block_size // self.batch_size\n # last block might be smaller than self.block_size\n bpb_last = len(self.readers[0][-1]) // self.batch_size\n return bpb * (self.block_per_epoch - 1) + bpb_last\n \n\n def __iter__(self):\n \"\"\"\n Yields:\n {'encoder_inputs_p': (en-[batch x num_word], fo-[batch x num_word])\n 'decoder_inputs_p': (fo-[batch x num_word], en-[batch x num_word]),\n 'target_weights_p': (same shape floats)}\n lang indices [0,1] should match for encoder/decoder inputs\n \n BlockInfo = null\n \"\"\"\n assert all(self.readers), 'must call prepare() first'\n # shuffle blocks\n block_indices = shuffled_indices(self.block_per_epoch)\n for idx in block_indices:\n raw_data = [self.readers[l][idx] for l in [0, 1]]\n assert len(raw_data[0]) == len(raw_data[1])\n # convert string line to list of ints\n raw_data = [map(lambda s: map(int, s.strip().split()), raw_data[l])\n for l in [0, 1]]\n # shuffle en and fo and retain the pair ordering\n raw_data = zip(*raw_data)\n random.shuffle(raw_data)\n \n block_size = len(raw_data)\n batch_per_block = block_size // self.batch_size\n for i in range(batch_per_block):\n # [en, fr]\n raw_enfr = zip(*raw_data[self.batch_size*i:self.batch_size*(i+1)])\n enc = [None, None]\n dec = [None, None]\n weights = [None, None]\n for l in [0, 1]:\n enc_ = self.batch_encoder_pad(raw_enfr[l])\n enc[l] = np.array(enc_, np.int32)\n dec_, weights_ = self.batch_decoder_pad(raw_enfr[1-l])\n dec[l] = np.array(dec_, np.int32)\n weights[l] = np.array(weights_, np.float32)\n\n block_info = BlockInfo(batch_per_block=batch_per_block,\n block_size=block_size,\n is_first_batch=(i == 0))\n feed_dict = AttributeDict(encoder_inputs_p=enc,\n decoder_inputs_p=dec,\n target_weights_p=weights)\n yield feed_dict, block_info\n\n\nclass SemiCorpus(AbstractCorpus):\n def __init__(self, mono_corpora, para_corpus):\n \"\"\"\n Args:\n mono_corpora: list of 2\n para: corpus\n \"\"\"\n assert is_list_len(mono_corpora, 2)\n assert all(isinstance(corpus, AbstractCorpus) for corpus in mono_corpora)\n assert isinstance(para_corpus, AbstractCorpus)\n self.mono_corpora = mono_corpora\n self.para_corpus = para_corpus\n transfer_attrs(self.para_corpus, self, \n include_filter=['folder',\n 'batch_size'])\n \n \n @overrides\n def prepare(self, *args, **kwargs):\n for mono_corpus in self.mono_corpora:\n mono_corpus.prepare(*args, **kwargs)\n self.para_corpus.prepare(*args, **kwargs)\n self.vocab_size = max(self.mono_corpora[0].vocab_size,\n self.mono_corpora[1].vocab_size)\n self.rev_vocab = [self.mono_corpora[lang].rev_vocab for lang in [0,1]]\n \n \n @property\n @overrides\n def batch_per_epoch(self):\n return self.para_corpus.batch_per_epoch\n \n \n @overrides\n def __iter__(self):\n for mono0, mono1, para in itertools.izip(self.mono_corpora[0],\n self.mono_corpora[1],\n self.para_corpus):\n # mono0 is a 2-tuple (FeedDict, BlockInfo)\n mono = [mono0[0], mono1[0]]\n feeds = {}\n # combine two mono copora feed dict\n for key in mono[0]:\n assert key in mono[1], 'should have the same feed dict keys'\n feeds[key] = [mono[l][key] for l in [0, 1]]\n feeds = merge_dicts(feeds, para[0])\n yield AttributeDict(feeds), para[1]\n\n\n# ========================================================\n# ================== Word corpus =====================\n# ========================================================\nclass MonoWordCorpus(AbstractCorpus):\n def __init__(self, folder, \n corpus_file, \n vocab_prefix,\n batch_size,\n block_size,\n window=1,\n skip=1):\n \"\"\"\n Args (extra):\n window: default = 1, each word -> 2 x window context\n skip: default = 1, interval between the next center word\n \"\"\"\n AbstractCorpus.__init__(self, folder, \n corpus_file, \n vocab_prefix, \n batch_size, \n block_size)\n self.window = window\n self.skip = skip\n\n \n @property\n @overrides\n def batch_per_epoch(self):\n \"\"\"\n The number of words are unknown\n \"\"\"\n return 0\n# bpb = self.block_size // self.batch_size\n# # last block might be smaller than self.block_size\n# bpb_last = len(self.reader[-1]) // self.batch_size\n# return bpb * (self.block_per_epoch - 1) + bpb_last\n\n \n def __iter__(self):\n \"\"\"\n Use the corpus object directly as an iterator.\n \n Yields: \n 2-tuple\n First is a dictionary, second is a BlockInfo.\n ({encoder_inputs: [batch_size x 1]\n decoder_inputs: [batch_size x (window x 2)]})\n \n BlockInfo is None\n \"\"\"\n assert self.reader is not None, 'must call prepare() first'\n # shuffle blocks\n block_indices = shuffled_indices(self.block_per_epoch)\n for idx in block_indices:\n raw_data = self.reader[idx]\n # convert string line to list of ints\n raw_data = map(lambda s: map(int, s.strip().split()), raw_data)\n # concatenate all sentences\n flat_data = list(itertools.chain.from_iterable(raw_data))\n # compute approximate batch_per_block\n batch_per_block = ((len(flat_data) - 2 * self.window) \n // self.skip // self.batch_size)\n del raw_data # save memory\n\n if batch_per_block == 0:\n continue\n \n ptr = self.window # data pointer starts at the first center word\n offset_range = range(-self.window, self.window+1)\n offset_range.remove(0) # e.g. [-3, -2, -1, 1, 2, 3]\n for i in range(batch_per_block):\n # k-hot encoding (entries are word counts, can be > 1.0)\n decoder_inputs = np.zeros((self.batch_size, self.vocab_size))\n encoder_inputs = []\n for b in range(self.batch_size):\n encoder_inputs.append(flat_data[ptr])\n # surrounding words\n for offset in offset_range:\n assert 0 <= ptr+offset < len(flat_data)\n word_id = flat_data[ptr+offset]\n decoder_inputs[b, word_id] += 1.0\n ptr += self.skip\n \n encoder_inputs = np.array(encoder_inputs, dtype=np.int32)\n # self.block_size is sentence level, meaningless\n block_info = BlockInfo(batch_per_block=batch_per_block,\n block_size=0,\n is_first_batch= (i == 0))\n feed_dict = AttributeDict(encoder_inputs=encoder_inputs,\n decoder_inputs=decoder_inputs)\n yield feed_dict, block_info\n\n\nclass ParallelWordCorpus(AbstractCorpus):\n def __init__(self, folder, \n corpus_file, \n mono_corpora,\n batch_size):\n \"\"\"\n Each line of the corpus has two tokens separated by space. \n The first symbols is English and the second is foreign (fo). \n \n Args:\n mono_corpora: a two-tuple of MonoStreamCorpus, En and Fo. The corpora must\n have `vocab` field that maps string to int ID. \n \"\"\"\n AbstractCorpus.__init__(self, folder=folder, \n corpus_file=corpus_file, \n vocab_prefix=None, \n batch_size=batch_size, \n block_size=None)\n assert is_list_len(mono_corpora, 2), \\\n 'mono_corpora must have two items [en_corpus, fo_corpus]'\n assert hasattr(mono_corpora[0], 'vocab'), 'EN corpus does not have vocab'\n assert hasattr(mono_corpora[1], 'vocab'), 'FO corpus does not have vocab'\n self.vocab = (mono_corpora[0].vocab, mono_corpora[1].vocab)\n self.paired_words = None\n \n\n @overrides\n def prepare(self):\n self.reader = InMemoryFile(self.corpus_path,\n data_fmt=InMemoryFile.TEXT,\n block_size=0)\n # list of (en word int, fo word int)\n self.paired_words = []\n for line in self.reader:\n line = line.strip().split()\n assert len(line) == 2, 'each line should have two tokens (en, fo) word'\n # look up word int IDs in the vocab dict\n line = [self.vocab[0].get(line[0], UNK_ID), \n self.vocab[1].get(line[1], UNK_ID)]\n self.paired_words.append(line)\n \n \n @property\n @overrides\n def batch_per_epoch(self):\n assert self.paired_words is not None, 'must call prepare() first'\n return len(self.paired_words) // self.batch_size\n \n\n def __iter__(self):\n \"\"\"\n Yields:\n {'encoder_inputs_p': [batch x 1] int IDs for en\n 'decoder_inputs_p': [batch x 1] int IDs for fo}\n \n BlockInfo = null\n \"\"\"\n assert self.paired_words is not None, 'must call prepare() first'\n # shuffle all pairs\n random.shuffle(self.paired_words)\n batch_per_epoch = self.batch_per_epoch\n assert batch_per_epoch > 0\n for b in range(batch_per_epoch):\n words = np.array(self.paired_words[self.batch_size * b:\n self.batch_size * (b+1)],\n dtype=np.int32)\n feeds = {'encoder_inputs_p': words[:, 0],\n 'decoder_inputs_p': words[:, 1]}\n yield feeds, BlockInfo(None, None, None)\n\n\nclass SemiWordCorpus(AbstractCorpus):\n def __init__(self, mono_en, mono_fo, para_file, mode):\n \"\"\"\n Args:\n mono_en, mono_fo: corpora\n para_file: file name for parallel corpus\n mode: 0 - train, 1 - valid\n \"\"\"\n assert isinstance(mono_en, AbstractCorpus)\n assert isinstance(mono_fo, AbstractCorpus)\n self.mono_en = mono_en\n self.mono_fo = mono_fo\n\n transfer_attrs(self.mono_en, self, \n include_filter=['folder',\n 'batch_size',\n 'token_ids_to_sentence'])\n self.mode = mode\n self.para_file = para_file\n \n \n @overrides\n def prepare(self, *args, **kwargs):\n for mono_corpus in [self.mono_en, self.mono_fo]:\n mono_corpus.prepare(*args, **kwargs)\n self.vocab_size = self.mono_en.vocab_size\n \n if self.mode == 0:\n ParaCorpus = circular_iterable(0)(ParallelWordCorpus)\n else:\n ParaCorpus = ParallelWordCorpus\n self.para_corpus = ParaCorpus(self.folder,\n corpus_file=self.para_file,\n mono_corpora=[self.mono_en, self.mono_fo],\n batch_size=self.batch_size)\n self.para_corpus.prepare()\n\n \n @property\n @overrides\n def batch_per_epoch(self):\n return min(self.mono_en.batch_per_epoch,\n self.mono_fo.batch_per_epoch)\n \n \n @overrides\n def __iter__(self):\n for mono0, mono1, para in itertools.izip(self.mono_en,\n self.mono_fo,\n self.para_corpus):\n mono = [mono0, mono1]\n feeds = {'encoder_inputs': \n [mono[l][0]['encoder_inputs'] for l in [0,1]],\n 'decoder_inputs': \n [mono[l][0]['decoder_inputs'] for l in [0,1]]}\n feeds = merge_dicts(feeds, para[0])\n yield feeds, mono0[1]\n\n\n# ========================================================\n# Debugging corpus ONLY. \n# ========================================================\nclass ShiftedDualCorpus(MonoStreamCorpus):\n \"\"\"\n A fake dual corpus that shifts English to create a \"new\" language.\n The shifted-English will be marked with a degree symbol. \n \"\"\"\n @overrides\n def prepare(self, *args, **kwargs):\n \"\"\"\n Vocab [1 to N] and [N+1 to 2N] are the same, with shifted indices\n \"\"\"\n MonoStreamCorpus.prepare(self, *args, **kwargs)\n # add a degree symbol\n for i in range(len(self.rev_vocab)):\n self.rev_vocab.append(u'{}\\u00b0'.format(\n self.rev_vocab[i].decode('utf-8')))\n \n self.vocab_shifted = {v: idx + self.vocab_size\n for v, idx in self.vocab.iteritems()}\n\n\n @overrides\n def __iter__(self):\n \"\"\"\n Yields: {'encoder_inputs': [ lang0, lang1] ...}\n \"\"\"\n assert self.reader is not None, 'must call prepare() first'\n # shuffle blocks except for the last one, which might be smaller\n block_indices = shuffled_indices(self.block_per_epoch - 1)\n for idx, shift_idx in (zip(block_indices, reversed(block_indices))\n + [(self.block_per_epoch - 1, ) * 2]):\n all_data = []\n for i, is_shifted in zip([idx, shift_idx], [False, True]):\n raw_data = self.reader[i]\n # convert string line to list of ints\n if is_shifted:\n raw_data = [map(lambda x: int(x)+self.vocab_size, \n s.strip().split()) \n for s in raw_data]\n else:\n raw_data = [map(int, s.strip().split()) \n for s in raw_data]\n \n # length along the second dimension\n block_size = len(raw_data)\n batch_len = block_size // self.batch_size \n\n data = np.empty([self.batch_size, batch_len], dtype=object)\n # each line is of batch_len, row dim = batch_size\n for i in range(self.batch_size):\n data[i] = raw_data[batch_len * i : batch_len * (i + 1)]\n\n # number of batches per epoch\n if not is_shifted:\n batch_per_block = batch_len // self.NS\n else:\n # shifted version should have the same batch_per_block\n assert batch_per_block == batch_len // self.NS\n \n if batch_per_block == 0:\n continue\n \n if is_div(batch_len, self.NS) and not self.is_self_encode:\n # When batch_len is a multiple of NS, the last NS in batch_len \n # will not have the next element. \n # wraps the data around with the lower right corner = PLACEHOLDER\n data = self._wrap_around(data)\n assert data.shape, (self.batch_size, batch_len + 1)\n all_data.append(data)\n \n for i in range(batch_per_block):\n block_info = BlockInfo(batch_per_block=batch_per_block,\n block_size=block_size,\n is_first_batch= (i == 0))\n batch_tensors = zip(self.get_batch_tensor(all_data[0], i),\n self.get_batch_tensor(all_data[1], i))\n yield self.to_feed_dict(batch_tensors), block_info\n\n\n# ====== Debug\nclass ShiftedParallelCorpus(ShiftedDualCorpus):\n \"\"\"\n A fake parallel corpus that shifts English to create a \"new\" language.\n The shifted-English will be marked with a degree symbol. \n \"\"\"\n def __init__(self, *args, **kwargs):\n kwargs['num_sentence_step'] = -1\n kwargs['is_self_encode'] = None\n MonoStreamCorpus.__init__(self, *args, **kwargs)\n \n @property\n @overrides\n def batch_per_epoch(self):\n bpb = self.block_size // self.batch_size\n # last block might be smaller than self.block_size\n bpb_last = len(self.reader[-1]) // self.batch_size\n return bpb * (self.block_per_epoch - 1) + bpb_last\n \n \n @overrides\n def __iter__(self):\n \"\"\"\n encoder_inputs_p, decoder_inputs_p, target_weights_p are all \n 2-tuples of (en->en', en'->en)\n encoder_inputs_p[0] and decoder_inputs_p[0] should be fed as input and \n output for the translation sub-network.\n MAKE SURE the [0] and [1] match each other when switching write-head!!!\n \"\"\"\n assert self.reader is not None, 'must call prepare() first'\n block_indices = shuffled_indices(self.block_per_epoch)\n\n for idx in block_indices:\n raw_data = self.reader[idx]\n raw_data = [map(int, s.strip().split()) for s in raw_data]\n random.shuffle(raw_data)\n raw_data_shift = [map(l_add(self.vocab_size), s) for s in raw_data]\n \n # length along the second dimension\n block_size = len(raw_data)\n batch_per_block = block_size // self.batch_size\n if batch_per_block == 0:\n continue\n \n for i in range(batch_per_block):\n block_info = BlockInfo(batch_per_block=batch_per_block,\n block_size=block_size,\n is_first_batch= (i == 0))\n # en -> shifted_en\n en_fr = self.get_batch_tensor(raw_data, \n raw_data_shift, \n i)\n # shifted_en -> en\n fr_en = self.get_batch_tensor(raw_data_shift, \n raw_data, \n i)\n yield (self.to_feed_dict(zip(en_fr, fr_en),\n names=['encoder_inputs_p',\n 'decoder_inputs_p',\n 'target_weights_p']), \n block_info)\n\n\n @overrides\n def get_batch_tensor(self, data_enc, data_dec, i):\n \"\"\"\n data_enc and data_dec are two different languages, must be aligned.\n data_enc will be fed to encoder while data_dec to decoder.\n \"\"\"\n # ragged arrays of batched enc and dec\n data_enc = data_enc[i*self.batch_size:(i+1)*self.batch_size]\n data_dec = data_dec[i*self.batch_size:(i+1)*self.batch_size]\n enc_inputs = self.batch_encoder_pad(data_enc)\n dec_inputs, target_weights = self.batch_decoder_pad(data_dec)\n \n return (np.array(enc_inputs, np.int32),\n np.array(dec_inputs, np.int32),\n np.array(target_weights, np.float32))\n \n\ndef CycleShiftedParallelCorpus(cycles):\n return circular_iterable(cycles)(ShiftedParallelCorpus)\n\n\n# ====== Debug\nclass ShiftedSemiCorpus(AbstractCorpus):\n def __init__(self, mono_corpus, parallel_corpus):\n self.mono_corpus = mono_corpus\n self.parallel_corpus = parallel_corpus\n self.token_ids_to_sentence = self.mono_corpus.token_ids_to_sentence\n \n \n @overrides\n def prepare(self, *args, **kwargs):\n self.mono_corpus.prepare(*args, **kwargs)\n self.parallel_corpus.prepare(*args, **kwargs)\n \n @property\n @overrides\n def batch_per_epoch(self):\n return self.mono_corpus.batch_per_epoch\n \n \n @overrides\n def __iter__(self):\n for mono, parallel in itertools.izip(self.mono_corpus,\n self.parallel_corpus):\n mono_feeds, mono_info = mono\n par_feeds, par_info = parallel\n \n assert len(set(mono_feeds.keys()) & set(par_feeds.keys())) == 0, \\\n '{} and {} should not have overlap'.format(mono_feeds, par_feeds)\n yield merge_dicts(mono_feeds, par_feeds), mono_info","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":61464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"360888770","text":"#Enter deposit\r\n#Enter widthdrawal\r\n#validate quit\r\ndef menu():\r\n print(\"\"\"\r\n 1.balance\r\n 2.Withdrawal\r\n 3.deposit\r\n 4.Quit\r\n 5.Menu\r\n \"\"\")\r\n \r\nbalance = 150000.00\r\nmenu()\r\nOption = int(input(\"Enter Menu Option\")) \r\n\r\nif Option==1:\r\n print(\"balance:\", balance)\r\n rb= input(\"Type “menu” and press enter to go back to main menu\")\r\n if rb == \"menu\":\r\n menu()\r\n else:\r\n exit()\r\nif Option == 2:\r\n print (\"balance:\" , balance)\r\n withdrawal= float(input(\"Enter amount and press enter (or type menu and press enter to go back to main menu)\"))\r\n if withdrawal == \"menu\":\r\n menu()\r\n elif withdrawal > 0:\r\n fb = (balance - withdrawal)\r\n print(\"foreward balance\" ,fb)\r\n elif withdrawal > balance or 20000:\r\n print (\"insufficient funds in account\")\r\n else:\r\n print(\"No withdawal made\")\r\n print (\"Max withdrawal for the day is 50000\")\r\n print (\"Max withdrawal per transaction is 20000\")\r\n print (\"Max withdrawal frequency is 3\")\r\n \r\n \r\nif Option == 3:\r\n print(\"balance:\", balance)\r\n deposit = float(input(\"Enter amount and press enter (or type menu and press enter to go back to main menu)\"))\r\n if deposit == \"menu\":\r\n menu()\r\n elif deposit > 40000:\r\n print(\"Deposit must be 40,000 and below\") \r\n elif deposit > 0:\r\n fb = (balance + deposit)\r\n print(\"foreward balance:\" , fb)\r\n else:\r\n print(\"None deposit made:\")\r\n print (\"Max deposit for the day is 150000\")\r\n print (\"Max deposit per transaction is 40000\")\r\n print (\"Max deposit frequency for the day is 4\")\r\nif Option == 4:\r\n quit = input(\"Are you sure you want to quit? (yes/no)\")\r\n if quit == \"yes\":\r\n exit()\r\n else:\r\n print (Option)\r\nif Option == 5:\r\n menu() \r\n\r\n\r\n\r\n\r\n","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"314095352","text":"# supported python 2.7\r\n#\r\n# https://www.clips.uantwerpen.be/pages/pattern-en#parser\r\n# With relations=True each word is annotated with a role tag (e.g., -SBJ for subject or -OBJ for).\r\n# With lemmata=True each word is annotated with its base form.\r\n# With tokenize=False, punctuation marks will not be separated from words.\r\n#\r\n# https://www.clips.uantwerpen.be/pages/MBSP-tags\r\n# Relation tags\r\n# . sentence subject(SBJ)\r\n# . sentence object(OBJ)\r\n#\r\n# python -m pip install vaderSentiment\r\n#\r\n#-*- coding: utf-8 -*-\r\nimport os\r\nimport re\r\nimport nltk\r\nfrom nltk.corpus.reader import WORD\r\nfrom pattern.en import parse, tree, pprint, Sentence, parsetree, Text, Chunk, tag, conjugate, lemma, lexeme\r\nfrom pattern.search import search\r\nfrom pattern.text import Sentence\r\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\r\nimport sqlite3\r\n\r\n\"\"\"\r\ns = 'The mobile web is more important than mobile apps.'\r\ns = parsetree(s)\r\nfor sentence in s:\r\n for chunk in sentence.chunks:\r\n for word in chunk.words:\r\n print (word),\r\n print()\r\n\r\n\"\"\"\r\n\r\n#s = parsetree('The mobile web is more important than mobile apps.', relations=True, lemmata=True)\r\n#print repr(s)\r\n#print parse('I ate pizza.').split()\r\n\r\n#s = 'The mobile web is more important than mobile apps.'\r\n#pprint(parse(s, relations=True, lemmata=True))\r\n\r\n#path = \"/Users/u.hyeyeon/Dropbox/_VTT/dataset/bbc/\"\r\n#path = \"/Users/u.hyeyeon/Dropbox/_VTT/dataset/FilmCorpus2.0/imsdb_raw_nov_2015/\"\r\n\r\npath = \"E:/Dropbox/_VTT/dataset/bbc/\"\r\n\r\nsid=SentimentIntensityAnalyzer()\r\n\r\ncon = sqlite3.connect(\"Corpus.db\")\r\ncon.isolation_level = None # auto commit\r\ncursor = con.cursor()\r\n\r\nfileSeq=0\r\ngenreFolder=\"entertainment\"\r\nfiles = \"289.txt\"\r\n\r\n\r\nfileSeq = fileSeq + 1\r\n#con.execute(\"INSERT INTO fileTBL (seq, genre, fileName, corpus) VALUES(?, ?, ?, ?)\", (fileSeq, genreFolder, files, 'BBC', ))\r\n\r\nf = open(path + genreFolder + \"/\" + files, \"r\")\r\nplotText = f.read()\r\nf.close()\r\n\r\nplotText = re.sub('', '', plotText, 0, re.I | re.S)\r\nplotText = re.sub('<.+?>', '', plotText, 0, re.I | re.S)\r\nsentList = [x.replace(\"\\n\",\" \") for x in nltk.sent_tokenize(plotText.decode('utf-8').replace(\"\\t\",\"\"))]\r\n\r\nsentenceSeq = 0\r\nfor strSentence in sentList:\r\n #print(\"strSentence : \", strSentence)\r\n\r\n sentenceSeq+=1\r\n sentiment = sid.polarity_scores(strSentence)\r\n #con.execute(\"INSERT INTO sentenceTBL (fileSeq, seq, sentence, obj, pos, neg, neu, com) VALUES(?, ?, ?, ?, ?, ?, ?)\", (fileSeq, sentenceSeq, strSentence, sentiment[\"neg\"], sentiment[\"neu\"], sentiment[\"compound\"]))\r\n\r\n a = parse(strSentence, relations=True, lemmata=True)\r\n #pprint(a)\r\n\r\n sentence = Sentence(a)\r\n\r\n listVP = []\r\n listOBJ = []\r\n listSBJ = []\r\n # solved Dictionary's Key None\r\n if (None in sentence.relations[\"VP\"] or None in sentence.relations[\"SBJ\"] or None in sentence.relations[\"OBJ\"]):\r\n listVP.append(\"\")\r\n listOBJ.append(\"\")\r\n listSBJ.append(\"\")\r\n\r\n for key, val in sentence.relations[\"VP\"].items():\r\n if (\"None\" in str(key)):\r\n listVP[0] = val\r\n else :\r\n listVP.append(val)\r\n\r\n for key, val in sentence.relations[\"SBJ\"].items():\r\n if (\"None\" in str(key)):\r\n listSBJ[0] = val\r\n listSBJ.append(val)\r\n\r\n for key, val in sentence.relations[\"OBJ\"].items():\r\n if (\"None\" in str(key)):\r\n listOBJ[0] = val\r\n listOBJ.append(val)\r\n\r\n maxID = max(len(listVP), len(listOBJ), len(listSBJ))\r\n if (maxID > 0) :\r\n for i in range(maxID):\r\n try:\r\n subject = ' '.join(listSBJ[i].lemmata)\r\n except :\r\n subject = \"\"\r\n\r\n try:\r\n verbs = ' '.join(listVP[i].lemmata)\r\n except :\r\n verbs = \"\"\r\n\r\n try:\r\n objects = ' '.join(listOBJ[i].lemmata)\r\n except :\r\n objects = \"\"\r\n\r\n\r\n\r\n print(subject, verbs, objects, i)\r\n\r\n #con.execute(\"INSERT INTO ChunkTBL (fileSeq, sentSeq, id, sbj, vp, obj) VALUES(?, ?, ?, ?, ?, ?)\", (fileSeq, sentenceSeq, i, subject, verbs, objects), )\r\n print (\"====================================================\")\r\n\r\n #print strVP\r\n #print(sentence.relations)\r\n #print(sentence.subjects)\r\n #print(sentence.objects)\r\n #print(sentence.verbs)\r\n #print(sentence.chunk)\r\n\r\ncon.close()\r\n\r\n'''\r\ncon = sqlite3.connect(\"causalRelation.db\")\r\ncon.isolation_level = None # auto commit\r\ncursor = con.cursor()\r\n\r\nprevVerb = verbList[0]\r\nverbDic = {}\r\nfor i in range(1,len(verbList)-1):\r\n if (verbList[i] not in (\"be\",\"do\",\"let\",\"begin\",\"have\",\"try\",\"start\")):\r\n print (prevVerb, \"_\", verbList[i])\r\n\r\n if (prevVerb+\"_\"+verbList[i] in verbDic):\r\n verbDic[prevVerb+\"_\"+verbList[i]] = verbDic[prevVerb+\"_\"+verbList[i]] + 1\r\n con.execute(\"UPDATE pmiScoreGenre SET count = count + 1 WHERE genre=? AND eventPair=?\", (genreFolder, prevVerb + \"_\" + verbList[i],))\r\n else :\r\n verbDic[prevVerb+\"_\"+verbList[i]] = 1\r\n con.execute(\"INSERT INTO pmiScoreGenre(eventPair, count, genre) VALUES(?, ?, ?)\", (prevVerb + \"_\" + verbList[i], 1, genreFolder, ))\r\n prevVerb = verbList[i]\r\n\r\n\r\nprint (\"verbList =====================>>>>> \", verbList)\r\nprint (\"vpList =====================>>>>> \", vpList)\r\nprint (\"verbDic =====================>>>>> \", verbDic)\r\n\r\n # sqlite3 insert : subject / objects / verbs / CPC / Sentiment\r\n # genre, wordCount, filename, sentence\r\n # subject : Chunk('he/NP-SBJ-1'), Chunk('you/NP-SBJ-2')]\r\n # objects : [Chunk('it/NP-OBJ-2')]\r\n # verbs : [Chunk('would n't talk/VP-1'), Chunk('saw/VP-2')]\r\n # CPC :\r\n # Sentiment : {'neg': 0.0, 'neu': 0.853, 'pos': 0.147, 'compound': 0.1406}\r\n\r\n #ret.write(strSentence+\"\\n\")\r\n'''","sub_path":"extraction_svo_sentiment_1.py","file_name":"extraction_svo_sentiment_1.py","file_ext":"py","file_size_in_byte":5889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"354242227","text":"#!/usr/bin/python3\nimport sys\nimport json\nimport os\nimport subprocess\n\nDATA_DIR = \"data\"\nVALIDATOR_DIR = \"validator\"\n\nindex = 0\ndef get_matching(subtask_score):\n global index\n index += 1\n\n valid_cases = []\n for f in os.listdir(DATA_DIR):\n if os.path.isfile(os.path.join(DATA_DIR, f)) and f.endswith(\".in\"):\n # Run the validator\n p = subprocess.Popen(os.path.join(VALIDATOR_DIR, \"sub%d\" % index) + \" < \" + os.path.join(DATA_DIR, f), shell=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)\n p.wait()\n\n # The validator returns 0 upon success\n if p.returncode == 0:\n valid_cases.append(f[:-3])\n\n valid_cases_regex = \"^({})$\".format(\"|\".join(valid_cases))\n\n # [subtask_score, subtask_regex, subtask_name]\n return [subtask_score, valid_cases_regex, \"Subtask {}\".format(str(index))]\n\nsubtasks = [get_matching(int(s)) for s in sys.argv[1:]]\n\n\nprint(json.dumps(subtasks, indent=2))\n","sub_path":"spire/cmsify.py","file_name":"cmsify.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"163699040","text":"from django.shortcuts import render\n#from search.models import request\n\n\n# Create your views here.\ndef index(request):\n return render(request, 'config/home.html')\n\n#View used to select number of hosts/commands\ndef choose_hosts(request):\n if request.method == 'POST':\n num_rows = request.POST['rows']\n context_dict = {'num_rows': range(int(num_rows)), 'n':num_rows}\n return render(request, 'config/home.html', context_dict)\n\ndef hosts(request):\n\n #init host and cmd list\n hostlist = []\n cmdlist = []\n\n if request.method == 'POST':\n #Convert the number of rows to an integer from unicode\n n = int(request.POST.get('n')[0])\n for i in range(n):\n hostlist.append(str(request.POST['host'+str(i)]))\n cmdlist.append(str(request.POST['cmd'+str(i)]))\n #paramiko(hostlist,cmdlist)\n else:\n error_message = 'This was not a POST request'\n return render('search/confirmation.html', {\n 'error_message': error_message,\n })\n return render(request, 'config/home.html')\n\ndef upload(request):\n return render(request, 'config/home.html')","sub_path":"vailconfig/config/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"410610197","text":"import logging\nfrom collections import defaultdict\nfrom plynx.db.graph import Graph\nfrom plynx.db.node_cache_manager import NodeCacheManager\nfrom plynx.constants import NodeRunningStatus, GraphRunningStatus\nfrom plynx.graph.base_nodes import NodeCollection\nfrom plynx.utils.common import to_object_id\nfrom plynx.utils.config import get_web_config\n\n\nclass GraphScheduler(object):\n \"\"\" Main graph scheduler.\n\n It works with a single db.graph.Graph object.\n GraphScheduler loads the Graph from DB.\n It determines Nodes to be executed.\n\n Args:\n graph (str or Graph)\n\n \"\"\"\n node_cache_manager = NodeCacheManager()\n WEB_CONFIG = get_web_config()\n\n def __init__(self, graph, node_collection=None):\n if isinstance(graph, Graph):\n self.graph_id = graph._id\n self.graph = graph\n else:\n self.graph_id = graph\n self.graph = Graph.load(self.graph_id)\n\n self.node_id_to_node = {\n node._id: node for node in self.graph.nodes\n }\n\n # number of dependencies to ids\n self.dependency_index_to_node_ids = defaultdict(lambda: set())\n self.node_id_to_dependents = defaultdict(lambda: set())\n self.node_id_to_dependency_index = defaultdict(lambda: 0)\n self.uncompleted_nodes_count = 0\n if node_collection:\n self.node_collection = node_collection\n else:\n self.node_collection = NodeCollection()\n\n for node in self.graph.nodes:\n # ignore nodes in finished statuses\n if NodeRunningStatus.is_finished(node.node_running_status):\n continue\n node_id = node._id\n dependency_index = 0\n for node_input in node.inputs:\n for input_value in node_input.values:\n parent_node_id = to_object_id(input_value.node_id)\n self.node_id_to_dependents[parent_node_id].add(node_id)\n if not NodeRunningStatus.is_finished(self.node_id_to_node[parent_node_id].node_running_status):\n dependency_index += 1\n\n if not NodeRunningStatus.is_finished(node.node_running_status):\n self.uncompleted_nodes_count += 1\n self.dependency_index_to_node_ids[dependency_index].add(node_id)\n self.node_id_to_dependency_index[node_id] = dependency_index\n\n def finished(self):\n if self.graph.graph_running_status == GraphRunningStatus.FAILED_WAITING:\n # wait for the rest of the running jobs to finish\n # check running status of each of the nodes\n for node in self.graph.nodes:\n if node.node_running_status == NodeRunningStatus.RUNNING:\n return False\n # set status to FAILED\n self.graph.graph_running_status = GraphRunningStatus.FAILED\n self.graph.save(force=True)\n return True\n return self.graph.graph_running_status in {GraphRunningStatus.SUCCESS, GraphRunningStatus.FAILED, GraphRunningStatus.CANCELED}\n\n def pop_jobs(self):\n \"\"\"Get a set of nodes with satisfied dependencies\"\"\"\n res = []\n if GraphRunningStatus.is_failed(self.graph.graph_running_status):\n return res\n cached_nodes = []\n for node_id in self.dependency_index_to_node_ids[0]:\n node = self._get_node_with_inputs(node_id).copy()\n if GraphScheduler._cacheable(node):\n try:\n cache = GraphScheduler.node_cache_manager.get(node, self.graph.author)\n if cache:\n node.node_running_status = NodeRunningStatus.RESTORED\n node.outputs = cache.outputs\n node.logs = cache.logs\n node.cache_url = '{}/graphs/{}?nid={}'.format(\n GraphScheduler.WEB_CONFIG.endpoint.rstrip('/'),\n str(cache.graph_id),\n str(cache.node_id),\n )\n cached_nodes.append(node)\n continue\n except Exception as err:\n logging.exception(\"Unable to update cache: `{}`\".format(err))\n job = self.node_collection.make_job(node)\n res.append(job)\n del self.dependency_index_to_node_ids[0]\n\n for node in cached_nodes:\n self.update_node(node)\n\n return res\n\n def update_node(self, node):\n dest_node = self.node_id_to_node[node._id]\n if node.node_running_status == NodeRunningStatus.SUCCESS \\\n and dest_node.node_running_status != node.node_running_status \\\n and GraphScheduler._cacheable(node):\n GraphScheduler.node_cache_manager.post(node, self.graph_id, self.graph.author)\n\n if dest_node.node_running_status == node.node_running_status:\n return\n\n self._set_node_status(node._id, node.node_running_status)\n # TODO smarter copy\n dest_node.logs = node.logs\n dest_node.outputs = node.outputs\n dest_node.cache_url = node.cache_url\n\n self.graph.save(force=True)\n\n def _set_node_status(self, node_id, node_running_status):\n node = self.node_id_to_node[node_id]\n node.node_running_status = node_running_status\n\n if node_running_status == NodeRunningStatus.FAILED:\n self.graph.graph_running_status = GraphRunningStatus.FAILED_WAITING\n\n if node_running_status in {NodeRunningStatus.SUCCESS, NodeRunningStatus.FAILED, NodeRunningStatus.RESTORED}:\n for dependent_node_id in self.node_id_to_dependents[node_id]:\n dependent_node = self.node_id_to_node[dependent_node_id]\n prev_dependency_index = self.node_id_to_dependency_index[dependent_node_id]\n\n removed_dependencies = 0\n for node_input in dependent_node.inputs:\n for input_value in node_input.values:\n if to_object_id(input_value.node_id) == to_object_id(node_id):\n removed_dependencies += 1\n dependency_index = prev_dependency_index - removed_dependencies\n\n self.dependency_index_to_node_ids[prev_dependency_index].remove(dependent_node_id)\n self.dependency_index_to_node_ids[dependency_index].add(dependent_node_id)\n self.node_id_to_dependency_index[dependent_node_id] = dependency_index\n self.uncompleted_nodes_count -= 1\n\n if self.uncompleted_nodes_count == 0 and not GraphRunningStatus.is_failed(self.graph.graph_running_status):\n self.graph.graph_running_status = GraphRunningStatus.SUCCESS\n\n # self.graph.save()\n\n def _get_node_with_inputs(self, node_id):\n \"\"\"Get the node and init its inputs, i.e. filling its resource_ids\"\"\"\n res = self.node_id_to_node[node_id]\n for node_input in res.inputs:\n for value in node_input.values:\n value.resource_id = self.node_id_to_node[to_object_id(value.node_id)].get_output_by_name(\n value.output_id\n ).resource_id\n return res\n\n @staticmethod\n def _cacheable(node):\n for parameter in node.parameters:\n if parameter.name == 'cacheable':\n return parameter.value\n return False\n","sub_path":"plynx/graph/graph_scheduler.py","file_name":"graph_scheduler.py","file_ext":"py","file_size_in_byte":7418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"7470666","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function, division\nimport sys\nif sys.version_info.major < 3:\n\tinput = raw_input\nfrom lib import *\n# Factorial digit sum\n# Problem 20\n# n! means n × (n − 1) × ... × 3 × 2 × 1\n# For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,\n# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.\n# Find the sum of the digits in the number 100!\nNumber = 100\n#Answer = 648\n\nif __name__ == \"__main__\":\n\tprint(\n\t\tsum(\n\t\t\tmap(\n\t\t\t\tint,\n\t\t\t\tstr(factorial(Number))\n\t\t\t\t)\n\t\t\t)\n\t\t)","sub_path":"problem_20.py","file_name":"problem_20.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"514770698","text":"#!/usr/bin/env python3\n\nimport logging\nfrom typing import (\n Any,\n Awaitable,\n Callable,\n Dict,\n List,\n Optional,\n Type,\n TypeVar,\n get_type_hints,\n)\n\nimport discord\n\nfrom commands import (\n ban,\n clear_stats,\n macro,\n remindme,\n rename,\n reset_roll,\n roll,\n scoreboard,\n set_msg,\n set_timeout,\n)\nfrom message_context import MessageContext\nfrom models import BotParam, GreedyStr\n\n\nCommandFunc = Callable[..., Awaitable[None]]\nT = TypeVar(\"T\")\n\n\nDEFAULT_REGISTERED_COMMANDS = [\n # Basic roll commands\n roll.roll,\n # Scoreboard commands\n scoreboard.scoreboard,\n # Set win/loss message commands\n set_msg.set_msg,\n # Server/chat renaming commands\n rename.rename,\n # Reset roll commands\n reset_roll.reset_roll,\n # Roll timeout commands\n set_timeout.set_timeout,\n # Clear stats commands\n clear_stats.clear_stats,\n # Reminder commands\n remindme.remindme,\n # Ban commands\n ban.ban,\n ban.unban,\n # Macro commands\n macro.macro_add,\n macro.macro_del,\n macro.m,\n]\n\n\nclass CommandRunner:\n def __init__(self, cmds: Optional[List[CommandFunc]] = None) -> None:\n cmds = cmds or DEFAULT_REGISTERED_COMMANDS\n self.cmds = {cmd.__name__: cmd for cmd in cmds}\n\n def register(self, cmd: CommandFunc) -> None:\n self.cmds[cmd.__name__] = cmd\n\n @staticmethod\n def is_botparam_type(t: Any) -> bool:\n if hasattr(t, \"__origin__\"):\n return issubclass(t.__origin__, BotParam)\n\n @staticmethod\n def typify(typ: Type[T], value: str) -> Any:\n from_str_callable = getattr(typ, \"from_str\", None)\n if callable(from_str_callable):\n return from_str_callable(value)\n else:\n # Assume typ takes a string constructor\n return typ(value)\n\n @staticmethod\n def typify_all(f: CommandFunc, args: List[str]) -> Dict[str, Any]:\n types = get_type_hints(f)\n\n # Validate that this is a function taking a MessageContext\n ctx_param = None\n for k, v in types.items():\n if v is MessageContext:\n ctx_param = k\n\n if ctx_param is None:\n error = \"Can only typify function with signature like:\\n\\t\"\n error += \"async def func(MessageContext, ...)\"\n raise TypeError(error)\n\n # Remove those specialized arguments now\n del types[ctx_param]\n\n # TODO - Currently only handles GreedyStr as last arg\n # To handle in another position, we'd need to use something like\n # a regex matcher algorithm; not worth it currently\n argc = f.__code__.co_argcount\n parameters = list(f.__code__.co_varnames[:argc])\n for i in range(len(parameters)):\n if parameters[i] == ctx_param:\n del parameters[i]\n break\n\n # Also check if there are bot params we should disable\n parameters = [\n param\n for param in parameters\n if not CommandRunner.is_botparam_type(types[param])\n ]\n\n if len(parameters) > 0 and types[parameters[-1]] is GreedyStr:\n # This is -1 because the last argument will be part of the glob\n n = len(parameters) - 1\n args, glob = args[:n], args[n:]\n greedy_arg = \" \".join(glob)\n args.append(greedy_arg)\n\n # TODO: This is *maybe* a good idea, but if we want to support default\n # arguments, I think it could cause some additional headaches. For now,\n # let's just allow extraneous arguments.\n # if len(parameters) != len(args):\n # raise ValueError(f\"Have {len(parameters)} parameters bUt {len(args)} args given\")\n\n # Make sure *all* arguments are kwargs now\n typed_args = {\n k: CommandRunner.typify(types[k], v)\n # TODO: We implicitly rely on ctx being the first param here,\n # which isn't good style... it could break a function\n for k, v in zip(parameters, args)\n }\n return typed_args\n\n async def call(self, ctx: MessageContext) -> None:\n # Split args to prepare for dynamic dispatch\n argv = ctx.message.content.split(\" \")\n funcname, args = argv[0], argv[1:]\n if funcname[0] != \"!\":\n raise ValueError(\"Called CommandRunner without leading `!`\")\n funcname = funcname[1:]\n\n # Now try to call the referenced method\n try:\n func = self.cmds[funcname]\n prepared_args = CommandRunner.typify_all(func, args)\n args_str = \", \".join(args)\n logging.info(f\"Calling {funcname}(ctx, {args_str}) successfully\")\n await func(ctx, **prepared_args)\n except KeyError as ke:\n logging.error(f\"Could not find function {funcname}\")\n raise\n except Exception as e:\n # TODO: Log helpful message to message.guild\n logging.error(f\"Failed to call function: {funcname}(ctx, {args_str})\")\n logging.error(f\"{type(e)}: {e}\")\n # Reraise to let server_context provide help content\n raise\n\n @staticmethod\n def helptext(f: CommandFunc, limit: Optional[int] = None) -> str:\n types = get_type_hints(f)\n argc = f.__code__.co_argcount\n args = f.__code__.co_varnames[:argc]\n\n args_str = \"\"\n if len(args) > 0 and types[args[0]] is MessageContext:\n args = args[1:]\n # If there are args, we prepend a space character since it will\n # start right after the function name (otherwise there's a somewhat\n # awkward extra space with helptext for param-less functions)\n if len(args) > 0:\n args_str = \" \"\n # This is going to look like some more witchcraft, but we have to fully\n # instantiate a generic and then check its __class__ attribute since\n # calling issubclass immediately tells us that types[arg] is not a class\n args_str += \" \".join(\n f\"<{arg}>\" for arg in args if not CommandRunner.is_botparam_type(types[arg])\n )\n\n usage = \"\"\n if f.__doc__ and len(f.__doc__) > 0:\n doc = f.__doc__\n if limit and len(doc) > limit:\n doc = doc[:limit] + \"...\"\n usage = f\": {doc}\"\n else:\n usage = f\":\\n{doc}\"\n return f\"__!{f.__name__}__{args_str}{usage}\"\n","sub_path":"command_runner.py","file_name":"command_runner.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"464070398","text":"#! \\Local\\Programs\\Python\\Python36\\python.exe\n# -*- coding: utf-8 -*-\n__author__ = '98221254@qq.com'\n'''\n可重入锁\n - 作用:为了解决递归调用函数或函数多次调用时, 重复申请锁会出现自己产生死锁。\n 可重入锁则允许该函数在释放前,多次申请锁。 \n - 方法:threading.RLock()\n'''\nimport threading\nimport time\n\nnum = 0\n# lock = threading.Lock() # 普通锁: 造成死锁\nlock = threading.RLock() # 可重入锁: 可以运行\n\n\nclass MyThread(threading.Thread):\n def run(self):\n global num\n time.sleep(1)\n if lock.acquire(timeout=1):\n num += 1\n msg = self.name + ' set num to ' + str(num)\n print(msg)\n lock.acquire()\n lock.release()\n lock.release()\n\n\ndef main():\n for i in range(5):\n t = MyThread()\n t.start()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"学习/多线程/008_可重入锁.py","file_name":"008_可重入锁.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"432190611","text":"#!/usr/bin/env python\n# -*- coding: utf8 -*-\n\nimport examples\nimport model\nimport fofunctions\nfrom itertools import product \n\n\ndef sage_lattice_to_model(lat):\n \"\"\"\n Convierte de un reticulado de sage a un modelo.\n \"\"\"\n \n meet = [[[] for i in range(lat.cardinality())] for i in range(lat.cardinality())]\n join = [[[] for i in range(lat.cardinality())] for i in range(lat.cardinality())]\n \n for t in product(range(lat.cardinality()),repeat=2):\n meet[t[0]][t[1]] = lat.meet(*t)\n join[t[0]][t[1]] = lat.join(*t)\n\n meet = fofunctions.FO_Operation(meet)\n join = fofunctions.FO_Operation(join)\n\n return model.FO_Model(examples.tiporet, range(lat.cardinality()), {\"v\": join, \"^\": meet}, {})\n\n\ndef sage_poset_to_model(pos):\n \"\"\"\n Convierte de un poset de sage a un modelo.\n \"\"\"\n le = []\n for t in product(range(pos.cardinality()),repeat=2):\n if pos.le(*t):\n le.append(t)\n le = fofunctions.FO_Relation(le, range(pos.cardinality()))\n return model.FO_Model(examples.tipoposet, range(pos.cardinality()), {}, {\"<=\":le})\n","sub_path":"package/src/definability/sage_to.py","file_name":"sage_to.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"603015387","text":"def outline_rect_dict(basket_h, basket_l, basket_w, palette):\n col_dic = get_colors(palette)\n outline_dictionary = {}\n # Produce outline\n \n basket_dic = {}\n color =col_dic['-']\n for i in range(0, basket_h):\n for j in range(0, 2*basket_l+2*basket_w):\n bottom_left = (j, i)\n # Displays rectangles row by row starting from the first column\n rect = Rectangle( bottom_left, 1, 1, fill = True, facecolor = color, edgecolor = \"white\", linewidth = 1)\n basket_dic[rect] = \"-\"\n return basket_dic\n\ndef plot_rect_empty2D(basket_h, basket_l, basket_w, palette):\n \n global outline\n outline = outline_rect_dict(basket_h, basket_l, basket_w,palette)\n \n global color_mat_rect_DIY\n color_mat_rect_DIY = [ ['-' for j in range(2*basket_l + 2*basket_w)] for i in range(basket_h)]\n\n char_col_dic = get_colors(palette)\n col_char_dic = get_inverse_pattern_dictionary(char_col_dic)\n \n def plot_palette(palette):\n plt.ion()\n fig = plt.figure(figsize=(8, 1), frameon=False)\n ax = fig.add_subplot(111, facecolor = '#ffffff')\n col_pos_dictionary = {}\n \n for x, color in enumerate(palette):\n col_pos_dictionary[(Rectangle((x, 0), 1, 1, facecolor=color))] = (x,color)\n ax.add_patch(Rectangle(((1.5*x), 0), 1, 1, facecolor=color, edgecolor = color, linewidth = 2))\n \n \n def color_picker(event):\n for x, color in enumerate(palette):\n col_pos_dictionary[(Rectangle((x, 0), 1, 1, facecolor=color))] = (x,color)\n ax.add_patch(Rectangle((1.5*x, 0), 1, 1, facecolor = color, edgecolor = 'white', linewidth = 10))\n\n tx = 'x=%f, y=%f' % (event.xdata, event.ydata) \n for key in col_pos_dictionary:\n w,h = key.get_width(),key.get_height()\n x0,y0 = key.xy\n if 1.5*x0 <= event.xdata <= 1.5*x0 + w and y0 <= event.ydata <= y0 + h:\n value = col_pos_dictionary[key]\n position = value[0]\n global new_color\n new_color = value[1]\n rect = Rectangle( (1.5*x0,y0), w,h, fill = False, facecolor = new_color, edgecolor = new_color, linewidth = 10)\n ax.add_patch(rect)\n text_pal.set_text(new_color)\n\n plt.draw()\n \n cid = fig.canvas.mpl_connect('button_press_event', color_picker)\n ax.set_xlim((-0.1, 1.5*len(pal_a)+0.1))\n ax.set_ylim((-0.1, 1.1))\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_aspect(\"equal\")\n plt.show()\n \n \n plot_palette(palette)\n \n fig = plt.figure(figsize=(7,5), frameon=False)\n current_axis= fig.add_subplot(111, facecolor = '#ffffff')\n\n def onclick(event):\n current_axis.add_patch(front_outline)\n current_axis.add_patch(right_outline)\n current_axis.add_patch(back_outline)\n current_axis.add_patch(left_outline)\n tx = 'x=%f, y=%f' % (event.xdata, event.ydata) \n for key in outline:\n w,h = key.get_width(),key.get_height()\n x0,y0 = key.xy\n if x0 <= event.xdata <= x0 + w and y0 <= event.ydata <= y0 + h:\n rect = Rectangle( (x0,y0), w,h, fill = True, facecolor = new_color, edgecolor = 'white', linewidth = 1)\n current_axis.add_patch(rect)\n new_char = col_char_dic[new_color]\n color_mat_rect_DIY[y0][x0] = new_char\n text.set_text(outline[rect])\n\n \n\n cid = fig.canvas.mpl_connect('button_press_event', onclick)\n \n for key in outline:\n current_axis.add_patch(key)\n \n front_outline = Rectangle((0,0), basket_l, basket_h, fill = False, edgecolor = \"black\", linewidth = 2)\n right_outline = Rectangle((basket_l,0), basket_w, basket_h, fill = False, edgecolor = \"black\", linewidth = 2)\n back_outline = Rectangle((basket_l+basket_w,0), basket_l, basket_h, fill = False, edgecolor = \"black\", linewidth = 2)\n left_outline = Rectangle((2*basket_l+ basket_w,0), basket_w, basket_h, fill = False, edgecolor = \"black\", linewidth = 2)\n current_axis.add_patch(front_outline)\n current_axis.add_patch(right_outline)\n current_axis.add_patch(back_outline)\n current_axis.add_patch(left_outline)\n \n \n plt.xlim(-0.25 , 2*basket_l + 2*basket_w + 0.25)\n plt.ylim(-0.25 , basket_h +0.25)\n current_axis.axis('off')\n plt.show()\n\ndef plot_rect3D_DIY(basket_h, basket_l, basket_w, palette):\n \n ax = a3.Axes3D(plt.figure(figsize = (6,6)), facecolor = '#ffffff')\n \n col_dic = get_colors(palette)\n rect_col_list = color_mat_rect_DIY\n\n rows = basket_h + 1\n cols_fb = basket_l + 1\n cols_lr = basket_w + 1\n\n indent = min(basket_w, basket_l)/5\n weave_w = indent/(rows-1)\n z = np.linspace(0, basket_h, rows)\n basket_rim = (z[1]-z[0])/2\n\n x = []\n for i in range(0, rows):\n x.append(np.linspace(indent - i*weave_w, basket_l - indent + i*weave_w, cols_fb))\n \n y = []\n for i in range(0, rows):\n y.append(np.linspace(indent - i*weave_w, basket_w - indent + i*weave_w, cols_lr))\n\n # FRONT\n for i in range(0, basket_h):\n for j in range(0, basket_l):\n\n bottom_left = [x[i][j], indent-i*weave_w, z[i]]\n top_left = [x[i+1][j], indent-(i+1)*weave_w, z[i+1]]\n top_right = [x[i+1][j+1], indent-(i+1)*weave_w, z[i+1]]\n bottom_right = [x[i][j+1], indent-i*weave_w, z[i]]\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n \n color = col_dic[rect_col_list[i][j]]\n rect.set_color(color)\n rect.set_edgecolor('#ad8a54')\n \n ax.add_collection3d(rect)\n \n # BASKET RIM\n if i == rows - 2:\n bottom_left = top_left\n bottom_right = top_right\n top_left = [x[i+1][j], indent-(i+1)*weave_w, z[i+1] + basket_rim]\n top_right = [x[i+1][j+1], indent-(i+1)*weave_w, z[i+1]+ basket_rim]\n\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n rect.set_color('#af8a52')\n rect.set_edgecolor('#87693c')\n ax.add_collection3d(rect)\n \n\n # BACK \n for i in range(0, basket_h):\n for j in range(0, basket_l):\n\n bottom_left = [x[i][j], basket_w - indent + i*weave_w, z[i]]\n top_left = [x[i+1][j], basket_w - indent + (i+1)*weave_w, z[i+1]]\n top_right = [x[i+1][j+1], basket_w - indent + (i+1)*weave_w, z[i+1]]\n bottom_right = [x[i][j+1], basket_w - indent + i*weave_w, z[i]]\n\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n \n color = col_dic[rect_col_list[i][2*basket_l+basket_w-j-1]] \n rect.set_color(color)\n rect.set_edgecolor('#ad8a54')\n ax.add_collection3d(rect)\n \n if i == rows - 2:\n bottom_left = top_left\n bottom_right = top_right\n top_left = [x[i+1][j], basket_w - indent + (i+1)*weave_w, z[i+1] + basket_rim]\n top_right = [x[i+1][j+1], basket_w - indent + (i+1)*weave_w, z[i+1]+ basket_rim]\n\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n rect.set_color('#af8a52')\n rect.set_edgecolor('#87693c')\n ax.add_collection3d(rect)\n\n # RIGHT\n for i in range(0,basket_h): \n for j in range(0, basket_w):\n bottom_left = [basket_l - indent + i*weave_w, y[i][j], z[i]]\n top_left = [basket_l - indent + (i+1)*weave_w, y[i+1][j], z[i+1]]\n top_right = [basket_l - indent + (i+1)*weave_w, y[i+1][j+1], z[i+1]]\n bottom_right = [basket_l - indent + i*weave_w, y[i][j+1], z[i]]\n\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n \n color = col_dic[rect_col_list[i][basket_l + j]] \n rect.set_color(color)\n rect.set_edgecolor('#ad8a54')\n ax.add_collection3d(rect)\n \n if i == rows - 2:\n bottom_left = top_left\n bottom_right = top_right\n top_left = [basket_l - indent + (i+1)*weave_w, y[i+1][j], z[i+1] + basket_rim]\n top_right = [basket_l - indent + (i+1)*weave_w, y[i+1][j+1], z[i+1] + basket_rim]\n\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n rect.set_color('#af8a52')\n rect.set_edgecolor('#87693c')\n ax.add_collection3d(rect)\n \n\n # LEFT \n for i in range(0,rows-1):\n \n for j in range(0, cols_lr-1):\n bottom_left = [indent - i*weave_w, y[i][j], z[i]]\n top_left = [indent - (i+1)*weave_w, y[i+1][j], z[i+1]]\n top_right = [indent - (i+1)*weave_w, y[i+1][j+1], z[i+1]]\n bottom_right = [indent - i*weave_w, y[i][j+1], z[i]]\n\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n\n color = col_dic[rect_col_list[i][2*basket_l+2*basket_w-j-1]] \n rect.set_color(color)\n rect.set_edgecolor('#ad8a54')\n ax.add_collection3d(rect)\n \n if i == rows - 2:\n bottom_left = top_left\n bottom_right = top_right\n top_left = [indent - (i+1)*weave_w, y[i+1][j], z[i+1] + basket_rim]\n top_right = [indent - (i+1)*weave_w, y[i+1][j+1], z[i+1] + basket_rim]\n\n rect_coords = [bottom_left, top_left, top_right, bottom_right]\n rect = a3.art3d.Poly3DCollection([rect_coords]) \n rect.set_color('#af8a52')\n rect.set_edgecolor('#87693c')\n ax.add_collection3d(rect)\n\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n ax.set_xlim(0, basket_l)\n ax.set_ylim(0, basket_w)\n ax.set_zlim(0,basket_h)\n ax.axis('off')\n plt.show()\n\n","sub_path":"Basket-Notebook/python_scripts/older_python_scripts/create_rect.py","file_name":"create_rect.py","file_ext":"py","file_size_in_byte":10690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"552798018","text":"from annotation_app.models import Bill, Senator\n\n\ndef create(senator_name, bill_id):\n senator = Senator.objects.filter(name = senator_name)\n\n if senator:\n senator[0].bills.add(Bill.objects.get(id = bill_id))\n return senator[0]\n\n else:\n senator = Senator()\n senator.name = senator_name\n senator.save()\n\n senator.bills.add(Bill.objects.get(id = bill_id))\n senator.save()\n return senator\n","sub_path":"annotation_app/controllers/senators_controller.py","file_name":"senators_controller.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"61851630","text":"#-------------------------------------------------------------\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n#-------------------------------------------------------------\n\n__all__ = [\"SystemDSContext\"]\n\nimport os\nimport subprocess\nimport threading\nfrom typing import Optional, Sequence, Union, Dict, Tuple, Iterable\n\nimport numpy as np\nfrom py4j.java_gateway import JavaGateway\nfrom py4j.protocol import Py4JNetworkError\n\nfrom systemds.matrix import full, seq, federated, Matrix, rand, OperationNode\nfrom systemds.utils.helpers import get_module_dir\nfrom systemds.utils.consts import VALID_INPUT_TYPES\n\nPROCESS_LOCK: threading.Lock = threading.Lock()\nPROCESS: Optional[subprocess.Popen] = None\nACTIVE_PROCESS_CONNECTIONS: int = 0\n\n\nclass SystemDSContext(object):\n \"\"\"A context with a connection to the java instance with which SystemDS operations are executed.\n If necessary this class might also start a java process which is used for the SystemDS operations,\n before connecting.\"\"\"\n _java_gateway: Optional[JavaGateway]\n\n def __init__(self):\n global PROCESS_LOCK\n global PROCESS\n global ACTIVE_PROCESS_CONNECTIONS\n # make sure that a process is only started if necessary and no other thread\n # is killing the process while the connection is established\n PROCESS_LOCK.acquire()\n try:\n # attempt connection to manually started java instance\n self._java_gateway = JavaGateway(eager_load=True)\n except Py4JNetworkError:\n # if no java instance is running start it\n systemds_java_path = os.path.join(get_module_dir(), 'systemds-java')\n cp_separator = ':'\n if os.name == 'nt': # nt means its Windows\n cp_separator = ';'\n lib_cp = os.path.join(systemds_java_path, 'lib', '*')\n systemds_cp = os.path.join(systemds_java_path, '*')\n classpath = cp_separator.join([lib_cp, systemds_cp])\n process = subprocess.Popen(['java', '-cp', classpath, 'org.apache.sysds.pythonapi.PythonDMLScript'],\n stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n process.stdout.readline() # wait for 'Gateway Server Started\\n' written by server\n assert process.poll() is None, \"Could not start JMLC server\"\n self._java_gateway = JavaGateway()\n PROCESS = process\n if PROCESS is not None:\n ACTIVE_PROCESS_CONNECTIONS += 1\n PROCESS_LOCK.release()\n\n @property\n def java_gateway(self):\n return self._java_gateway\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close()\n # no errors to handle to allow continuation\n return None\n\n def close(self):\n \"\"\"Close the connection to the java process and do necessary cleanup.\"\"\"\n\n global PROCESS_LOCK\n global PROCESS\n global ACTIVE_PROCESS_CONNECTIONS\n self._java_gateway.shutdown()\n PROCESS_LOCK.acquire()\n # check if no other thread is connected to the process, if it was started as a subprocess\n if PROCESS is not None and ACTIVE_PROCESS_CONNECTIONS == 1:\n # stop the process by sending a new line (it will shutdown on its own)\n PROCESS.communicate(input=b'\\n')\n PROCESS.wait()\n PROCESS = None\n ACTIVE_PROCESS_CONNECTIONS = 0\n PROCESS_LOCK.release()\n\n def matrix(self, mat: Union[np.array, os.PathLike], *args: Sequence[VALID_INPUT_TYPES],\n **kwargs: Dict[str, VALID_INPUT_TYPES]) -> 'Matrix':\n \"\"\" Create matrix.\n\n :param mat: Matrix given by numpy array or path to matrix file\n :param args: additional arguments\n :param kwargs: additional named arguments\n :return: the OperationNode representing this operation\n \"\"\"\n return Matrix(self, mat, *args, **kwargs)\n\n def federated(self, addresses: Iterable[str], ranges: Iterable[Tuple[Iterable[int], Iterable[int]]],\n *args: Sequence[VALID_INPUT_TYPES], **kwargs: Dict[str, VALID_INPUT_TYPES]) -> 'OperationNode':\n \"\"\"Create federated matrix object.\n \n :param addresses: addresses of the federated workers\n :param ranges: for each federated worker a pair of begin and end index of their held matrix\n :param args: unnamed params\n :param kwargs: named params\n :return: the OperationNode representing this operation\n \"\"\"\n return federated(self, addresses, ranges, *args, **kwargs)\n\n def full(self, shape: Tuple[int, int], value: Union[float, int]) -> 'OperationNode':\n \"\"\"Generates a matrix completely filled with a value\n\n :param shape: shape (rows and cols) of the matrix\n :param value: the value to fill all cells with\n :return: the OperationNode representing this operation\n \"\"\"\n return full(self, shape, value)\n\n def seq(self, start: Union[float, int], stop: Union[float, int] = None,\n step: Union[float, int] = 1) -> 'OperationNode':\n \"\"\"Create a single column vector with values from `start` to `stop` and an increment of `step`.\n If no stop is defined and only one parameter is given, then start will be 0 and the parameter will be\n interpreted as stop.\n\n :param start: the starting value\n :param stop: the maximum value\n :param step: the step size\n :return: the OperationNode representing this operation\n \"\"\"\n return seq(self, start, stop, step)\n\n def rand(self, rows: int, cols: int, min: Union[float, int] = None,\n max: Union[float, int] = None, pdf: str = \"uniform\",\n sparsity: Union[float, int] = None, seed: Union[float, int] = None,\n lambd: Union[float, int] = 1) -> OperationNode:\n \"\"\"Generates a matrix filled with random values\n\n :param rows: number of rows\n :param cols: number of cols\n :param min: min value for cells\n :param max: max value for cells\n :param pdf: \"uniform\"/\"normal\"/\"poison\" distribution\n :param sparsity: fraction of non-zero cells\n :param seed: random seed\n :param lambd: lamda value for \"poison\" distribution\n :return:\n \"\"\"\n available_pdfs = [\"uniform\", \"normal\", \"poisson\"]\n if rows < 0:\n raise ValueError(\"In rand statement, can only assign rows a long (integer) value >= 0 \"\n \"-- attempted to assign value: {r}\".format(r=rows))\n if cols < 0:\n raise ValueError(\"In rand statement, can only assign cols a long (integer) value >= 0 \"\n \"-- attempted to assign value: {c}\".format(c=cols))\n if pdf not in available_pdfs:\n raise ValueError(\"The pdf passed is invalid! given: {g}, expected: {e}\".format(g=pdf, e=available_pdfs))\n\n return rand(self, rows, cols, min, max, pdf, sparsity, seed, lambd)","sub_path":"src/main/python/systemds/context/systemds_context.py","file_name":"systemds_context.py","file_ext":"py","file_size_in_byte":7746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"84340139","text":"#!/usr/bin/env python\n#coding=utf-8\nfrom django.http import HttpResponse\nfrom blog.models import OptionSet\nimport random,cStringIO\nfrom PIL import Image, ImageDraw, ImageFont, ImageFilter\n\nfrom settings import CAPTCHA_FONT\n\n_letter_cases = \"abcdefghjkmnpqrstuvwxy\" # 小写字母,去除可能干扰的i,l,o,z\n_upper_cases = _letter_cases.upper() # 大写字母\n_numbers = ''.join(map(str, range(3, 10))) # 数字\ninit_chars = ''.join((_letter_cases, _upper_cases, _numbers))\n \ndef create_validate_code(size=(80, 20),\n chars=init_chars,\n img_type=\"GIF\",\n mode=\"RGB\",\n bg_color=(255, 255, 255),\n fg_color=(0, 0, 255),\n font_size=18,\n font_type=CAPTCHA_FONT,\n length=4,\n draw_lines=True,\n n_line=(1, 2),\n draw_points=True,\n point_chance = 2):\n\n width, height = size # 宽, 高\n img = Image.new(mode, size, bg_color) # 创建图形\n draw = ImageDraw.Draw(img) # 创建画笔\n \n def get_chars():\n '''生成给定长度的字符串,返回列表格式'''\n return random.sample(chars, length)\n \n def create_lines():\n '''绘制干扰线'''\n line_num = random.randint(*n_line) # 干扰线条数\n \n for i in range(line_num):\n # 起始点\n begin = (random.randint(0, size[0]), random.randint(0, size[1]))\n #结束点\n end = (random.randint(0, size[0]), random.randint(0, size[1]))\n draw.line([begin, end], fill=(0, 0, 0))\n \n def create_points():\n '''绘制干扰点'''\n chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100]\n \n for w in xrange(width):\n for h in xrange(height):\n tmp = random.randint(0, 100)\n if tmp > 100 - chance:\n draw.point((w, h), fill=(0, 0, 0))\n \n def create_strs():\n '''绘制验证码字符'''\n c_chars = get_chars()\n strs = ' %s ' % ' '.join(c_chars) # 每个字符前后以空格隔开\n font = ImageFont.truetype(font_type, font_size)\n draw.text((0,0),strs, font=font, fill=fg_color)\n return ''.join(c_chars)\n \n def draw_arithmetic():\n font = ImageFont.truetype(font_type, font_size)\n first=random.randint(1,10)\n second=random.randint(2,12)\n draw.text((0,0), str(first)+'+'+str(second),font=font,fill=(100,211, 90))\n return first+second\n \n if draw_lines:\n create_lines()\n if draw_points:\n create_points()\n tp=OptionSet.get('safecode_type', 1);\n if tp == str(1):\n strs = create_strs()\n else:\n strs = draw_arithmetic()\n\n img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界加强(阈值更大)\n \n return img, strs\n\ndef validate(request):\n \n buf = cStringIO.StringIO()\n img,str = create_validate_code()\n img.save(buf, \"GIF\")\n \n request.session['safecode'] =str\n return HttpResponse(buf.getvalue(), \"image/gif\")","sub_path":"youflog/blog/views/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"220767280","text":"from setuptools import setup, find_packages\nimport os\nimport sys\n\nrequires = open(\"requirements.txt\").read().split(\"\\n\")\nreadme = open(\"README.rst\").read()\n\nsetup(\n name=\"azcat\",\n version=\"1.0.5\",\n description=\"A alternative to cat(1); specialized for printing files\",\n long_description=readme,\n author=\"Seiya Nuta\",\n author_email=\"nuta@seiya.me\",\n url=\"http://github.com/nuta/azcat\",\n packages=find_packages(),\n scripts=[\"az\"],\n install_requires=requires,\n classifiers = [\n \"Development Status :: 5 - Production/Stable\",\n \"Environment :: Console\",\n \"License :: Public Domain\",\n \"Operating System :: POSIX\",\n \"Topic :: Utilities\"\n ]\n)\n","sub_path":"pypi_install_script/azcat-1.0.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"502031251","text":"import re\n\nfrom walrus.walrus_creator.job import Job\nfrom walrus.pylib import pyudf\n\n\ndef make_job(taskinfo):\n return BaseJob(taskinfo)\n\n\nclass BaseJob(Job):\n\n \"\"\"\n Base type task.\n \"\"\"\n\n def __init__(self, taskinfo):\n super(BaseJob, self).__init__(taskinfo)\n self.check_task()\n self.parse_task()\n\n def check_task(self):\n \"\"\"\n Check the task info.\n \"\"\"\n d_job = self.parse_json(self.taskinfo['f_task_logic'])\n self.check_dict(d_job, ['begin_day', 'end_day'])\n if isinstance(d_job['begin_day'], list):\n if not isinstance(d_job['end_day'], list) or not isinstance(d_job['filter'], list) or len(d_job['begin_day']) != len(d_job['end_day']) or len(d_job['begin_day']) != len(d_job['filter']):\n raise Exception('Multi filter format error!')\n d_job['mflag'] = True\n else:\n d_job['begin_day'], d_job['end_day'] = self.check_days(\n d_job['begin_day'], d_job['end_day'])\n if 'filter' not in d_job or not d_job['filter']:\n d_job['filter'] = ''\n d_job['mflag'] = False\n if 'groupby' not in d_job or not d_job['groupby']:\n d_job['groupby'] = 'g_all'\n if 'metric' not in d_job or not d_job['metric']:\n d_job['metric'] = 'imp'\n if 'user' not in d_job or not d_job['user']:\n d_job['user'] = 'qq'\n if 'exts' not in d_job or not d_job['exts']:\n d_job['exts'] = {}\n self.d_job = d_job\n\n def check_freq(self, metrics):\n \"\"\"\n freq can only be calc with imp, uv\n \"\"\"\n m = ['freq', 'uv', 'imp']\n for n in metrics:\n if n not in m:\n raise Exception('freq can not be calc with %s!' % n)\n\n def parse_task(self):\n if not self.d_job['mflag']:\n filters, sfilters = self.handle_filter(\n self.taskinfo['f_data_src'], self.d_job['filter'])\n cal_days = [(self.d_job['begin_day'], self.d_job['end_day'])]\n else:\n filters = ['date']\n sfilters = []\n cal_days = []\n for i in xrange(len(self.d_job['filter'])):\n f, f_str = self.handle_filter(\n self.taskinfo['f_data_src'], self.d_job['filter'][i])\n filters.extend(f)\n f_str = \"(%s) and date >= '%s' and date <= '%s'\" % (\n f_str, self.d_job['begin_day'][i], self.d_job['end_day'][i])\n sfilters.append(f_str)\n cal_days.append(\n (self.d_job['begin_day'][i], self.d_job['end_day'][i]))\n groupbys = self.get_field_list(self.d_job['groupby'])\n metrics = self.get_field_list(self.d_job['metric'])\n if 'freq' in metrics:\n self.check_freq(metrics)\n user = self.d_job['user']\n need_fields = list(set(filters + groupbys + [user]))\n self.d_parsed = {\n \"s_filter\": sfilters,\n \"filters\": filters,\n \"groupbys\": groupbys,\n \"metrics\": metrics,\n \"user\": user,\n \"mflag\": self.d_job['mflag']\n }\n self.PIG, self.checklist = self.make_base_code(\n self.taskinfo['f_data_src'], need_fields, metrics=metrics, cal_days=cal_days, exts=self.d_job['exts'])\n\n def make_code(self):\n if 'freq' in self.d_parsed['metrics']:\n self.make_freq_code()\n else:\n self.make_puv_code()\n return self.set_return_dict(self.PIG, self.result_desc, self.hadoop_url, self.checklist)\n\n def make_freq_code(self):\n '''\n --metric freq can only be calc by view.\n\n f_view = filter view by *;\n a = group f_view by (groupby, user);\n b = foreach a generate flatten(group) as XXX, SUM(f_view.count) as freq;\n c = group b by (groupby, freq);\n result = foreach c generate flatten(group) as XXX, COUNT_STAR(b) as uv;\n\n store result into XXX;\n '''\n data_src = self.taskinfo['f_data_src'].replace('_click', '')\n groupbys = self.d_parsed['groupbys']\n user = self.d_parsed['user']\n if user in groupbys:\n s_groupby_user = \", \".join(groupbys)\n else:\n s_groupby_user = \", \".join(groupbys) + \", %s\" % user\n s_groupby = \", \".join(groupbys)\n s_filter = self.d_parsed['s_filter']\n if self.d_parsed['mflag']:\n pig_filter = \"\"\n u_filter = []\n for i in xrange(len(s_filter)):\n pig_filter += \"f_view_%d = filter %s by %s;\\n\" % (\n i, data_src, s_filter[i])\n u_filter.append(\"f_view_%d\" % i)\n pig_filter += \"f_view = union %s;\\n\\n\" % ', '.join(u_filter)\n else:\n pig_filter = \"f_view = filter %s by %s;\\n\\n\" % (data_src, s_filter)\n\n self.PIG += (\"%(pig_filter)s\"\n \"a = group f_view by (%(s_groupby_user)s);\\n\"\n \"b = foreach a generate flatten(group) as(%(s_groupby_user)s), SUM(f_view.count) as freq;\\n\"\n \"c = group b by (%(s_groupby)s, freq);\\n\"\n \"result = foreach c generate flatten(group) as(%(s_groupby)s, freq), COUNT_STAR(b.%(s_user_flag)s) as uv;\\n\\n\"\n \"store result into '%(s_hadoop)s';\\n\\n\"\n % {\n 'pig_filter': pig_filter,\n 's_groupby_user': s_groupby_user,\n 's_groupby': s_groupby,\n 's_hadoop': self.hadoop_url,\n 's_user_flag': user\n }\n )\n self.result_desc = ','.join(groupbys) + '-' + 'freq,uv'\n\n def make_puv_code(self):\n view_flag = False\n click_flag = False\n if 'income' in self.d_parsed['metrics']:\n view_flag = True\n # add money:double\n self.make_income_code()\n if 'tp1_imp' in self.d_parsed['metrics']:\n view_flag = True\n # add count_tp1:int\n self.make_tp1_code()\n if 'imp' in self.d_parsed['metrics'] or 'uv' in self.d_parsed['metrics']:\n view_flag = True\n if 'click' in self.d_parsed['metrics'] or 'click_uv' in self.d_parsed['metrics']:\n click_flag = True\n if not view_flag and not click_flag:\n raise Exception('Nothing to calc!')\n if view_flag:\n self.make_view_code()\n if click_flag:\n self.make_click_code()\n if view_flag and click_flag:\n self.join_view_click()\n else:\n if view_flag:\n self.PIG += \"store view into '%s';\\n\\n\" % self.hadoop_url\n else:\n self.PIG += \"store click into '%s';\\n\\n\" % self.hadoop_url\n\n def make_tp1_code(self):\n '''\n video_view = foreach video_view generate *, (tp_index == 1 ? count : 0) as count_tp1:int;\n '''\n self.PIG += 'video_view = foreach video_view generate *, (tp_index == 1 ? count : 0) as count_tp1:int;\\n\\n'\n\n def make_income_code(self):\n '''\n split video_view into view_90 if oid==90, view_not_90 if oid!=90;\n m = foreach view_90 generate *, 0 as money:double;\n i = group view_not_90 by (date, loc_code, oid);\n j = foreach i generate flatten(view_not_90), SUM(view_not_90.count) as pv_all;\n\n a = load '/user/AD/qqlive/conf/oid_daily_money_yyyymmdd.cfg' as (day_money:chararray, loc_code_money:int, oid_money:int, money:double);\n b = filter a by (day_money >= begin_day and day_money <= end_day and oid_money != 0 and oid_money != 90 and money != 0);\n c = join j by (date, loc_code, oid) left, b by (day_money, loc_code_money, oid_money);\n n = foreach c generate view_generate, money/pv_all as money:double;\n video_view = union m, n;\n '''\n p = re.compile(r'video_view = load .+;')\n m = re.search(p, self.PIG)\n begin_day = self.d_job['begin_day']\n end_day = self.d_job['end_day']\n if isinstance(begin_day, list):\n begin_day = sorted(begin_day)[0]\n end_day = sorted(end_day)[-1]\n p = re.compile(r'\\s+video_view = foreach \\w+ generate .+;')\n m = re.search(p, self.PIG)\n s_view_ge = m.group(0).split('generate')[1].replace(\";\", \"\").strip()\n s_view_ge = re.sub(r'\\([^)]*\\)', \"\", s_view_ge)\n sTemp = s_view_ge.split(', ')\n for i in xrange(len(sTemp)):\n if ' as ' in sTemp[i]:\n sTemp[i] = sTemp[i].split(':')[0].split(' as ')[1].strip()\n s_view_ge = \", \".join(sTemp)\n yesterday = pyudf.get_yesterday()\n url = '/user/AD/qqlive/conf/oid_daily_money_%s.cfg' % yesterday\n self.checklist.append(url)\n self.PIG += (\"split video_view into view_90 if oid==90, view_not_90 if oid!=90;\\n\"\n \"m = foreach view_90 generate *, 0 as money:double;\\n\"\n \"i = group view_not_90 by (date, loc_code, oid);\\n\"\n \"j = foreach i generate flatten(view_not_90), SUM(view_not_90.count) as pv_all;\\n\\n\"\n \"a = load '/user/AD/qqlive/conf/oid_daily_money_%(yesterday)s.cfg' as (day_money:chararray, loc_code_money:int, oid_money:int, money:double);\\n\"\n \"b = filter a by (day_money >= '%(begin_day)s' and day_money <= '%(end_day)s' and oid_money != 0 and oid_money != 90 and money != 0);\\n\"\n \"c = join j by (date, loc_code, oid) left, b by (day_money, loc_code_money, oid_money);\\n\"\n \"n = foreach c generate %(s_view_ge)s, money/pv_all as money:double;\\n\"\n \"video_view = union m, n;\\n\\n\"\n % {\n \"yesterday\": yesterday,\n \"begin_day\": begin_day,\n \"end_day\": end_day,\n \"s_view_ge\": s_view_ge\n }\n )\n\n def join_view_click(self):\n '''\n join_view_click = join view by (groupby) left, click by (groupby);\n result = foreach join_view_click generate b_group..e_group, tp1_imp, imp, uv, income, click, uv_click;\n store result into '/user/AD/walrus/base/ip_id';\n '''\n groupbys = self.d_parsed['groupbys']\n metrics = self.d_parsed['metrics']\n self.result_desc = ','.join(groupbys) + '-' + ','.join(metrics)\n s_groupby = \", \".join(groupbys)\n s_metric = \", \".join(metrics)\n s_view_groupby = \"$0..$%d\" % (len(groupbys) - 1)\n self.PIG += (\"join_view_click = join view by (%(s_groupby)s) left, click by (%(s_groupby)s);\\n\"\n \"result = foreach join_view_click generate %(s_view_groupby)s, %(s_metric)s;\\n\"\n \"store result into '%(s_r_url)s';\\n\\n\"\n % {\n 's_groupby': s_groupby,\n 's_view_groupby': s_view_groupby,\n 's_metric': s_metric,\n 's_r_url': self.hadoop_url\n })\n\n def make_view_code(self):\n '''\n tp1_imp, imp, uv, income\n\n f_view = filter view by XXX;\n a = group f_view by (groupby, user);\n b = foreach a generate flatten(group) as ..., SUM(f_view.count_tp1) as tp1_imp, SUM(f_view.count) as imp, SUM(f_view.money) as income;\n c = group b by (groupby);\n view = foreach c generate flatten(group) as ..., SUM(b.tp1_imp) as tp1_imp, SUM(b.imp) as imp, COUNT_STAR(b) as uv, SUM(b.income) as income;\n '''\n data_src = self.taskinfo['f_data_src'].replace('_click', '')\n metrics = self.d_parsed['metrics']\n groupbys = self.d_parsed['groupbys']\n result_m = []\n user = self.d_parsed['user']\n if user in groupbys:\n s_groupby_user = \", \".join(groupbys)\n else:\n s_groupby_user = \", \".join(groupbys) + \", %s\" % user\n s_groupby = \", \".join(groupbys)\n s_filter = self.d_parsed['s_filter']\n s_g_1 = \"\"\n s_g_2 = \"\"\n if 'tp1_imp' in metrics:\n s_g_1 += ', SUM(f_view.count_tp1) as tp1_imp'\n s_g_2 += ', SUM(b.tp1_imp) as tp1_imp'\n result_m.append('tp1_imp')\n if 'imp' in metrics:\n s_g_1 += ', SUM(f_view.count) as imp'\n s_g_2 += ', SUM(b.imp) as imp'\n result_m.append('imp')\n if 'uv' in metrics:\n s_g_2 += ', COUNT_STAR(b.%s) as uv' % user\n result_m.append('uv')\n if 'income' in metrics:\n s_g_1 += ', SUM(f_view.money) as income'\n s_g_2 += ', SUM(b.income) as income'\n result_m.append('income')\n\n if self.d_parsed['mflag']:\n pig_filter = \"\"\n u_filter = []\n for i in xrange(len(s_filter)):\n pig_filter += \"f_view_%d = filter %s by %s;\\n\" % (\n i, data_src, s_filter[i])\n u_filter.append(\"f_view_%d\" % i)\n pig_filter += \"f_view = union %s;\\n\\n\" % ', '.join(u_filter)\n else:\n pig_filter = \"f_view = filter %s by %s;\\n\\n\" % (data_src, s_filter)\n\n self.PIG += (\"%(pig_filter)s\"\n \"a = group f_view by (%(s_groupby_user)s);\\n\"\n \"b = foreach a generate flatten(group) as (%(s_groupby_user)s)%(s_g_1)s;\\n\"\n \"c = group b by (%(s_groupby)s);\\n\"\n \"view = foreach c generate flatten(group) as (%(s_groupby)s)%(s_g_2)s;\\n\\n\"\n % {\n 'pig_filter': pig_filter,\n 's_groupby_user': s_groupby_user,\n 's_groupby': s_groupby,\n 's_g_1': s_g_1,\n 's_g_2': s_g_2\n })\n self.result_desc = ','.join(groupbys) + '-' + ','.join(result_m)\n\n def make_click_code(self):\n '''\n click, uv_click\n\n f_click = filter click by ***;\n a = group f_click by (groupby, user);\n b = foreach a generate flatten(group) as ..., SUM(f_click.count) as click;\n c = group b by (groupby);\n click = foreach c generate flatten(group) as ..., SUM(b.click) as click, COUNT_STAR(b) as uv_click;\n '''\n data_src = self.taskinfo['f_data_src'].replace('_view', '')\n metrics = self.d_parsed['metrics']\n groupbys = self.d_parsed['groupbys']\n result_m = []\n user = self.d_parsed['user']\n if user in groupbys:\n s_groupby_user = \", \".join(groupbys)\n else:\n s_groupby_user = \", \".join(groupbys) + \", %s\" % user\n s_groupby = \", \".join(groupbys)\n s_filter = self.d_parsed['s_filter']\n s_g_1 = \"\"\n s_g_2 = \"\"\n if 'click' in metrics:\n s_g_1 += ', SUM(f_click.count) as click'\n s_g_2 += ', SUM(b.click) as click'\n result_m.append('click')\n if 'uv_click' in metrics:\n s_g_2 += ', COUNT_STAR(b.%s) as uv_click' % self.user_flag\n result_m.append('uv_click')\n\n if self.d_parsed['mflag']:\n pig_filter = \"\"\n u_filter = []\n for i in xrange(len(s_filter)):\n pig_filter += \"f_click_%d = filter %s by %s;\\n\" % (\n i, data_src, s_filter[i])\n u_filter.append(\"f_click_%d\" % i)\n pig_filter += \"f_click = union %s;\\n\\n\" % ', '.join(u_filter)\n else:\n pig_filter = \"f_click = filter %s by %s;\\n\\n\" % (\n data_src, s_filter)\n\n self.PIG += (\"%(pig_filter)s\"\n \"a = group f_click by (%(s_groupby_user)s);\\n\"\n \"b = foreach a generate flatten(group) as(%(s_groupby_user)s)%(s_g_1)s;\\n\"\n \"c = group b by (%(s_groupby)s);\\n\"\n \"click = foreach c generate flatten(group) as (%(s_groupby)s)%(s_g_2)s;\\n\\n\"\n % {\n 'pig_filter': pig_filter,\n 's_groupby_user': s_groupby_user,\n 's_groupby': s_groupby,\n 's_g_1': s_g_1,\n 's_g_2': s_g_2\n })\n self.result_desc = ','.join(groupbys) + '-' + ','.join(result_m)\n","sub_path":"walrus/walrus_creator/base_job.py","file_name":"base_job.py","file_ext":"py","file_size_in_byte":16315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"134993626","text":"import os\nimport shutil\nimport sys\nfrom invoke import task\n\n\nDEFAULT_DOCKER_IMAGE = 'orbin/gramhopper'\nDEFAULT_DOCKER_TAG = 'latest'\nDOCKER_IMAGE_ENV_VARIABLE = 'DOCKER_IMAGE_TAG'\nTASK_SUCCESS_CODE = 0\nTASK_FAILURE_CODE = 1\nSUCCESS_COLOR = '\\033[92m'\nFAILURE_COLOR = '\\033[91m'\nDEFAULT_COLOR = '\\033[39m'\n\n\n@task\ndef build(context, package=True, docker_image=True, docker_tag=DEFAULT_DOCKER_TAG, docs=False):\n if package:\n print('Building package...')\n context.run('python setup.py sdist bdist_wheel', echo=True)\n\n if docker_image:\n print('Building docker image...')\n\n # If not specified the tag as a flag, the tag from the environment variable is preferred\n if docker_tag == DEFAULT_DOCKER_TAG and \\\n DOCKER_IMAGE_ENV_VARIABLE in os.environ:\n docker_tag = os.environ[DOCKER_IMAGE_ENV_VARIABLE]\n\n context.run(f'docker build -t {DEFAULT_DOCKER_IMAGE}:{docker_tag} .', echo=True)\n\n if docs:\n build_docs(context)\n\n\n@task\ndef build_docs(context):\n print('Building docs...')\n with context.cd('docs'):\n context.run('make html', echo=True)\n\n\n@task\ndef lint(context):\n source_code_dirs = './*.py ./gramhopper'\n test_code_dirs = './tests'\n exit_code = TASK_SUCCESS_CODE\n\n print('Running pylint on source code...')\n result = context.run(f'pylint {source_code_dirs}', warn=True, echo=True)\n if not result.exited == TASK_SUCCESS_CODE:\n exit_code = TASK_FAILURE_CODE\n\n print('Running pylint on test code...')\n result = context.run(f'pylint --rcfile=./tests/tests.pylintrc {test_code_dirs}',\n warn=True,\n echo=True)\n if not result.exited == TASK_SUCCESS_CODE:\n exit_code = TASK_FAILURE_CODE\n\n print('Running flake8...')\n result = context.run('flake8 --exclude=venv', warn=True, echo=True)\n if not result.exited == TASK_SUCCESS_CODE:\n exit_code = TASK_FAILURE_CODE\n\n print('Running pytype...')\n python_version = f'{sys.version_info.major}.{sys.version_info.minor}'\n cmd = f'pytype --config ./setup.cfg -V {python_version} {source_code_dirs} {test_code_dirs}'\n result = context.run(cmd, warn=True, echo=True)\n if not result.exited == TASK_SUCCESS_CODE:\n exit_code = TASK_FAILURE_CODE\n\n message_color = SUCCESS_COLOR if exit_code == TASK_SUCCESS_CODE else FAILURE_COLOR\n status_string = 'successfully' if exit_code == TASK_SUCCESS_CODE else 'with errors'\n\n finished_string = f'{message_color}Lint task finished {status_string} {DEFAULT_COLOR}'\n print(finished_string)\n sys.exit(exit_code)\n\n\n@task\ndef test(context):\n gramhopper_dir = os.path.join(os.path.expanduser('~'), '.gramhopper')\n gramhopper_backup_dir = os.path.join(os.path.expanduser('~'), '.gramhopper_bak')\n\n if os.path.exists(gramhopper_dir):\n print('Backing up configuration directory...')\n shutil.copytree(gramhopper_dir, gramhopper_backup_dir)\n\n print('Copying test assets...')\n shutil.rmtree(gramhopper_dir, ignore_errors=True)\n shutil.copytree('./tests/assets/.gramhopper', gramhopper_dir)\n\n print('Running tests...')\n context.run('pytest', echo=True)\n\n print('Removing test assets...')\n shutil.rmtree(gramhopper_dir)\n\n if os.path.exists(gramhopper_backup_dir):\n print('Restoring configuration directory...')\n shutil.copytree(gramhopper_backup_dir, gramhopper_dir)\n shutil.rmtree(gramhopper_backup_dir)\n\n\n@task\ndef publish(context, docker_tag=None, docker_latest=False, production_pypi=False, skip_pypi=False):\n if not skip_pypi:\n pypi_type = 'production' if production_pypi else 'test'\n print(f'Uploading package to {pypi_type} PyPI...')\n repo_url_flag = '' if production_pypi else '--repository-url https://test.pypi.org/legacy/'\n context.run(f'twine upload {repo_url_flag} dist/*', echo=True)\n\n if docker_tag:\n publish_docker_image(context, f'{DEFAULT_DOCKER_IMAGE}:{docker_tag}')\n\n if docker_latest:\n publish_docker_image(context, f'{DEFAULT_DOCKER_IMAGE}:latest')\n\n\ndef publish_docker_image(context, full_image_name):\n print(f'Uploading docker image {full_image_name} to PyPI...')\n context.run(f'docker push {full_image_name}', echo=True)\n\n\n@task\ndef clean(context, # pylint: disable=too-many-arguments\n package=False,\n docker=False,\n docs=False,\n lint=False, # pylint: disable=redefined-outer-name\n test=False, # pylint: disable=redefined-outer-name\n all=False): # pylint: disable=redefined-builtin\n\n if all:\n package = True\n docker = True\n docs = True\n lint = True\n test = True\n elif not any([package, docker, docs, lint, test]):\n # If no flag was specified, exit with an error\n print('Specified nothing to clean', file=sys.stderr)\n sys.exit(TASK_FAILURE_CODE)\n\n if package:\n print('Removing package build outputs...')\n clean_package()\n\n if docker:\n print('Removing docker images...')\n clean_docker(context)\n\n if docs:\n print('Removing docs build outputs...')\n shutil.rmtree('./docs/build', ignore_errors=True)\n\n if lint:\n print('Removing lint outputs and cache files...')\n shutil.rmtree('./pytype_output', ignore_errors=True)\n shutil.rmtree('./.pytype', ignore_errors=True)\n\n if test:\n print('Removing test outputs and cache files...')\n shutil.rmtree('./.pytest_cache', ignore_errors=True)\n shutil.rmtree('./gramhopper_test.egg-info', ignore_errors=True)\n\n\ndef clean_package():\n shutil.rmtree('./build', ignore_errors=True)\n shutil.rmtree('./dist', ignore_errors=True)\n shutil.rmtree('./gramhopper.egg-info', ignore_errors=True)\n\n\ndef clean_docker(context):\n docker_result = context.run('docker', hide='both')\n # If docker is installed, remove both the image with the default tag and\n # the image with the tag from the environment variable\n if docker_result.exited == TASK_SUCCESS_CODE:\n tags_to_remove = [DEFAULT_DOCKER_IMAGE]\n if DOCKER_IMAGE_ENV_VARIABLE in os.environ:\n tags_to_remove.append(os.environ[DOCKER_IMAGE_ENV_VARIABLE])\n\n hashes_to_remove = []\n for tag in tags_to_remove:\n hash_result = context.run(f'docker images -q {tag}', hide='out')\n image_hash = hash_result.stdout.split('\\n')[0].strip()\n if image_hash:\n hashes_to_remove.append(image_hash)\n\n if hashes_to_remove:\n hashes_to_remove = ' '.join(set(hashes_to_remove))\n context.run(f'docker rmi -f {hashes_to_remove}', echo=True)\n else:\n print('No docker images to remove')\n else:\n print('Docker is not installed on this machine')\n","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"74667323","text":"str_seconds=input(\"enter the number of seconds to convert\")\ntotal_secs=int(str_seconds)\n\n#converting seconds to hrs min and secs\nhrs=total_secs//3600\nremaining_sec=total_secs%3600\nmin=remaining_sec//60\nsec=remaining_sec%60\n\nprint(\"hrs=%s min=%s sec=%s\" % (hrs,min,sec))\n","sub_path":"convert_Sec_to_hrsMinSec.py","file_name":"convert_Sec_to_hrsMinSec.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"429372464","text":"import os\nfrom src.language.Kotlin import extract_libraries\n\n\ndef test_extract_libraries():\n dir_path = os.path.dirname(os.path.realpath(__file__))\n files = ['fixtures/Kotlin.kt']\n fq_files = [os.path.join(dir_path, f) for f in files]\n libs = extract_libraries(fq_files)\n assert len(libs) == 1\n\n assert 'syntax.lexer.Token' in libs[\"Kotlin\"]\n assert 'syntax.tree' in libs[\"Kotlin\"]","sub_path":"test/test_Kotlin.py","file_name":"test_Kotlin.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"238556829","text":"file=open(\"B-small-attempt2.in\",\"r\")\nfile_out=open(\"B.out\",\"wr\")\n\ncase_n=file.readline()\n\nfor x in xrange(int(case_n)):\n case_id=x+1\n case_vn=int(file.readline())\n case_vn=2*case_vn-1\n count=0\n values=[]\n dict={}\n while count 0.1][drill_name]\n bootstrap_sample_means = []\n for _ in range(10000):\n bootstrap = np.random.choice(data, size=len(data), replace=True)\n bootstrap_mean = np.mean(bootstrap)\n bootstrap_sample_means.append(bootstrap_mean)\n left_endpoint = np.percentile(bootstrap_sample_means, 2.5)\n right_endpoint = np.percentile(bootstrap_sample_means, 97.5)\n return left_endpoint, right_endpoint\n\n\ndef fit_plot(drill_name, axes, dist, name):\n '''\n Plots the histogram of a combine drill's data and fits a distribution\n using the MLE method, all on the passed-in axes.\n ----------\n Parameters\n ----------\n drill_name: str\n A string matching one of the six combine drills' names.\n axes: matplotlib axes subplot\n A matplotlib axes subplot for the histogram and fit distribution\n to be plotted on.\n dist: scipy.stats distribution (ex: stats.norm)\n A distribution to be used as a model to create a fit for the data.\n name: str\n A string to be used as the plot title\n ----------\n Returns \n ----------\n None\n ''' \n data = joined[joined[drill_name] > 0.1][drill_name]\n n = len(data)\n mu = np.mean(data)\n s = np.std(data, ddof=1)\n x = np.linspace(mu - 4* s, mu + 4*s, 1000) \n hist = axes.hist(data, bins=50, color='b', density=True, \n label='original data', alpha=0.5, zorder=5) \n fit_mu, fit_s = dist.fit(data)\n cont_pdf = axes.plot(x, dist.pdf(x, fit_mu, fit_s),\n color='r', label='fit', zorder=10)\n axes.set_title(name)\n\n\ndef quartiles(df, category, q_divs):\n '''\n Computes the four quartile DataFrames from the passed-in DF.\n ----------\n Parameters\n ----------\n df: Pandas DataFrame\n A DataFrame to split into 4 quartiles.\n category: str\n A string containing the column name that you wish to use to split\n the DataFrame into 4 quartiles\n q_divs: list\n A list of three floats which are the 25th percentile, Median, and \n 75th percentile of the column's data, which will be used to split\n the Dataframe \n ----------\n Returns \n ----------\n A tuple of 4 DataFrames\n ''' \n w_q1 = df[df[category] <= q_divs[0]]\n w_q2 = df[(df[category] > q_divs[0]) & (df[category] <= q_divs[1])]\n w_q3 = df[(df[category] > q_divs[1]) & (df[category] <= q_divs[2])]\n w_q4 = df[df[category] > q_divs[2]]\n return w_q1, w_q2, w_q3, w_q4\n\n\ndef combined_norm_fits(drill_name, axes, name):\n '''\n Splits the combine drill's data into four DataFrames, the four quartiles\n of the performing players' weights. Next, it fits a normal distribution to\n each quartile's data. Finally, it averages the four fits for each point in\n the x array and plots the combined fit over a histogram of the drill's data.\n ----------\n Parameters\n ----------\n drill_name: str\n A string matching one of the six combine drills' names.\n axes: matplotlib axes subplot\n A matplotlib axes subplot for the histogram and fit distribution\n to be plotted on.\n name: str\n A string to be used as the plot title\n print: bool\n A boolean value to print the normal fits' loc/shape\n ----------\n Returns \n ----------\n None\n '''\n temp = joined[joined[drill_name] > 0.1]\n q_divs = [temp['Weight (lbs)'].describe()[j] for j in [4, 5, 6]]\n w_qs = quartiles(temp, 'Weight (lbs)', q_divs)\n q = ['q1', 'q2', 'q3', 'q4']\n mean, std = temp[drill_name].mean(), temp[drill_name].std()\n mu = {}\n s = {}\n for i, w in enumerate(w_qs):\n data = w[w[drill_name] > 0.1][drill_name]\n mu[q[i]], s[q[i]] = stats.norm.fit(data)\n print(drill_name, q[i], mu[q[i]], s[q[i]])\n x = np.linspace(mean - 4* std, mean + 4*std, 1000)\n y = (stats.norm.pdf(x, mu[q[0]], s[q[0]]) + stats.norm.pdf(x, mu[q[1]], s[q[1]]) \n + stats.norm.pdf(x, mu[q[2]], s[q[2]]) + stats.norm.pdf(x, mu[q[3]], s[q[3]]))/4\n hist = axes.hist(temp[drill_name], bins=50, color='b', density=True, \n label='original data', alpha=0.5, zorder=5)\n cont_pdf = axes.plot(x, y, color='r', label='fit', zorder=10)\n axes.set_title(name)\n\n\ndef plot_hist(drill_name, axes):\n '''\n Plots the data from the combine drill as a histogram on the \n passed-in axes.\n ----------\n Parameters\n ----------\n drill_name: str\n A string matching one of the six combine drills' names.\n axes: matplotlib axes subplot\n A matplotlib axes subplot for the histogram and fit distribution\n to be plotted on.\n ----------\n Returns \n ----------\n None\n ''' \n data = joined[joined[drill_name] > 0.1][drill_name]\n hist = axes.hist(data, bins=50, color='b', alpha=0.5, label='original data')\n n, mu, s= len(data), np.mean(data), np.std(data, ddof=1)\n title = axes.set_title(label=(drill_name + '\\n n={}, '.format(n) + \n r'$\\bar X$={:2.2f}, s= {:2.2f}'.format(mu, s)))\n\n\n# Plot the data from each drill as a histogram on it's own subplot.\nfig, axs = plt.subplots(2, 3, figsize=(15,8))\naxs_f = axs.flatten()\nfor ind, ax in enumerate(axs_f):\n plot_hist(drills[ind], ax)\nfig.tight_layout()\nplt.savefig('images/drill_data_dist.png')\n\n\n# Bootstrapping 10000 samples for each drill and calculating 95% CI\nfor drill in drills:\n lower, upper = bootstrap_95_ci(drill)\n print('Based on 10,000 bootstrapped samples, the 95% CI for the {} is [{:2.2f}, {:2.2f}]'\n .format(short_name[drill], lower, upper))\n\n\n# Plotting the three drills which have skewed data as a histogram on a subpllot beside\n# the weight of the participants as a histogram, beside a scatter plot highliting any\n# correlation between the drill data and the player's weights. Also, plots a fit line \n# to the scatter plot data using the method of least squares.\nfig, axs = plt.subplots(3, 3, figsize=(15,10))\nindex = [0, 4, 5]\nfor i in [0, 1, 2]:\n data = joined[['Weight (lbs)', drills[index[i]]]].dropna()\n array = data.to_numpy()\n m, b = np.polyfit(array[:,0], array[:,1], 1)\n forty = data.hist(drills[index[i]], bins=50 ,color='b', \n ax=axs[i,0], label=drills[index[i]], alpha=0.5)\n w = data.hist('Weight (lbs)', bins=50, color='r', \n ax=axs[i,1], label='Weight (lbs)', alpha=0.5)\n fit = axs[i, 2].plot(array[:,0], m*array[:,0]+b)\n scat = joined.plot.scatter('Weight (lbs)', drills[index[i]], alpha=0.75, \n color='g', ax=axs[i,2], title= drills[index[i]] + ' vs Weight (lbs)')\nfig.tight_layout()\nplt.savefig('images/skewed_drills.png')\n\n\n# Creating a plot with a normal distribution fit for each weight quartile of the\n# 40-yard dash participants to highlight the location of each weight class's \n# 40-yard dash times. \nfig, ax = plt.subplots()\nx = np.linspace(4, 6.5, 1000)\ntemp = joined[joined[drills[0]] > 0.1]\nq_divs = [temp['Weight (lbs)'].describe()[j] for j in [4, 5, 6]]\nw_qs = quartiles(temp, 'Weight (lbs)', q_divs)\nq = ['q1', 'q2', 'q3', 'q4']\nmu = {}\ns = {}\nfor i, w in enumerate(w_qs):\n data = w[w[drills[0]] > 0.1][drills[0]]\n mu[q[i]], s[q[i]] = stats.norm.fit(data)\n cont_pdf = ax.plot(x, stats.norm.pdf(x, mu[q[i]], s[q[i]]), label=q[i], zorder=10)\nplot = ax.set_title('40 Yard Dash: Fit Normal Distributions\\n by Weight Quartiles')\nleg = ax.legend()\nplt.savefig('images/fits_by_wq.png')\n\n\n# Creating a plot comparing the 40-yard dash data with three different distribution\n# fits: Normal, Gumbel, and average of the four quartile's fit distributions.\nfig, axs = plt.subplots(1,3, figsize=(18,4))\nax = axs.flatten()\nfit_plot(drills[0], ax[0], stats.norm, '40 Yard Dash: Normal Fit')\nfit_plot(drills[0], ax[1], stats.gumbel_r, '40 Yard Dash: Gumbel Fit')\ncombined_norm_fits(drills[0], ax[2], '40 Yard Dash: Avg of Weight Quartile Fits')\nplt.savefig('images/fit_comparison.png')\n\n\n# Generate and Save the Drills Data Distribution Fits as image (using the average fit method)\nfig, axs = plt.subplots(2, 3, figsize=(15,8))\naxs_f = axs.flatten()\nfor ind, ax in enumerate(axs_f):\n data = joined[joined[drills[ind]] > 0.1][drills[ind]]\n n, mu, s= len(data), np.mean(data), np.std(data, ddof=1)\n title = (drills[ind] + '\\n n={}, '.format(n) + \n r'$\\bar X$={:2.2f}, s= {:2.2f}'.format(mu, s))\n combined_norm_fits(drills[ind], ax, title)\nfig.tight_layout()\nplt.savefig('images/drill_data_dist_fits.png')","sub_path":"src/data_distributions.py","file_name":"data_distributions.py","file_ext":"py","file_size_in_byte":9096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"394043714","text":"from stacktach import utils\nfrom stacktach import image_type\n\n\nclass Notification(object):\n def __init__(self, body):\n self.body = body\n self.request_id = body['_context_request_id']\n self.payload = body.get('payload', {})\n self.state = self.payload.get('state', \"\")\n self.old_state = self.payload.get('old_state', \"\")\n self.old_task = self.payload.get('old_task_state', \"\")\n self.task = self.payload.get('new_task_state', \"\")\n self.image_type = image_type.get_numeric_code(self.payload)\n self.publisher = self.body['publisher_id']\n self.event = self.body['event_type']\n image_meta = self.payload.get('image_meta', {})\n self.os_architecture = image_meta.get('org.openstack__1__architecture',\n '')\n self.os_distro = image_meta.get('org.openstack__1__os_distro', '')\n self.os_version = image_meta.get('org.openstack__1__os_version', '')\n self.rax_options = image_meta.get('com.rackspace__1__options', '')\n\n @property\n def when(self):\n when = self.body.get('timestamp', None)\n if not when:\n when = self.body['_context_timestamp'] # Old way of doing it\n when = utils.str_time_to_unix(when)\n return when\n\n def rawdata_kwargs(self, deployment, routing_key, json):\n return {\n 'deployment': deployment,\n 'routing_key': routing_key,\n 'event': self.event,\n 'publisher': self.publisher,\n 'json': json,\n 'state': self.state,\n 'old_state': self.old_state,\n 'task': self.task,\n 'old_task': self.old_task,\n 'image_type': self.image_type,\n 'when': self.when,\n 'publisher': self.publisher,\n 'service': self.service,\n 'host': self.host,\n 'instance': self.instance,\n 'request_id': self.request_id,\n 'tenant': self.tenant,\n 'os_architecture': self.os_architecture,\n 'os_distro': self.os_distro,\n 'os_version': self.os_version,\n 'rax_options': self.rax_options\n }\n\n @property\n def instance(self):\n # instance UUID's seem to hide in a lot of odd places.\n instance = self.payload.get('instance_id', None)\n instance = self.payload.get('instance_uuid', instance)\n if not instance:\n instance = self.payload.get('exception', {}).get('kwargs', {}).get('uuid')\n if not instance:\n instance = self.payload.get('instance', {}).get('uuid')\n return instance\n\n @property\n def host(self):\n host = None\n parts = self.publisher.split('.')\n if len(parts) > 1:\n host = \".\".join(parts[1:])\n return host\n\n @property\n def service(self):\n parts = self.publisher.split('.')\n return parts[0]\n\n @property\n def tenant(self):\n tenant = self.body.get('_context_project_id', None)\n tenant = self.payload.get('tenant_id', tenant)\n return tenant\n","sub_path":"stacktach/notification.py","file_name":"notification.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"571868690","text":"\n# coding: utf-8\n\n# In[ ]:\n\n################################################This is the data management hub for the chronic imaging work.\n\n\n# In[1]:\n\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom scipy import misc \nfrom scipy import ndimage\nfrom scipy import signal\nimport re \nimport os\nfrom skimage import transform as tf\nimport numpy as np\nimport Image\nimport pickle\nimport sys\nimport scipy\nimport generalFunctions as gef\nimport random\nfrom scipy.signal import savgol_filter\nfrom scipy import stats\nfrom pandas import DataFrame as dataFrame\nimport pandas as pd\n#import analysis_dataGrouping as dg\n#import analysis_visualisation as av\n#import analysis_reachFunctions as arf\n#import analysis_dFFFunctions as dfff\nimport tifffile as tff\nimport copy as cp\n\nimport image_registration as imr\nimport jpImageFunctions as jpi\nfrom jpImageFunctions import regImage\nimport generalFunctions as gef\ninIpython=0\n\nif (inIpython==1):\n get_ipython().magic(u'matplotlib inline')\n #matplotlib.style.use('ggplot')\n #matplotlib.rcParams.update(mpl.rcParamsDefault)\n font = {'family' : 'normal',\n 'weight' : 'bold',\n 'size' : 22}\n\n matplotlib.rc('font', **font)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[2]:\n\n####CONFIGS\n####Make this easily scalable to multiple mice? how much harder will this be to add in later?\ndataFolder = 'data/chronicImaging/'\nmiceToLoad = ['MTHL054'] ###all the mice that you want to process.\n\n#exclusion capability should come in somewhat later.\n\n\n# In[5]:\n\n###########Find relevant sessions\n#do this for all mice?\n\nmouseSessions = {} #mouse sessions holds the relevant folders for each session for each mouse.\nfor mouseId in range(len(miceToLoad)):\n files = os.listdir(dataFolder+miceToLoad[mouseId])\n files = sorted(files)\n print(files)\n \n matchPattern = '[A-Z]{1,4}[0-9]{1,3}_S[0-9]{1,3}_F[0-9]{1,3}' ##the outline for acceptable files [A-D]{1-4}_\n mouseSessions[mouseId] = [elem for elem in files if re.search(matchPattern, elem) != None]\n\n\n# In[23]:\n\n#####################################What is the next process?\n\n\n\n \n\n\n# In[3]:\n\n#prototyping produceMeanStack\nproduceStack=0\nif (produceStack ==1):\n for mouseId in range(len(miceToLoad)):\n numSessions = len(mouseSessions[mouseId])\n mouseName = miceToLoad[mouseId]\n print(mouseName)\n print(numSessions)\n\n sessionFovMeans = np.zeros([30,512,512])\n\n for sessionId in range(numSessions):\n print(sessionId)\n sessionName = mouseSessions[mouseId][sessionId]\n\n regDirecPath = dataFolder + mouseName + '/' + sessionName + '/registeredDirectory/'\n fovPath = regDirecPath + sessionName + '_fovMean.tif'\n print(fovPath)\n currImg = tff.TIFFfile(fovPath)\n currImg = currImg.asarray()\n sessionFovMeans[sessionId,:,:] =currImg\n sessionFovMeans = sessionFovMeans.astype('int16')\n #saveName = 'testy_' + str(sessionId) + '.tif'\\\n saveName = sessionName + '_fovMean.tif'\n tff.imsave(saveName,sessionFovMeans[sessionId,:,:])\n ##now we find the fov means, load them!\n sessionFovMeans = sessionFovMeans.astype('int16')\n #saveName = 'testy_' + str(sessionId) + '.tif'\\\n saveName = 'stackFovMean.tif'\n tff.imsave(saveName,sessionFovMeans[:,:,:])\n\n\n# In[65]:\n\ndistributeRoiSet=0\nif (distributeRoiSet==1):\n #####This code sends the communal roiSet more broadly.\n import shutil\n import re\n for mouseId in range(len(miceToLoad)):\n files = os.listdir(dataFolder+miceToLoad[mouseId])\n files = sorted(files)\n print(files)\n print('Working on mouse ' + str(miceToLoad[mouseId]))\n matchPattern = '[A-Z]{1,4}[0-9]{1,3}_S[0-9]{1,3}_F[0-9]{1,3}' ##the outline for acceptable files [A-D]{1-4}_\n mouseSessions[mouseId] = [elem for elem in files if re.search(matchPattern, elem) != None]\n print('The following relevant sessions were identified: ' + str(mouseSessions))\n \n ###now we take a copy\n matchPattern = 'RoiSet.zip' ##the outline for acceptable files [A-D]{1-4}_\n fovFile = [elem for elem in files if re.search(matchPattern, elem) != None]\n print(fovFile)\n \n ####now we iterate through and copy the roiSet to each file area.\n \n for sessionId in range(len(mouseSessions[mouseId])):\n #print(mouseSessions[sessionId])\n savePath = dataFolder + miceToLoad[mouseId] + '/' + mouseSessions[mouseId][sessionId] + '/registeredDirectory/' + mouseSessions[mouseId][sessionId] + '_roiSet.zip'\n print(savePath)\n shutil.copy(dataFolder+miceToLoad[mouseId]+'/'+fovFile[0], savePath)\n #now we do the copying. yipee\n\n\n# In[7]:\n\nrunPostProcess=0\nif (runPostProcess==1):\n \n for mouseId in range(len(miceToLoad)):\n files = os.listdir(dataFolder+miceToLoad[mouseId])\n files = sorted(files)\n print(files)\n print('Working on mouse ' + str(miceToLoad[mouseId]))\n matchPattern = '[A-Z]{1,4}[0-9]{1,3}_S[0-9]{1,3}_F[0-9]{1,3}' ##the outline for acceptable files [A-D]{1-4}_\n mouseSessions[mouseId] = [elem for elem in files if re.search(matchPattern, elem) != None]\n print('The following relevant sessions were identified: ' + str(mouseSessions))\n \n ###now we take a copy\n #matchPattern = 'RoiSet.zip' ##the outline for acceptable files [A-D]{1-4}_\n #fovFile = [elem for elem in files if re.search(matchPattern, elem) != None]\n #print(fovFile)\n \n ####now we iterate through and copy the roiSet to each file area.\n \n for sessionId in range(len(mouseSessions[mouseId])):\n projectFolder = 'chronicImaging'\n \n \n commandToRun = 'python 2_postProcessor.py ' + mouseSessions[mouseId][sessionId] + ' ' + projectFolder\n os.system(commandToRun)\n \n \nrunFeatureExtractor=1\nif (runFeatureExtractor==1):\n \n for mouseId in range(len(miceToLoad)):\n files = os.listdir(dataFolder+miceToLoad[mouseId])\n files = sorted(files)\n print(files)\n print('Working on mouse ' + str(miceToLoad[mouseId]))\n matchPattern = '[A-Z]{1,4}[0-9]{1,3}_S[0-9]{1,3}_F[0-9]{1,3}' ##the outline for acceptable files [A-D]{1-4}_\n mouseSessions[mouseId] = [elem for elem in files if re.search(matchPattern, elem) != None]\n print('The following relevant sessions were identified: ' + str(mouseSessions))\n \n ###now we take a copy\n #matchPattern = 'RoiSet.zip' ##the outline for acceptable files [A-D]{1-4}_\n #fovFile = [elem for elem in files if re.search(matchPattern, elem) != None]\n #print(fovFile)\n \n ####now we iterate through and copy the roiSet to each file area.\n \n for sessionId in range(len(mouseSessions[mouseId])):\n projectFolder = 'chronicImaging'\n \n \n commandToRun = 'python 3_featureExtractor.py ' + mouseSessions[mouseId][sessionId] + ' ' + projectFolder\n os.system(commandToRun)\n\n\n# In[62]:\n\nfovFile\n\n\n# In[57]:\n\nmouseSessions\n\n\n# In[29]:\n\nget_ipython().magic(u'matplotlib inline')\nplt.imshow(sessionFovMeans[1,:,:])\nfig = plt.gcf()\nfig.set_size_inches(12,12)\n\n\n# In[7]:\n\nmouseSessions\n\n\n# In[74]:\n\n#############need to go through + add deep commenting to this shit storm.\ndef regImageSimple(fullSearchNameRegged,filenameToLoad,sessionMeanOfImage, meanOfImage):\n currImg = tff.TIFFfile(fullSearchNameRegged + filenameToLoad)\n currImg = currImg.asarray() #converts the movie to a numpy array.\n currFrames = np.shape(currImg)\n difference = np.zeros((currFrames[0],2),dtype='int16')\n \n \n \n for compare in range(currFrames[0]):\n differencey = imr.register_images(sessionMeanOfImage,currImg[compare])\n difference[compare] = differencey\n \n\n\t\t ####Here we align the images:\n currImg2 = np.zeros((currFrames[0],512, 512),dtype='int16')\n for compare in range(currFrames[0]):\n newImg = np.roll(currImg[compare], -difference[compare][1], axis = 0) #-difference[compare][1]\n newImg = np.roll(newImg,-difference[compare][0], axis = 1)\n currImg2[compare] = newImg ###BUG THIS WILL STORE REST OF FILE TOO\n\n\n print('Aligned')\n del currImg\n currImg2 = currImg2.astype('int16')\n\t##Alignment should now be done.\n\n \n \n meanOfImage[numOfFile] = np.mean(currImg2,axis=0)\n #low_values_indices = meanOfImage[numOfFile] > imageConfig['imMaxContrast'] # Where values are low\n #meanOfImage[numOfFile, low_values_indices] = imageConfig['imMaxContrast']\n meanOfImage[numOfFile] = meanOfImage[numOfFile].astype('int16')\n \n \n os.remove(fullSearchNameRegged + filenameToLoad) \n #filenameToLoad = filenameToLoad + '.f'\n tff.imsave(fullSearchNameRegged + filenameToLoad,currImg2)\n \n\t#loadTiffMovie(movieSaveName2)\n print('Saved')\n return meanOfImage,difference\n\n\n\n\n# In[73]:\n\n#######ReRegister\n###Register:\n#how to verify output of this?\n\nreregister=1\nmouseIdToRegister =0 #the mouseId in the sessionFovMeans\nsessionToRegisterTo=0 #the fovMean to pick basically.\nif (reregister==1):\n \n #####Relevant fovMean:\n #fovToRegisterTo = \n mouseName = miceToLoad[mouseIdToRegister]\n sessionName = mouseSessions[mouseIdToRegister][sessionToRegisterTo]\n regDirecPath = dataFolder + mouseName + '/' + sessionName + '/' + 'registeredDirectory/'\n fovPath = regDirecPath + sessionName + '_fovMean.tif'\n currImg = tff.TIFFfile(fovPath)\n currImg = currImg.asarray()\n fovToRegisterTo=currImg\n sessionMeanOfImage = fovToRegisterTo\n \n \n #####\n print('Launching re-registration')\n print('reregistration is being performed relative to ' + str(mouseSessions[mouseIdToRegister][sessionToRegisterTo]))\n ###Now we iterate over the stored sessions, re-registering.\n for sessionId in range(len(mouseSessions[mouseIdToRegister])):\n if (sessionId !=sessionToRegisterTo):\n \n print('reregistering ' + str(mouseSessions[mouseIdToRegister][sessionId]))\n ######Now we launch the registration.\n ####key things to prepare?\n mouseName = miceToLoad[mouseIdToRegister]\n sessionName = mouseSessions[mouseIdToRegister][sessionId]\n regDirecPath = dataFolder + mouseName + '/' + sessionName + '/registeredDirectory/'\n print(regDirecPath)\n \n #####Now we load the relevant files, + use a regex etc.\n \n fullSearchNameRegged = regDirecPath\n dataFilesNames = os.listdir(fullSearchNameRegged) ###DATAFILES IS OUR REFERENCE FRAME\n dataFilesNames = sorted(dataFilesNames)\n ##Now we filter the files so that they are only files that we are interested in:\n matchPattern = '[A-Z]{1,4}[0-9]{1,3}_S[0-9]{1,3}_F[0-9]{1,3}_[0-9]{1,8}_r.tif' ##the outline for acceptable files [A-D]{1-4}_\n dataFilesNames = [elem for elem in dataFilesNames if re.search(matchPattern, elem) != None]\n print('The number of matching files (ie, tiff files) is: ', len(dataFilesNames))\n \n meanOfImage = np.zeros((len(dataFilesNames),512,512),dtype='int16')\n numOfFile=0\n for fileId in range(len(dataFilesNames)):\n if (fileId<50000):\n print(dataFilesNames[fileId])\n\n filenameToLoad = dataFilesNames[fileId]\n meanOfImage,differences = regImageSimple(fullSearchNameRegged,filenameToLoad,sessionMeanOfImage, meanOfImage)\n\n numOfFile=numOfFile+1\n #Save the image mean\n iterationMeanOfImage = np.mean(meanOfImage,axis=0)\n #localImMaxContrast= 200\n #low_values_indices = iterationMeanOfImage > localImMaxContrast # Where values are low\n #iterationMeanOfImage[low_values_indices] = localImMaxContrast\n globalMeanOfImage = iterationMeanOfImage.astype('int16')\n\n sessionMeanOfImage = globalMeanOfImage\n #localImMaxContrast= 200\n #low_values_indices = sessionMeanOfImage > localImMaxContrast # Where values are low\n #sessionMeanOfImage[low_values_indices] = localImMaxContrast\n sessionMeanOfImage = sessionMeanOfImage.astype('int16')\n toSaveName = sessionName + '_fovMean.tif'\n\n tff.imsave(regDirecPath + toSaveName, sessionMeanOfImage)\n print('Produced global mean')\n ###now we utilise a funky function yay.\n \n \n ####SAVE ORIGINAL FOVMEAN UNDER A DIFFERENT NAME FOR CONTINUITY'S SAKE? YES, THIS IS A GOOD IDEA.\n \n \n \n \n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[37]:\n\n#plt.imshow(sessionFovMeans[1,:,:])\n#fig = plt.gcf()\n#fig.set_size_inches(12,12)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n###################################################\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"_DISTILL/chronicAnalysis_central.py","file_name":"chronicAnalysis_central.py","file_ext":"py","file_size_in_byte":13159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"575794272","text":"#collections module\n\n#counter\n#dictionary subclass that helps count hashable objects\n\nfrom collections import Counter\n\n#elements are keys and counter is the value\n\nl = [1,1,2,32,23,34,34,3,34,34,3,34,34,5,6,6,77,8,8,9]\n\nprint(Counter(l))\n\ns = \"laksjalsdkfjaslkfjaslfkjasdlfkjasdlfasjdf\"\n\nprint(Counter(s))\n\ns = \"How many times times times does each each word show up up up up up\"\n\nwords = s.split()\n\nprint(Counter(words))\n\n\nc = Counter(words)\n\nprint(c.most_common(2))\n\n#a lot of patterns - google this for more info\n\n\nprint(sum(c.values())) #find how many words\n\n#print(c.most_common())[:-n-1:-1]\t# n least common elements\n\n\n\n####\n## defaultdict\n\n#all methods of a dict but also takes in a first arg as a default data type\n\nfrom collections import defaultdict\n\nd = {\"k1\":1}\n\nprint(d[\"k1\"])\n\n#print(d[\"k2\"])\t#this will give a key error, won't in a default dict\n\nd1 = defaultdict(object)\n\nprint(d1[\"one\"])\t#will assign the factory condition for that\n\nfor item in d1:\n\tprint(item)\n\n\n\n#python debugger\n#pdb\n\nimport pdb\n\n#go to the line where you saw the error\n# pdb.set_trace()\n# can enter in variables to find out what is going on in the code\n# \n\n#timing code\nimport timeit\n\n#timeit.timeit()\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","sub_path":"Bootcamp/15 Advanced Modules/advanced.py","file_name":"advanced.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"13688745","text":"\nimport time, logging, os, io, glob, datetime\nfrom functools import wraps\nfrom pymongo import MongoClient\nfrom pymongo.collection import Collection\nfrom functools import partial\n\nfrom biothings.utils.common import timesofar, get_random_string, iter_n, \\\n open_compressed_file, get_compressed_outfile\nfrom biothings.utils.backend import DocESBackend, DocMongoBackend\n# stub, until set to real config module\nconfig = None\n\nclass Connection(MongoClient):\n \"\"\"\n This class mimicks / is a mock for mongokit.Connection class,\n used to keep used interface (registering document model for instance)\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(Connection,self).__init__(*args,**kwargs)\n self._registered_documents = {}\n def register(self, obj):\n self._registered_documents[obj.__name__] = obj\n def __getattr__(self,key):\n if key in self._registered_documents:\n document = self._registered_documents[key]\n return document\n else:\n try:\n return self[key]\n except Exception:\n raise AttributeError(key)\n\ndef requires_config(func):\n @wraps(func)\n def func_wrapper(*args,**kwargs):\n global config\n if not config:\n try:\n from biothings import config as config_mod\n config = config_mod\n except ImportError:\n raise Exception(\"call biothings.config_for_app() first\")\n return func(*args,**kwargs)\n return func_wrapper\n\n@requires_config\ndef get_conn(server, port):\n if config.DATA_SRC_SERVER_USERNAME and config.DATA_SRC_SERVER_PASSWORD:\n uri = \"mongodb://{}:{}@{}:{}\".format(config.DATA_SRC_SERVER_USERNAME,\n config.DATA_SRC_SERVER_PASSWORD,\n server, port)\n else:\n uri = \"mongodb://{}:{}\".format(server, port)\n conn = Connection(uri)\n return conn\n\n\n@requires_config\ndef get_src_conn():\n return get_conn(config.DATA_SRC_SERVER, config.DATA_SRC_PORT)\n\n\n@requires_config\ndef get_src_db(conn=None):\n conn = conn or get_src_conn()\n return conn[config.DATA_SRC_DATABASE]\n\n\n@requires_config\ndef get_src_master(conn=None):\n conn = conn or get_src_conn()\n return conn[config.DATA_SRC_DATABASE][config.DATA_SRC_MASTER_COLLECTION]\n\n\n@requires_config\ndef get_src_dump(conn=None):\n conn = conn or get_src_conn()\n return conn[config.DATA_SRC_DATABASE][config.DATA_SRC_DUMP_COLLECTION]\n\n\n@requires_config\ndef get_src_build(conn=None):\n conn = conn or get_src_conn()\n return conn[config.DATA_SRC_DATABASE][config.DATA_SRC_BUILD_COLLECTION]\n\n@requires_config\ndef get_src_build_config(conn=None):\n conn = conn or get_src_conn()\n return conn[config.DATA_SRC_DATABASE][config.DATA_SRC_BUILD_COLLECTION + \"_config\"]\n\n@requires_config\ndef get_target_conn():\n if config.DATA_TARGET_SERVER_USERNAME and config.DATA_TARGET_SERVER_PASSWORD:\n uri = \"mongodb://{}:{}@{}:{}\".format(config.DATA_TARGET_SERVER_USERNAME,\n config.DATA_TARGET_SERVER_PASSWORD,\n config.DATA_TARGET_SERVER,\n config.DATA_TARGET_PORT)\n else:\n uri = \"mongodb://{}:{}\".format(config.DATA_TARGET_SERVER,config.DATA_TARGET_PORT)\n conn = Connection(uri)\n return conn\n\n\n@requires_config\ndef get_target_db(conn=None):\n conn = conn or get_target_conn()\n return conn[config.DATA_TARGET_DATABASE]\n\n\n@requires_config\ndef get_target_master(conn=None):\n conn = conn or get_target_conn()\n return conn[config.DATA_TARGET_DATABASE][config.DATA_TARGET_MASTER_COLLECTION]\n\n@requires_config\ndef get_source_fullname(col_name):\n \"\"\"\n Assuming col_name is a collection created from an upload process,\n find the main source & sub_source associated.\n \"\"\"\n src_dump = get_src_dump()\n info = src_dump.find_one({\"$where\":\"function() {if(this.upload) {for(var index in this.upload.jobs) {if(this.upload.jobs[index].step == \\\"%s\\\") return this;}}}\" % col_name})\n if info:\n name = info[\"_id\"]\n if name != col_name:\n # col_name was a sub-source name\n return \"%s.%s\" % (name,col_name)\n else:\n return name\n\ndef get_source_fullnames(col_names):\n main_sources = set()\n for col_name in col_names:\n main_source = get_source_fullname(col_name)\n if main_source:\n main_sources.add(main_source)\n return list(main_sources)\n\ndef doc_feeder(collection, step=1000, s=None, e=None, inbatch=False, query=None, batch_callback=None,\n fields=None, logger=logging):\n '''A iterator for returning docs in a collection, with batch query.\n additional filter query can be passed via \"query\", e.g.,\n doc_feeder(collection, query={'taxid': {'$in': [9606, 10090, 10116]}})\n batch_callback is a callback function as fn(cnt, t), called after every batch\n fields is optional parameter passed to find to restrict fields to return.\n '''\n if isinstance(collection,DocMongoBackend):\n collection = collection.target_collection\n cur = collection.find(query, no_cursor_timeout=True, projection=fields)\n n = cur.count()\n s = s or 0\n e = e or n\n logger.info('Retrieving %d documents from database \"%s\".' % (n, collection.name))\n t0 = time.time()\n if inbatch:\n doc_li = []\n cnt = 0\n t1 = time.time()\n try:\n if s:\n cur.skip(s)\n cnt = s\n logger.info(\"Skipping %d documents.\" % s)\n if e:\n cur.limit(e - (s or 0))\n cur.batch_size(step)\n logger.info(\"Processing %d-%d documents...\" % (cnt + 1, min(cnt + step, e)))\n for doc in cur:\n if inbatch:\n doc_li.append(doc)\n else:\n yield doc\n cnt += 1\n if cnt % step == 0:\n if inbatch:\n yield doc_li\n doc_li = []\n if n:\n logger.info('Done.[%.1f%%,%s]' % (cnt * 100. / n, timesofar(t1)))\n else:\n logger.info('Nothing to do...')\n if batch_callback:\n batch_callback(cnt, time.time()-t1)\n if cnt < e:\n t1 = time.time()\n logger.info(\"Processing %d-%d documents...\" % (cnt + 1, min(cnt + step, e)))\n if inbatch and doc_li:\n #Important: need to yield the last batch here\n yield doc_li\n\n #print 'Done.[%s]' % timesofar(t1)\n if n:\n logger.info('Done.[%.1f%%,%s]' % (cnt * 100. / n, timesofar(t1)))\n else:\n logger.info('Nothing to do...')\n logger.info(\"=\" * 20)\n logger.info('Finished.[total time: %s]' % timesofar(t0))\n finally:\n cur.close()\n\n# TODO: this func deals with different backend, should not be in bt.utils.mongo\n# and doc_feeder should do the same as this function regarding backend support\n@requires_config\ndef id_feeder(col, batch_size=1000, build_cache=True, logger=logging,\n force_use=False, force_build=False):\n \"\"\"Return an iterator for all _ids in collection \"col\"\n Search for a valid cache file if available, if not\n return a doc_feeder for that collection. Valid cache is\n a cache file that is newer than the collection.\n \"db\" can be \"target\" or \"src\".\n \"build_cache\" True will build a cache file as _ids are fetched, \n if no cache file was found\n \"force_use\" True will use any existing cache file and won't check whether\n it's valid of not.\n \"force_build\" True will build a new cache even if current one exists\n and is valid.\n \"\"\"\n src_db = get_src_db()\n ts = None\n found_meta = True\n\n if isinstance(col,DocMongoBackend):\n col = col.target_collection\n\n try:\n if col.database.name == config.DATA_TARGET_DATABASE:\n info = src_db[\"src_build\"].find_one({\"_id\": col.name})\n if not info:\n logger.warning(\"Can't find information for target collection '%s'\" % col.name)\n else:\n ts = info[\"started_at\"].timestamp()\n elif col.database.name == config.DATA_SRC_DATABASE:\n info = src_db[\"src_dump\"].find_one({\"$where\":\"function() {if(this.upload) {for(var index in this.upload.jobs) {if(this.upload.jobs[index].step == \\\"%s\\\") return this;}}}\" % col.name})\n if not info:\n logger.warning(\"Can't find information for source collection '%s'\" % col.name)\n else:\n ts = info[\"upload\"][\"jobs\"][col.name][\"started_at\"].timestamp()\n else:\n logging.warning(\"Can't find metadata for collection '%s' (not a target, not a source collection)\" % col)\n found_meta = False\n build_cache = False\n except KeyError:\n logger.warning(\"Couldn't find timestamp in database for '%s'\" % col.name)\n except Exception as e:\n logger.info(\"%s is not a mongo collection, _id cache won't be built (error: %s)\" % (col,e))\n build_cache = False\n\n # try to find a cache file\n use_cache = False\n cache_file = None\n cache_format = getattr(config,\"CACHE_FORMAT\",None)\n if found_meta and getattr(config,\"CACHE_FOLDER\",None):\n cache_file = get_cache_filename(col.name)\n try:\n # size of empty file differs depending on compression\n empty_size = {None:0,\"xz\":32,\"gzip\":25,\"bz2\":14}\n if force_build:\n logger.warning(\"Force building cache file\")\n use_cache = False\n # check size, delete if invalid\n elif os.path.getsize(cache_file) <= empty_size.get(cache_format,32): \n logger.warning(\"Cache file exists but is empty, delete it\")\n os.remove(cache_file)\n elif force_use:\n use_cache = True\n logger.info(\"Force using cache file\")\n else:\n mt = os.path.getmtime(cache_file)\n if ts and mt >= ts:\n use_cache = True\n else:\n logger.info(\"Cache is too old, discard it\")\n except FileNotFoundError:\n pass\n if use_cache:\n logger.debug(\"Found valid cache file for '%s': %s\" % (col.name,cache_file))\n with open_compressed_file(cache_file) as cache_in:\n if cache_format:\n iocache = io.TextIOWrapper(cache_in)\n else:\n iocache = cache_in\n for ids in iter_n(iocache,batch_size):\n yield [_id.strip() for _id in ids if _id.strip()]\n else:\n logger.debug(\"No cache file found (or invalid) for '%s', use doc_feeder\" % col.name)\n cache_out = None\n cache_temp = None\n if getattr(config,\"CACHE_FOLDER\",None) and config.CACHE_FOLDER and build_cache:\n if not os.path.exists(config.CACHE_FOLDER):\n os.makedirs(config.CACHE_FOLDER)\n cache_temp = \"%s._tmp_\" % cache_file\n # clean aborted cache file generation\n for tmpcache in glob.glob(os.path.join(config.CACHE_FOLDER,\"%s*\" % cache_temp)):\n logger.info(\"Removing aborted cache file '%s'\" % tmpcache)\n os.remove(tmpcache)\n # use temp file and rename once done\n cache_temp = \"%s%s\" % (cache_temp,get_random_string())\n cache_out = get_compressed_outfile(cache_temp,compress=cache_format)\n logger.info(\"Building cache file '%s'\" % cache_temp)\n else:\n logger.info(\"Can't build cache, cache not allowed or no cache folder\")\n build_cache = False\n if isinstance(col,Collection):\n doc_feeder_func = partial(doc_feeder,col, step=batch_size, inbatch=True, fields={\"_id\":1})\n elif isinstance(col,DocMongoBackend):\n doc_feeder_func = partial(doc_feeder,col.target_collection, step=batch_size, inbatch=True, fields={\"_id\":1})\n elif isinstance(col,DocESBackend):\n # get_id_list directly return the _id, wrap it to match other \n # doc_feeder_func returned vals. Also return a batch of id\n def wrap_id():\n ids = []\n for _id in col.get_id_list(step=batch_size):\n ids.append({\"_id\":_id})\n if len(ids) >= batch_size:\n yield ids\n ids = []\n if ids:\n yield ids\n doc_feeder_func = partial(wrap_id)\n else:\n raise Exception(\"Unknown backend %s\" % col)\n for doc_ids in doc_feeder_func():\n doc_ids = [_doc[\"_id\"] for _doc in doc_ids]\n if build_cache:\n strout = \"\\n\".join(doc_ids) + \"\\n\"\n if cache_format:\n # assuming binary format (b/ccompressed)\n cache_out.write(strout.encode())\n else:\n cache_out.write(strout)\n yield doc_ids\n if build_cache:\n cache_out.close()\n cache_final = os.path.splitext(cache_temp)[0]\n os.rename(cache_temp,cache_final)\n\n\ndef src_clean_archives(keep_last=1, src=None, verbose=True, noconfirm=False):\n '''clean up archive collections in src db, only keep last \n number of archive.\n '''\n from biothings.utils.dataload import list2dict\n from biothings.utils.common import ask\n\n src = src or get_src_db()\n\n archive_li = sorted([(coll.split('_archive_')[0], coll) for coll in src.collection_names()\n if coll.find('archive') != -1])\n archive_d = list2dict(archive_li, 0, alwayslist=1)\n coll_to_remove = []\n for k, v in archive_d.items():\n print(k, end='')\n #check current collection exists\n if src[k].count() > 0:\n cnt = 0\n for coll in sorted(v)[:-keep_last]:\n coll_to_remove.append(coll)\n cnt += 1\n print(\"\\t\\t%s archived collections marked to remove.\" % cnt)\n else:\n print('skipped. Missing current \"%s\" collection!' % k)\n if len(coll_to_remove) > 0:\n print(\"%d archived collections will be removed.\" % len(coll_to_remove))\n if verbose:\n for coll in coll_to_remove:\n print('\\t', coll)\n if noconfirm or ask(\"Continue?\") == 'Y':\n for coll in coll_to_remove:\n src[coll].drop()\n print(\"Done.[%s collections removed]\" % len(coll_to_remove))\n else:\n print(\"Aborted.\")\n else:\n print(\"Nothing needs to be removed.\")\n\n\ndef target_clean_collections(keep_last=2, target=None, verbose=True, noconfirm=False):\n '''clean up collections in target db, only keep last number of collections.'''\n import re\n from biothings.utils.common import ask\n\n target = target or get_target_db()\n coll_list = target.collection_names()\n\n for prefix in ('genedoc_mygene', 'genedoc_mygene_allspecies'):\n pat = prefix + '_(\\d{8})_\\w{8}'\n _li = []\n for coll_name in coll_list:\n mat = re.match(pat, coll_name)\n if mat:\n _li.append((mat.group(1), coll_name))\n _li.sort() # older collection appears first\n coll_to_remove = [x[1] for x in _li[:-keep_last]] # keep last # of newer collections\n if len(coll_to_remove) > 0:\n print('{} \"{}*\" collection(s) will be removed.'.format(len(coll_to_remove), prefix))\n if verbose:\n for coll in coll_to_remove:\n print('\\t', coll)\n if noconfirm or ask(\"Continue?\") == 'Y':\n for coll in coll_to_remove:\n target[coll].drop()\n print(\"Done.[%s collection(s) removed]\" % len(coll_to_remove))\n else:\n print(\"Aborted.\")\n else:\n print(\"Nothing needs to be removed.\")\n\n\ndef backup_src_configs():\n import json\n import os\n from .common import get_timestamp, DateTimeJSONEncoder\n from .aws import send_s3_file\n\n db = get_src_db()\n for cfg in ['src_dump', 'src_master', 'src_build']:\n xli = list(db[cfg].find())\n bakfile = '/tmp/{}_{}.json'.format(cfg, get_timestamp())\n bak_f = file(bakfile, 'w')\n json.dump(xli, bak_f, cls=DateTimeJSONEncoder, indent=2)\n bak_f.close()\n bakfile_key = 'genedoc_src_config_bk/' + os.path.split(bakfile)[1]\n print('Saving to S3: \"{}\"... '.format(bakfile_key), end='')\n send_s3_file(bakfile, bakfile_key, overwrite=True)\n os.remove(bakfile)\n print('Done.')\n\n\ndef get_data_folder(src_name):\n src_dump = get_src_dump()\n src_doc = src_dump.find_one({'_id': src_name})\n if not src_doc:\n raise ValueError(\"Can't find any datasource information for '%s'\" % src_name)\n # ensure we're not in a transient state\n assert src_doc.get(\"download\",{}).get('status') in ['success','failed'], \"Source files are not ready yet [status: \\\"%s\\\"].\" % src_doc['status']\n return src_doc['data_folder']\n\ndef get_latest_build(build_name):\n src_build = get_src_build()\n doc = src_build.find_one({\"_id\":build_name})\n if doc and doc.get(\"build\"):\n target = doc[\"build\"][-1][\"target_name\"]\n return target\n else:\n return None\n\ndef get_cache_filename(col_name):\n cache_folder = getattr(config,\"CACHE_FOLDER\",None)\n if not cache_folder:\n return # we don't even use cache, forget it\n cache_format = getattr(config,\"CACHE_FORMAT\",None)\n cache_file = os.path.join(config.CACHE_FOLDER,col_name)\n cache_file = cache_format and (cache_file + \".%s\" % cache_format) or cache_file\n return cache_file\n\ndef invalidate_cache(col_name,col_type=\"src\"):\n if col_type == \"src\":\n src_dump = get_src_dump()\n if not \".\" in col_name:\n fullname = get_source_fullname(col_name)\n assert fullname, \"Can't resolve source '%s' (does it exist ?)\" % col_name\n\n main,sub = fullname.split(\".\")\n doc = src_dump.find_one({\"_id\":main})\n assert doc, \"No such source '%s'\" % main\n assert doc.get(\"upload\",{}).get(\"jobs\",{}).get(sub), \"No such sub-source '%s'\" % sub\n # this will make the cache too old\n doc[\"upload\"][\"jobs\"][sub][\"started_at\"] = datetime.datetime.now()\n src_dump.update_one({\"_id\":main},{\"$set\" : {\"upload.jobs.%s.started_at\" % sub:datetime.datetime.now()}})\n elif col_type == \"target\":\n # just delete the cache file\n cache_file = get_cache_filename(col_name)\n if cache_file:\n try:\n os.remove(cache_file)\n except FileNotFoundError:\n pass\n\n","sub_path":"biothings/utils/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":18915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"433272583","text":"# Copyright Tom Westerhout (c) 2019\n#\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#\n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# * Neither the name of Tom Westerhout nor the names of other\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom numba import jit, float32, float64, complex64, complex128, void\nimport numpy as np\nimport torch\n\n__all__ = [\"logcosh\"]\n\n\n@jit(\n [\n void(complex64[:], complex64[:], float32[:]),\n void(complex128[:], complex128[:], float64[:]),\n ],\n nopython=True,\n fastmath=True,\n)\ndef _log_cosh_forward_impl(z, out, tanh_x):\n \"\"\"\n Kernel for implementing the forward pass of :py:class`_LogCosh`.\n\n :param z: A complex 1D array, input to ``forward``.\n :param out: A complex 1D array of the same shape as ``z``. It acts the\n output buffer. Upon return from the function it will contain\n ``log(cosh(z))``.\n :param tanh_x: Precomputed ``tanh(Re[z])``.\n \"\"\"\n log_2 = 0.693147180559945309417232121458176568075500134360255\n for i in range(z.size):\n x = np.abs(z[i].real)\n y = z[i].imag\n # To avoid overflow in cosh\n if x > 8:\n out[i] = x - log_2 + 0j\n else:\n out[i] = np.log(np.cosh(x)) + 0j\n out[i] += np.log(np.cos(y) + 1j * tanh_x[i] * np.sin(y))\n\n\n@jit(\n [\n void(complex64[:], complex64[:], float32[:], float32[:]),\n void(complex128[:], complex128[:], float64[:], float64[:]),\n ],\n nopython=True,\n fastmath=True,\n)\ndef _log_cosh_backward_impl(dz, out, tanh_x, tan_y):\n \"\"\"\n Kernel for implementing the backward pass of :py:class`_LogCosh`.\n\n This function is pure magic and it's a wonder that it works.\n\n :param dz: A complex 1D array, input to ``backward``.\n :param out:\n A complex 1D array of the same shape as ``z``. It acts the\n output buffer. Upon return from the function\n ``outₙ = ∂log(cosh(zₙ))/∂Re[zₙ] * Re[dzₙ] + ∂log(cosh(zₙ))/∂Im[zₙ] * Im[dzₙ]``.\n :param tanh_x: Precomputed ``tanh(Re[z])``.\n :param tan_y: Precomputed ``tan(Im[z])``.\n \"\"\"\n for i in range(len(out)):\n # B/A:\n B_over_A = tan_y[i] * tanh_x[i]\n # (∂A/∂x)/A:\n Dx_A_over_A = tanh_x[i]\n # (∂A/∂y)/A:\n Dy_A_over_A = -tan_y[i]\n # for convenience C := (∂A/∂y)/A + (B/A) * (∂A/∂x)/A:\n C = Dy_A_over_A + B_over_A * Dx_A_over_A\n # for convenience D := (∂A/∂x)/A - (B/A) * (∂A/∂y)/A:\n D = Dx_A_over_A - B_over_A * Dy_A_over_A\n # NOTE: The magic part. If you have an hour or two to spare, try checking this :)\n dx = dz[i].real\n dy = dz[i].imag\n out[i] = ((D * dx - C * dy) + 1j * (C * dx + D * dy)) / (1 + B_over_A ** 2)\n\n\nclass _LogCosh(torch.autograd.Function):\n @staticmethod\n def forward(ctx, z):\n \"\"\"\n :return: ``log(cosh(z))``\n \"\"\"\n if z.dtype == torch.float32:\n complex_type = np.complex64\n elif z.dtype == torch.float64:\n complex_type = np.complex128\n else:\n raise TypeError(\n \"Supported float types are float and double, but got {}.\".format(\n z.dtype\n )\n )\n\n # To make sure we're not computing derivatives.\n z = z.detach()\n # x := Re[z]\n x = z.view(-1, 2)[:, 0]\n # y := Im[z]\n y = z.view(-1, 2)[:, 1]\n # Precomputing tanh(Re[z]) -- we'll need it for both forward and\n # backward passes.\n tanh_x = torch.tanh(x)\n out = torch.empty(z.size(), dtype=z.dtype, requires_grad=False)\n _log_cosh_forward_impl(\n z.view(-1).numpy().view(dtype=complex_type),\n out.view(-1).numpy().view(dtype=complex_type),\n tanh_x.numpy(),\n )\n ctx.save_for_backward(z, tanh_x)\n return out\n\n\n\"\"\"\nLogCosh activation function.\n\"\"\"\nlogcosh = _LogCosh.apply\n","sub_path":"nqs_playground/functional.py","file_name":"functional.py","file_ext":"py","file_size_in_byte":5302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"275774801","text":"from tkinter import *\r\nimport tkinter.messagebox\r\nroot=Tk()\r\n\r\nanswer=tkinter.messagebox.askquestion('WARNING','This filters needs you to select the other image.\\nDo you want to continue??')\r\n\r\nif answer == 'yes':\r\n print(\"Fuck with ur silly faces\")\r\nelse:\r\n print(\"Fuck without a silly faces\")\r\nroot.mainloop()","sub_path":"PycharmProjects/GUI/messageBox.py","file_name":"messageBox.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"267548571","text":"from random import randint\nfrom math import sqrt, ceil\nfrom sys import maxsize\n\nGRIDSIZE = 30\n\nclass Vecteur:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n return Vecteur(self.x + other.x, self.y + other.y)\n\n def __sub__(self, other):\n return Vecteur(self.x - other.x, self.y - other.y)\n\n def __mul__(self, k):\n return Vecteur(k*self.x, k*self.y)\n\n def __div__(self, k):\n return Vecteur(self.x/k, self.y/k)\n\n def norme(self):\n return sqrt(self.x**2 + self.y**2)\n\n def normalise(self):\n n = self.norme()\n return Vecteur(self.x/n, self.y/n)\n\n def tourne(self):\n return Vecteur(self.y, self.x)\n\n def __str__(self):\n return f\"({self.x},{self.y})\"\n\n def to_int(self):\n return [ int(self.x), int(self.y) ]\n\nclass Obstacle:\n def __init__(self,\n debut=Vecteur(0, 0),\n rayon=5):\n\n self.position = debut\n self.rayon = rayon\n\n def setPosition(self, vecteur):\n self.position = vecteur\n\n def getPosition(self):\n return self.position\n\n def getPositionGrille(self):\n i = int(self.position.x/GRIDSIZE)\n j = int(self.position.y/GRIDSIZE)\n return i,j\n\n def distance(self, obstacle):\n dx = self.position.x -obstacle.position.x\n dy = self.position.y -obstacle.position.y\n return sqrt( dx*dx + dy*dy )\n #return (self.position - obstacle.position).norme()-3\n\n\nclass Voyageur(Obstacle):\n def __init__(self,\n debut=Vecteur(0, 0),\n destination=Vecteur(0, 0),\n taille_pas=10.0):\n\n super().__init__(debut, rayon=10)\n\n self.trajet = [ debut ]\n self.destination = destination\n self.next = debut\n self.taille_pas = taille_pas\n\n def observation(self, carte, voyageurs = None, obstacles = None, objectif = None, cout_objectif = 0):\n ## S'il n'y a pas d'objectif, aller vers la destination\n if objectif==None:\n destination = self.destination \n else:\n destination = objectif\n\n ## Vecteur vers la destination choisie\n direction = (destination - self.position)\n\n # Ce qui reste à parcourir\n reste = direction.norme()\n\n # Liste des voyageurs proches\n liste = [ voyageur\n for voyageur in voyageurs\n if ( (voyageur!=self) \n and (self.distance(voyageur) < voyageur.rayon + self.rayon + self.taille_pas) ) ]\n\n liste_devant = [ voyageur \n for voyageur in liste if (voyageur.position-destination).norme()self.taille_pas):\n pas = direction.normalise() * self.taille_pas\n # pas = Vecteur( direction.x * self.taille_pas / reste, direction.y * self.taille_pas / reste)\n self.next = self.position + pas\n else:\n self.next = destination\n else:\n ## Du monde devant\n #if objectif==None:\n i,j = self.getPositionGrille()\n\n ## On regarde les cases autour\n valeurs = []\n for colonne in range(i-1, i+2):\n for ligne in range(j-1, j+2):\n centre_case = Vecteur( colonne*GRIDSIZE + GRIDSIZE/2, ligne*GRIDSIZE + GRIDSIZE/2 )\n distance_case = (self.destination - centre_case).norme()\n\n ## Cout case = nb de voyageurs dans la case + poids relatif à la distance\n cout = carte.nb_voyageurs(colonne, ligne) + distance_case/800\n\n #print(cout, cout_objectif, cout=2:\n # ## Trop de monde, on attend\n # self.next = self.position\n #else:\n # ## On essaye d'eviter\n # direction = (self.position - liste[0].position) #.tourne()\n # pas = direction.normalise() * self.taille_pas\n # self.next = self.position+pas\n\n def deplacement(self):\n self.position = self.next\n self.trajet.append(self.position)\n\n def arrive(self):\n return self.position == self.destination\n\n def getTrajet(self):\n return self.trajet\n\n def __str__(self):\n return f\"{self.position} => {self.destination}\"\n\nclass Carte:\n def __init__(self, tx=400, ty=400, nb=100):\n \"\"\"Création d'une carte réctangulaire de taille tx * ty, avec nb voyageurs\"\"\"\n self.voyageurs = []\n self.voyageurs_arrives = []\n self.obstacles = []\n self.nb = nb\n self.w = tx\n self.h = ty\n\n #fenetre(tx+100, ty+100, \"Flux\")\n self.obstacles.append( Obstacle( Vecteur(tx/2, ty/2), 30) )\n self.obstacles.append( Obstacle( Vecteur(tx/6, ty/6), 30) )\n self.obstacles.append( Obstacle( Vecteur(5*tx/6, ty/6), 30) )\n self.obstacles.append( Obstacle( Vecteur(tx/6, 5*ty/6), 30) )\n self.obstacles.append( Obstacle( Vecteur(5*tx/6, 5*ty/6), 30) )\n\n for i in range(self.nb):\n\n dice = randint(0, 3)\n if dice == 0:\n dest = Vecteur(0, 0)\n elif dice == 1:\n dest = Vecteur(tx-1, 0)\n elif dice == 2:\n dest = Vecteur(tx-1, ty-1)\n else:\n dest = Vecteur(0, ty-1)\n\n pos = Vecteur(randint(0, tx-1), randint(0, ty-1))\n\n ## On crée un voyageur au hasard\n voyageur = Voyageur(pos, dest)\n\n ## On vérifie qu'il n'est pas trop proche de ceux déjà créés\n compteur = 1\n while compteur!=0:\n compteur = 0\n for j in range(i):\n if voyageur.distance(self.voyageurs[j]) < 2*voyageur.rayon :\n compteur = 1\n voyageur.setPosition( Vecteur(randint(0, tx-1), randint(0, ty-1)) )\n break\n\n for obstacle in self.obstacles:\n if voyageur.distance( obstacle ) < voyageur.rayon + obstacle.rayon :\n compteur = 1\n voyageur.setPosition( Vecteur(randint(0, tx-1), randint(0, ty-1)) )\n break\n\n self.voyageurs.append(voyageur)\n \n self.compter_voyageurs()\n\n def taille(self):\n \"\"\"Renvoie la taille de la carte\"\"\"\n return self.w, self.h\n\n def liste_voyageurs(self):\n \"\"\"Renvoie les deux listes des voyageurs\"\"\"\n return self.voyageurs, self.voyageurs_arrives\n\n def liste_obstacles(self):\n \"\"\"Renvoie les deux listes des voyageurs\"\"\"\n return self.obstacles\n\n def step(self):\n for v in self.voyageurs:\n v.observation(self, self.voyageurs, self.obstacles)\n v.deplacement()\n \n ## Enlever les voyageurs arrivés à destination\n for v in self.voyageurs:\n if v.arrive():\n self.voyageurs.remove(v)\n self.voyageurs_arrives.append(v)\n\n self.compter_voyageurs()\n\n def compter_voyageurs(self):\n nb_colonnes = ceil(self.w / GRIDSIZE)\n nb_lignes = ceil(self.h / GRIDSIZE)\n #print(nb_colonnes, nb_lignes)\n self.grille_nb_voyageurs = [ [ 0 ]*nb_lignes for i in range(nb_colonnes) ]\n\n for v in self.voyageurs:\n i,j = v.getPositionGrille()\n self.grille_nb_voyageurs[i][j] += 1\n\n #print(self.grille_nb_voyageurs)\n\n def print(self):\n \"\"\"Affichage des voyageurs dans la console\"\"\"\n for i in range(self.nb):\n print(\"Voyageur\", i, self.voyageurs[i])\n\n def nb_voyageurs(self, i, j):\n \"\"\"Renvoie le nombre de voyageurs dans la case (i,j) de la carte.\n Une case représéente un carré de 3x3 mètres = 30x30 px\"\"\"\n nb_colonnes = ceil(self.w / GRIDSIZE)\n nb_lignes = ceil(self.h / GRIDSIZE)\n\n ## Si (i,j) est en dehors de la grille, on renvoie maxsize\n if i<0 or i>=nb_colonnes or j<0 or j>=nb_lignes:\n return maxsize\n\n return self.grille_nb_voyageurs[i][j]\n\nif __name__ == '__main__':\n c = Carte(120,90,nb=5)\n c.print()\n # c.draw()\n\n #attendre_clic()\n\n for i in range(5000):\n c.step()\n if len(c.voyageurs)==0:\n break\n #attendre(50)","sub_path":"projet/src/modeles.py","file_name":"modeles.py","file_ext":"py","file_size_in_byte":9628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"390226416","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pywikibot, re, sys, argparse\n\nimport blib\nfrom blib import getparam, rmparam, set_template_name, msg, errmsg, site, tname\n\nouttext = []\n\ndef process_text_on_page(index, pagename, text):\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagename, txt))\n def errandpagemsg(txt):\n errandmsg(\"Page %s %s: %s\" % (index, pagename, txt))\n\n pagemsg(\"Processing\")\n\n notes = []\n\n def replace_links(description):\n def replace_raw_link(m):\n linktext = m.group(1)\n mm = re.search(r\":Category:Greek verbs conjugating like '(.*)'\\|'''like'''$\", linktext)\n if mm:\n return \"like(%s)\" % mm.group(1)\n if \":\" in linktext:\n return m.group(0)\n if \"|\" in linktext:\n parts = linktext.split(\"|\")\n if len(parts) != 2:\n pagemsg(\"WARNING: More than two parts in linktext: %s\" % linktext)\n return m.group(0)\n link, display = parts\n link = re.sub(\"#Greek$\", \"\", link)\n if display.replace(\"'\", \"\") == link:\n return \"<<%s>>\" % display\n retval = \"<<%s|%s>>\" % (link, display)\n pagemsg(\"WARNING: Returning two-part link %s\" % retval)\n return retval\n return \"<<%s>>\" % linktext\n description = re.sub(r\"\\[\\[(.*?)\\]\\]\", replace_raw_link, description)\n def replace_like(m):\n link, display = m.groups()\n if display.replace(\"'\", \"\") == link:\n return \"like<<%s>>\" % display\n pagemsg(\"WARNING: Can't collapse like(...) expression: %s\" % m.group(0))\n return m.group(0)\n description = re.sub(r\"like\\((.*?)\\) <<(.*?)>>\", replace_like, description)\n return description\n\n if \"verb conjugation group\" in pagename:\n label = re.sub(\"^Category:Greek \", \"\", pagename)\n breadcrumb = re.sub(\"^.*'(.*)'.*$\", r\"\\1\", label)\n lines = text.split(\"\\n\")\n breadcrumbs = lines[0]\n if not breadcrumbs.startswith(\">>\"):\n pagemsg(\"WARNING: Breadcrumb line doesn't look right: %s\" % breadcrumbs)\n return\n breadcrumbs = re.sub(\"^>>\", \"\", re.sub(\" $\", \"\", breadcrumbs)).split(\" >> \")\n breadcrumbs = [x.strip() for x in breadcrumbs]\n last_breadcrumb = blib.remove_links(breadcrumbs[-1]).replace(\"'\", \"\")\n if last_breadcrumb == \"Vowel ending stems\":\n parent = \"vowel-stem verbs\"\n else:\n last_breadcrumb = re.sub(\"(.*?) \", r\"(\\1)\", last_breadcrumb)\n parent = \"consonant-stem verbs in -%s-\" % last_breadcrumb\n category = lines[-1]\n m = re.search(r\"^\\[\\[Category:(.*)\\|(.*?)\\]\\]$\", category)\n if not m:\n pagemsg(\"WARNING: Last line doesn't look like a category line: %s\" % category)\n return\n parent2, conj_group_sort = m.groups()\n m = re.search(r\"^Greek (.*) conjugation groups$\", parent2)\n if not m:\n pagemsg(\"WARNING: Category doesn't look like a conjugation group: %s\" % parent2)\n return\n conj_group = m.group(1)\n textlines = lines[1:-1]\n if not textlines[-1]:\n textlines = textlines[0:-1]\n description = '\"' + '\\\\n\" ..\\n\\t\"'.join(textlines) + '\"'\n description = replace_links(description)\n cattext = \"\"\"\ngroups[\"%s\"] = {\"%s\", \"%s\", \"%s\",\n\\t%s\n}\n\n\"\"\" % (breadcrumb, conj_group, conj_group_sort, parent, description)\n pagemsg(\"Appended <%s>\" % cattext)\n outtext.append(cattext)\n elif \"verbs conjugating like\" in pagename:\n m = re.search(\"^Category:Greek verbs conjugating like '(.*?)'$\", pagename)\n if not m:\n pagemsg(\"WARNING: Can't parse 'verbs conjugating like' pagename\")\n return\n likeverb = m.group(1)\n lines = text.split(\"\\n\")\n breadcrumbs = lines[0]\n if not breadcrumbs.startswith(\":: >> \"):\n pagemsg(\"WARNING: Breadcrumb line doesn't look right: %s\" % breadcrumbs)\n return\n breadcrumbs = re.sub(\"^:: >> \", \"\", breadcrumbs).split(\" >> \")\n breadcrumbs = [x.strip() for x in breadcrumbs]\n parent_group = breadcrumbs[0]\n if len(breadcrumbs) == 1:\n breadcrumb_desc = None\n elif len(breadcrumbs) == 2:\n breadcrumb_desc = re.sub(\", like.*\", \"\", breadcrumbs[1])\n else:\n pagemsg(\"WARNING: Too many breadcrumbs for 'verbs conjugating like' page: %s\" % breadcrumbs)\n return\n m = re.search(r\"^\\[\\[:Category:Greek verb conjugation group '(.*)'\\]\\]$\", parent_group)\n if not m:\n pagemsg(\"WARNING: Can't parse 'verbs conjugating like' parent-group breadcrumb: %s\" % parent_group)\n return\n parent_group = m.group(1)\n if len(lines) < 3:\n pagemsg(\"WARNING: Not enough lines for 'verbs conjugating like' page: <<%s>>\" % text)\n return\n if not lines[-1].startswith(\"[[Category:\") or not lines[-2].startswith(\"[[Category:\"):\n pagemsg(\"WARNING: Last two lines aren't category references in 'verbs conjugating like' page: <<%s>>\" % text)\n return\n m = re.search(r\"^\\[\\[Category:Greek (.*?) conjugation verbs\", lines[-2])\n if not m:\n m = re.search(r\"^\\[\\[Category:Greek (.*?) conjugation verbs\", lines[-1])\n if not m:\n pagemsg(\"WARNING: Can't parse conjugation number out of last two category lines: <%s>, <%s>\" % (\n lines[-2], lines[-1]))\n return\n conj = m.group(1)\n desctext = []\n if len(lines) > 3:\n desctext = lines[1:-2]\n desctext = [x for x in desctext if x]\n if not desctext:\n description = None\n else:\n description = '\"' + '\\\\n\" ..\\n\\t\"'.join(desctext) + '\"'\n description = replace_links(description)\n if not breadcrumb_desc and not description:\n cattext = 'like_verbs[\"%s\"] = {\"%s\", \"%s\"}' % (likeverb, conj, parent_group)\n elif not description:\n cattext = 'like_verbs[\"%s\"] = {\"%s\", \"%s\", \"%s\"}' % (likeverb, conj, parent_group, breadcrumb_desc)\n else:\n breadcrumb_desc = '\"' + breadcrumb_desc + '\"' if breadcrumb_desc else \"nil\"\n cattext = 'like_verbs[\"%s\"] = {\"%s\", \"%s\", %s,\\n\\t%s\\n}' % (likeverb, conj, parent_group, breadcrumb_desc, description)\n cattext += \"\\n\"\n pagemsg(\"Appended <%s>\" % cattext)\n outtext.append(cattext)\n else:\n pagemsg(\"WARNING: Can't parse pagename\")\n\nparser = blib.create_argparser(\"Convert Greek verb categories to module\", include_pagefile=True,\n include_stdin=True)\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\n\nblib.do_pagefile_cats_refs(args, start, end, process_text_on_page, edit=True, stdin=True)\n\nmsg(\"\".join(outtext))\n","sub_path":"convert_greek_verb_categories.py","file_name":"convert_greek_verb_categories.py","file_ext":"py","file_size_in_byte":6345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"238727785","text":"import datetime\nimport logging\nimport queue\nimport threading\nimport time\nfrom types import TracebackType\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union\n\nimport psutil\n\nfrom determined.common import api, check\nfrom determined.common.api import TrialProfilerMetricsBatch\n\nSYSTEM_METRIC_TYPE_ENUM = \"PROFILER_METRIC_TYPE_SYSTEM\"\n\nLOG_NAMESPACE = \"determined-profiler\"\n\ntry:\n import pynvml\n\n pynvml.nvmlInit()\n SHOULD_PROFILE_GPUS = True\nexcept ModuleNotFoundError:\n logging.info(f\"{LOG_NAMESPACE} pynvml not found. Not collecting GPU metrics\")\n SHOULD_PROFILE_GPUS = False\nexcept pynvml.NVMLError_LibraryNotFound:\n logging.info(f\"{LOG_NAMESPACE} pynvml LibraryNotFound error. Not collecting GPU metrics\")\n SHOULD_PROFILE_GPUS = False\nexcept Exception as e:\n raise RuntimeError(f\"Could not set up pynvml, but it failed with an unexpected error: {e}\")\n\n\nclass Measurement:\n def __init__(self, timestamp: datetime.datetime, batch_idx: int, value: float):\n self.timestamp = timestamp\n self.batch_idx = batch_idx\n self.measurement = value\n\n\nclass StartMessage:\n pass\n\n\nclass ShutdownMessage:\n pass\n\n\nclass ProfilerAgent:\n \"\"\"\n Agent that collects metrics and sends them to the master.\n\n The ProfilerAgent needs to be created at the beginning of training and it needs\n to be notified every time the batch_idx increases.\n\n It will collect System Metrics using a background thread and then batch them and send\n them to the master. You can also collect Timings through the ProfilerAgent with the\n record_timing() method. The timings will be batched and sent to the master.\n\n Profiling is only active between start_on_batch and end_after_batch. It will also automatically\n shut down 5 minutes after starting. When profiling is not active, no system metrics are\n collected and the record_timing function is a no-op.\n \"\"\"\n\n def __init__(\n self,\n trial_id: int,\n agent_id: str,\n master_url: str,\n profiling_is_enabled: bool,\n global_rank: int,\n local_rank: int,\n start_on_batch: int,\n end_after_batch: Optional[int] = None,\n ):\n self.current_batch_idx = 0\n self.agent_id = agent_id\n self.trial_id = trial_id\n self.master_url = master_url\n self.start_on_batch = start_on_batch\n self.end_after_batch = end_after_batch\n self.local_rank = local_rank\n self.global_rank = global_rank\n\n self.profiling_is_enabled_in_experiment_config = profiling_is_enabled\n\n self.has_started = False\n self.has_finished = False\n\n self.shutdown_lock = threading.Lock()\n\n # If the ProfilingAgent is disabled, don't waste resources by creating useless threads\n if self.is_enabled:\n # Set up timer to stop collecting after 5 minutes\n self.max_collection_seconds = 300\n self.shutdown_timer = PreemptibleTimer(\n self.max_collection_seconds, self._end_collection\n )\n\n # Set up the thread responsible for making API calls\n self.send_queue = (\n queue.Queue()\n ) # type: \"\"\"queue.Queue[Union[List[TrialProfilerMetricsBatch], ShutdownMessage]]\"\"\"\n self.sender_thread = ProfilerSenderThread(self.send_queue, self.master_url)\n\n if self.sysmetrics_is_enabled:\n self.sys_metric_collector_thread = SysMetricCollectorThread(\n trial_id, agent_id, self.send_queue\n )\n\n # TODO [DET-5062]: Add data structure to batch timings and then send to SenderThread\n # Does this need to be its own thread to flush correctly?\n # if self.timings_is_enabled:\n # self.timings_batcher = TimingsBatcher()\n\n # Launch the children threads. This does not mean 'start collecting metrics'\n def start(self) -> None:\n if not self.is_enabled:\n return\n\n self.sender_thread.start()\n self.shutdown_timer.start()\n\n if self.sysmetrics_is_enabled:\n self.sys_metric_collector_thread.start()\n\n def end(self) -> None:\n if not self.is_enabled:\n return\n self._end_collection()\n\n def __enter__(self) -> \"ProfilerAgent\":\n self.start()\n return self\n\n def __exit__(\n self,\n exc_type: Optional[Type[BaseException]],\n exc_value: Optional[BaseException],\n traceback: Optional[TracebackType],\n ) -> None:\n self.end()\n\n @property\n def is_enabled(self) -> bool:\n \"\"\"\n Is the ProfilingAgent supposed to do anything at all?\n If this is false, the entire profiler is a no-op\n \"\"\"\n if not self.profiling_is_enabled_in_experiment_config:\n return False\n return self.sysmetrics_is_enabled or self.timings_is_enabled\n\n @property\n def sysmetrics_is_enabled(self) -> bool:\n return self.profiling_is_enabled_in_experiment_config and self.local_rank == 0\n\n @property\n def timings_is_enabled(self) -> bool:\n return self.profiling_is_enabled_in_experiment_config and self.global_rank == 0\n\n @property\n def is_active(self) -> bool:\n \"\"\"\n Is the ProfilingAgent actively collecting data and shipping to the API?\n \"\"\"\n if not self.is_enabled:\n return False\n return self.has_started and not self.has_finished\n\n def update_batch_idx(self, new_batch_idx: int) -> None:\n if not self.is_enabled:\n return\n\n check.check_gt_eq(\n new_batch_idx, self.current_batch_idx, \"Batch index should never decrease over time\"\n )\n self.current_batch_idx = new_batch_idx\n self.sys_metric_collector_thread.update_batch_idx(self.current_batch_idx)\n\n # Check if we should start collecting metrics\n if not self.has_started and self.current_batch_idx >= self.start_on_batch:\n self._begin_collection()\n\n # Check if we should stop collecting metrics due to batch idx being exceeded\n if (\n self.is_active\n and self.end_after_batch is not None\n and self.current_batch_idx > self.end_after_batch\n ):\n self._end_collection()\n\n def _begin_collection(self) -> None:\n if not self.is_enabled:\n return\n\n # Note: due to its simplicity, sender_thread doesn't need to be activated\n self.sys_metric_collector_thread.activate()\n # TODO [DET-5062]: Activate TimingBatcher as well\n self.shutdown_timer.activate()\n self.has_started = True\n\n def _end_collection(self) -> None:\n \"\"\"\n Stop collecting data and shut down child threads. This function can be invoked due to the\n max batch idx being exceeded, due to timeout or due to the ProfilingAgent shutting down as\n the harness exits, so the function needs to be threadsafe and idempotent.\n \"\"\"\n\n with self.shutdown_lock:\n if self.has_finished:\n return\n\n if self.is_enabled:\n # Shut down in reverse creation order\n self.shutdown_timer.kill()\n self.shutdown_timer.join()\n\n if self.sysmetrics_is_enabled:\n self.sys_metric_collector_thread.kill()\n self.sys_metric_collector_thread.join()\n\n # TODO [DET-5062]: Shut down TimingBatcher as well\n\n self.sender_thread.kill()\n self.sender_thread.join()\n\n self.has_finished = True\n\n def record_timing(self, timing: float) -> None:\n if not self.is_active:\n return\n # TODO [DET-5062]: Add new timing to TimingBatcher\n\n\nclass PreemptibleTimer(threading.Thread):\n \"\"\"\n Version of threading.Timer that can be cleaned up if the timer is no longer needed\n ```\n timer = CustomTimer(300, callback_fn)\n timer.start() # start the thread, not the timer\n timer.begin_timer()\n\n # After 300 seconds, callback_fn will be executed\n\n # If we need to clean up the timer\n timer.kill() # This is idempotent and will work fine if the timer has gone off\n ```\n \"\"\"\n\n def __init__(self, duration: int, callback: Callable):\n self.duration = duration\n self.callback = callback\n self._timer_has_begun = False\n self.control_queue: \"queue.Queue[Union[StartMessage, ShutdownMessage]]\" = queue.Queue()\n\n super().__init__(daemon=True)\n\n def activate(self) -> None:\n if not self._timer_has_begun:\n self.control_queue.put(StartMessage())\n self._timer_has_begun = True\n\n def kill(self) -> None:\n self.control_queue.put(ShutdownMessage())\n\n def run(self) -> None:\n msg = self.control_queue.get()\n if isinstance(msg, ShutdownMessage):\n return\n\n try:\n msg = self.control_queue.get(timeout=self.duration)\n if isinstance(msg, ShutdownMessage):\n return\n except queue.Empty:\n # Time is up!\n self.callback()\n\n\nclass SysMetricCollectorThread(threading.Thread):\n \"\"\"\n Background thread for collecting profiler metrics at a high granularity and shipping them to\n the master\n\n - SimpleCpuUtilization = Measured in percent\n - FreeMemory = Measured in Gigabytes\n - NetworkSentThroughput = Measured in Gigabit/s\n - NetworkRecvThroughput = Measured in Gigabit/s\n - DiskIops\n - DiskReadThroughput = Measured in bytes/second\n - DiskWriteThroughput = Measured in bytes/second\n - GpuUtilization = Measured in percent\n \"\"\"\n\n FLUSH_INTERVAL = 10 # How often to make API calls\n MEASUREMENT_INTERVAL = 0.1\n\n def __init__(self, trial_id: int, agent_id: str, send_queue: queue.Queue):\n\n self.current_batch_idx = 0\n self.send_queue = send_queue\n self.control_queue: \"queue.Queue[Union['StartMessage', 'ShutdownMessage']]\" = queue.Queue()\n self.current_batch = SysMetricBatcher(trial_id, agent_id)\n\n super().__init__(daemon=True)\n\n def activate(self) -> None:\n \"\"\"Begin collecting System Metrics\"\"\"\n self.control_queue.put(StartMessage())\n\n def kill(self) -> None:\n self.control_queue.put(ShutdownMessage())\n\n def update_batch_idx(self, new_batch_idx: int) -> None:\n self.current_batch_idx = new_batch_idx\n\n def run(self) -> None:\n cpu_util_collector = SimpleCpuUtilCollector()\n net_throughput_collector = NetThroughputCollector()\n free_memory_collector = FreeMemoryCollector()\n disk_collector = DiskReadWriteRateCollector()\n\n if SHOULD_PROFILE_GPUS:\n gpu_util_collector = GpuUtilCollector()\n gpu_memory_collection = GpuMemoryCollector()\n\n # Do nothing while we wait for a StartMessage\n msg = self.control_queue.get()\n if isinstance(msg, ShutdownMessage):\n return\n\n # Do initial measurement for rate-based collectors\n net_throughput_collector.reset()\n disk_collector.reset()\n\n batch_start_time = time.time()\n next_collection = time.time() + self.MEASUREMENT_INTERVAL\n\n while True:\n # This code is using a trick with the control_queue to sleep/block until the next\n # measurement should be taken, while still being able to respond to a shutdown\n # request immediately.\n now = time.time()\n if now < next_collection:\n sleep_time = next_collection - now\n # a negative timeout will lead to an exception when retrieving from the queue\n sleep_time = max(sleep_time, 0)\n try:\n msg = self.control_queue.get(timeout=sleep_time)\n if isinstance(msg, ShutdownMessage):\n # Drop any partial batches if we receive a shutdown\n return\n except queue.Empty:\n pass\n\n next_collection += self.MEASUREMENT_INTERVAL\n\n cpu_util = cpu_util_collector.measure(self.current_batch_idx)\n self.current_batch.add_nongpu_measurement(\n SysMetricType.SIMPLE_CPU_UTIL_METRIC, cpu_util\n )\n\n net_thru_sent, net_thru_recv = net_throughput_collector.measure(self.current_batch_idx)\n self.current_batch.add_nongpu_measurement(\n SysMetricType.NET_THRU_SENT_METRIC, net_thru_sent\n )\n self.current_batch.add_nongpu_measurement(\n SysMetricType.NET_THRU_RECV_METRIC, net_thru_recv\n )\n\n free_memory = free_memory_collector.measure(self.current_batch_idx)\n self.current_batch.add_nongpu_measurement(SysMetricType.FREE_MEM_METRIC, free_memory)\n\n disk_read_thru, disk_write_thru, iops = disk_collector.measure(self.current_batch_idx)\n self.current_batch.add_nongpu_measurement(\n SysMetricType.DISK_THRU_READ_METRIC, disk_read_thru\n )\n self.current_batch.add_nongpu_measurement(\n SysMetricType.DISK_THRU_WRITE_METRIC, disk_write_thru\n )\n self.current_batch.add_nongpu_measurement(SysMetricType.DISK_IOPS_METRIC, iops)\n\n if SHOULD_PROFILE_GPUS:\n gpu_util = gpu_util_collector.measure(self.current_batch_idx)\n for gpu_uuid in gpu_util.keys():\n self.current_batch.add_gpu_measurement(\n SysMetricType.GPU_UTIL_METRIC, gpu_uuid, gpu_util[gpu_uuid]\n )\n\n gpu_memory = gpu_memory_collection.measure(self.current_batch_idx)\n for gpu_uuid in gpu_memory.keys():\n self.current_batch.add_gpu_measurement(\n SysMetricType.GPU_FREE_MEMORY_METRIC, gpu_uuid, gpu_util[gpu_uuid]\n )\n\n # Check if it is time to flush the batch and start a new batch\n if time.time() - batch_start_time > self.FLUSH_INTERVAL:\n self.send_queue.put(self.current_batch.convert_to_post_format())\n self.current_batch.clear()\n batch_start_time = time.time()\n\n\nclass ProfilerSenderThread(threading.Thread):\n \"\"\"\n This is a thread that exists solely so that we can make API calls without blocking.\n It has a Queue through which work is sent to the thread\n \"\"\"\n\n def __init__(self, inbound_queue: queue.Queue, master_url: str) -> None:\n self.master_url = master_url\n self.inbound_queue = inbound_queue\n super().__init__(daemon=True)\n\n def kill(self) -> None:\n self.inbound_queue.put(ShutdownMessage())\n\n def run(self) -> None:\n while True:\n message = self.inbound_queue.get()\n if isinstance(message, ShutdownMessage):\n return\n api.post_trial_profiler_metrics_batches(\n self.master_url,\n message,\n )\n\n\nclass SysMetricType:\n GPU_UTIL_METRIC = \"gpu_util\"\n GPU_FREE_MEMORY_METRIC = \"gpu_free_memory\"\n NET_THRU_SENT_METRIC = \"net_throughput_sent\"\n NET_THRU_RECV_METRIC = \"net_throughput_recv\"\n DISK_IOPS_METRIC = \"disk_iops\"\n DISK_THRU_READ_METRIC = \"disk_throughput_read\"\n DISK_THRU_WRITE_METRIC = \"disk_throughput_write\"\n FREE_MEM_METRIC = \"free_memory\"\n SIMPLE_CPU_UTIL_METRIC = \"cpu_util_simple\"\n\n\nclass SysMetricBatcher:\n \"\"\"\n Data structure to collect batches of SysMetrics and then convert them to the format expected by\n the API\n \"\"\"\n\n def __init__(self, trial_id: int, agent_id: str) -> None:\n self.trial_id = trial_id\n self.agent_id = agent_id\n self.clear()\n\n def clear(self) -> None:\n self.batch = {\n SysMetricType.GPU_UTIL_METRIC: {},\n SysMetricType.GPU_FREE_MEMORY_METRIC: {},\n SysMetricType.NET_THRU_SENT_METRIC: [],\n SysMetricType.NET_THRU_RECV_METRIC: [],\n SysMetricType.DISK_IOPS_METRIC: [],\n SysMetricType.DISK_THRU_READ_METRIC: [],\n SysMetricType.DISK_THRU_WRITE_METRIC: [],\n SysMetricType.FREE_MEM_METRIC: [],\n SysMetricType.SIMPLE_CPU_UTIL_METRIC: [],\n } # type: Dict[str, Any]\n\n def add_nongpu_measurement(self, metric_type: str, measurement: Measurement) -> None:\n assert (\n metric_type in self.batch.keys()\n ), f\"Tried to add unknown type of non-GPU metric: {metric_type}\"\n self.batch[metric_type].append(measurement)\n\n def add_gpu_measurement(\n self, metric_type: str, gpu_uuid: str, measurement: Measurement\n ) -> None:\n assert (\n metric_type in self.batch.keys()\n ), f\"Tried to add unknown type of GPU metric: {metric_type}\"\n if gpu_uuid not in self.batch[metric_type].keys():\n self.batch[metric_type][gpu_uuid] = []\n self.batch[metric_type][gpu_uuid].append(measurement)\n\n def convert_to_timestamp_str(self, timestamp: datetime.datetime) -> str:\n return timestamp.isoformat() + \"Z\"\n\n def convert_to_post_format(self) -> List[TrialProfilerMetricsBatch]:\n def to_post_format(\n measurements: List[Measurement], labels: Dict[str, Any]\n ) -> TrialProfilerMetricsBatch:\n values, batches, timestamps = [], [], []\n for m in measurements:\n values.append(m.measurement)\n batches.append(m.batch_idx)\n timestamps.append(self.convert_to_timestamp_str(m.timestamp))\n return TrialProfilerMetricsBatch(values, batches, timestamps, labels)\n\n def make_labels(name: str, metric_type: str, gpu_uuid_label: str = \"\") -> Dict[str, Any]:\n return {\n \"trialId\": self.trial_id,\n \"name\": name,\n \"agentId\": self.agent_id,\n \"gpuUuid\": gpu_uuid_label,\n \"metricType\": metric_type,\n }\n\n trial_profiler_metrics_batches = []\n for metric_name in self.batch.keys():\n if (\n metric_name\n not in [SysMetricType.GPU_UTIL_METRIC, SysMetricType.GPU_FREE_MEMORY_METRIC]\n and len(self.batch[metric_name]) > 0\n ):\n trial_profiler_metrics_batches.append(\n to_post_format(\n self.batch[metric_name],\n make_labels(metric_name, SYSTEM_METRIC_TYPE_ENUM),\n )\n )\n\n # GPU Metrics need to be batched by GPU UUID\n if (\n metric_name in [SysMetricType.GPU_UTIL_METRIC, SysMetricType.GPU_FREE_MEMORY_METRIC]\n and len(self.batch[metric_name].keys()) > 0\n ):\n for gpu_uuid in self.batch[metric_name].keys():\n if len(self.batch[metric_name][gpu_uuid]) > 0:\n trial_profiler_metrics_batches.append(\n to_post_format(\n self.batch[metric_name][gpu_uuid],\n make_labels(\n metric_name, SYSTEM_METRIC_TYPE_ENUM, gpu_uuid_label=gpu_uuid\n ),\n )\n )\n\n return trial_profiler_metrics_batches\n\n\nGIGA = 1_000_000_000\n\n\nclass SimpleCpuUtilCollector:\n def measure(self, batch_idx: int) -> Measurement:\n cpu_util = psutil.cpu_percent()\n timestamp = datetime.datetime.utcnow()\n return Measurement(timestamp, batch_idx, cpu_util)\n\n\nclass FreeMemoryCollector:\n def measure(self, batch_idx: int) -> Measurement:\n free_mem_bytes = psutil.virtual_memory().available\n timestamp = datetime.datetime.utcnow()\n return Measurement(timestamp, batch_idx, free_mem_bytes / GIGA)\n\n\nclass NetThroughputCollector:\n def __init__(self) -> None:\n self.reset()\n\n def reset(self) -> None:\n self.start_time = time.time()\n net = psutil.net_io_counters()\n self.start_sent = net.bytes_sent\n self.start_recv = net.bytes_recv\n\n def measure(self, batch_idx: int) -> Tuple[Measurement, Measurement]:\n net = psutil.net_io_counters()\n end_time = time.time()\n\n delta_sent_bytes = net.bytes_sent - self.start_sent\n delta_recv_bytes = net.bytes_recv - self.start_recv\n\n time_delta = end_time - self.start_time\n\n self.start_time = end_time\n self.start_sent = net.bytes_sent\n self.start_recv = net.bytes_recv\n\n sent_throughput_bytes_per_second = delta_sent_bytes / time_delta\n recv_throughput_bytes_per_second = delta_recv_bytes / time_delta\n\n sent_throughput_gigabits_per_second = sent_throughput_bytes_per_second * 8 / GIGA\n recv_throughput_gigabits_per_second = recv_throughput_bytes_per_second * 8 / GIGA\n\n timestamp = datetime.datetime.fromtimestamp(end_time)\n return Measurement(timestamp, batch_idx, sent_throughput_gigabits_per_second), Measurement(\n timestamp, batch_idx, recv_throughput_gigabits_per_second\n )\n\n\nclass DiskReadWriteRateCollector:\n def __init__(self) -> None:\n self.reset()\n\n def reset(self) -> None:\n self.start_time = time.time()\n disk = psutil.disk_io_counters()\n\n self.start_read_bytes = disk.read_bytes\n self.start_write_bytes = disk.write_bytes\n\n self.start_read_count = disk.read_count\n self.start_write_count = disk.write_count\n\n def measure(self, batch_idx: int) -> Tuple[Measurement, Measurement, Measurement]:\n disk = psutil.disk_io_counters()\n end_time = time.time()\n\n delta_read_bytes = disk.read_bytes - self.start_read_bytes\n delta_write_bytes = disk.write_bytes - self.start_write_bytes\n\n delta_read_count = disk.read_count - self.start_read_count\n delta_write_count = disk.write_count - self.start_write_count\n\n delta_time = end_time - self.start_time\n\n self.start_time = end_time\n self.start_read_bytes = disk.read_bytes\n self.start_write_bytes = disk.write_bytes\n self.start_read_count = disk.read_count\n self.start_write_count = disk.write_count\n\n read_throughput_bytes_per_sec = delta_read_bytes / delta_time\n write_throughput_bytes_per_sec = delta_write_bytes / delta_time\n\n read_throughput_count_per_sec = delta_read_count / delta_time\n write_throughput_count_per_sec = delta_write_count / delta_time\n\n timestamp = datetime.datetime.fromtimestamp(end_time)\n read_throughput = Measurement(timestamp, batch_idx, read_throughput_bytes_per_sec)\n write_throughput = Measurement(timestamp, batch_idx, write_throughput_bytes_per_sec)\n iops = Measurement(\n timestamp, batch_idx, read_throughput_count_per_sec + write_throughput_count_per_sec\n )\n\n return read_throughput, write_throughput, iops\n\n\nclass GpuUtilCollector:\n def __init__(self) -> None:\n self.num_gpus = pynvml.nvmlDeviceGetCount()\n\n def measure(self, batch_idx: int) -> Dict[str, Measurement]:\n measurements = {}\n timestamp = datetime.datetime.utcnow()\n for i in range(self.num_gpus):\n handle = pynvml.nvmlDeviceGetHandleByIndex(i)\n try:\n util = pynvml.nvmlDeviceGetUtilizationRates(handle)\n measurements[handle] = Measurement(timestamp, batch_idx, util.gpu)\n except pynvml.NVMLError as e:\n logging.info(f\"{LOG_NAMESPACE}: failed to sample GPU utilization for GPU {i}: {e}\")\n return measurements\n\n\nclass GpuMemoryCollector:\n def __init__(self) -> None:\n self.num_gpus = pynvml.nvmlDeviceGetCount()\n\n def measure(self, batch_idx: int) -> Dict[str, Measurement]:\n measurements = {}\n timestamp = datetime.datetime.utcnow()\n for i in range(self.num_gpus):\n handle = pynvml.nvmlDeviceGetHandleByIndex(i)\n try:\n info = pynvml.nvmlDeviceGetMemoryInfo(handle)\n measurements[handle] = Measurement(timestamp, batch_idx, info.free)\n except pynvml.NVMLError as e:\n logging.info(f\"{LOG_NAMESPACE}: failed to sample GPU memory for GPU {i}: {e}\")\n return measurements\n","sub_path":"harness/determined/profiler.py","file_name":"profiler.py","file_ext":"py","file_size_in_byte":24438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"326302231","text":"import numpy as np\nfrom keras.models import model_from_json\nfrom keras.models import load_model\n\ndef prediction(img):\n # load json and create model\n json_file = open('model.json', 'r')\n \n loaded_model_json = json_file.read()\n json_file.close()\n loaded_model = model_from_json(loaded_model_json)\n \n # load weights into new model\n loaded_model.load_weights(\"\")\n #print(\"Loaded model from disk\")\n \n loaded_model.save('cnn.hdf5')\n loaded_model=load_model('cnn.hdf5')\n \n characters = '0,1,2,3,4,5,6,7,8,9'\n characters = characters.split(',')\n \n x = np.asarray(img, dtype = np.float32).reshape(1, 32, 32, 1) / 255 \n predicted=np.argmax(loaded_model.predict(x), axis=-1)\n label = characters[predicted]\n \n \n return label","sub_path":"predictor.py","file_name":"predictor.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"187081301","text":"import logging\nimport jwt\nimport re\nimport datetime\nfrom odoo import http, service, registry, SUPERUSER_ID\nfrom odoo.http import request\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\n\n_logger = logging.getLogger(__name__)\n\nSECRET_KEY = \"skjdfe48ueq893rihesdio*($U*WIO$u8\"\n\nregex = r\"^[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$\"\n\n\nclass Validator:\n def is_valid_email(self, email):\n return re.search(regex, email)\n\n def create_token(self, user):\n try:\n exp = datetime.datetime.utcnow() + datetime.timedelta(days=30)\n payload = {\n 'exp': exp,\n 'iat': datetime.datetime.utcnow(),\n 'sub': user['id'],\n 'lgn': user['login'],\n }\n\n token = jwt.encode(\n payload,\n SECRET_KEY,\n algorithm='HS256'\n )\n\n self.save_token(token, user['id'], exp)\n\n return token\n except Exception as ex:\n _logger.error(ex)\n raise\n\n def save_token(self, token, uid, exp):\n request.env['jwt.access_token'].sudo().create({\n 'user_id': uid,\n 'expires': exp.strftime(DEFAULT_SERVER_DATETIME_FORMAT),\n 'token': token,\n })\n\n def verify(self, token):\n record = request.env['jwt.access_token'].sudo().search([\n ('token', '=', token)\n ])\n\n if len(record) != 1:\n\n _logger.info('not found %s' % token)\n return False\n\n if not record.is_valid():\n return False\n \n\n _logger.info('found for %s' % token)\n return record.user_id\n \n \n def verify_token(self, token):\n try:\n result = {\n 'status': False,\n 'message': None,\n }\n payload = jwt.decode(token, SECRET_KEY)\n\n if not self.verify(token):\n result['message'] = 'token-invalid'\n return result\n # verify expiration\n # We don't need to verify since jwt has done it for us (which would raise a 'jwt.ExpiredSignatureError')\n # if datetime.datetime.utcnow().timestamp() > payload['exp']:\n # return False\n\n # get user password\n # usr = request.env['res.users'].sudo().browse(payload['sub']).read(['password'])\n # if len(usr) == 0:\n # result['message'] = 'user-not-found'\n # return result\n # usr = usr[0]\n # log the user in\n uid = request.session.authenticate(request.session.db, uid=payload['sub'], password=token)\n if not uid:\n result['message'] = 'login-failed'\n return result\n\n result['status'] = True\n return result\n except jwt.ExpiredSignatureError:\n result['message'] = 'token-expired'\n return result\n except jwt.InvalidTokenError:\n result['message'] = 'token-invalid'\n return result\n except Exception:\n # raise\n result['message'] = 'token-invalid'\n return result\n # return result\n\nvalidator = Validator()","sub_path":"validator.py","file_name":"validator.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"584661619","text":"import os\n\nimport pandas as pd\nimport numpy as np\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify, render_template\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\n\n#################################################\n# Database Setup\n#################################################\n\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"sqlite:///db/waterdb.sqlite\"\ndb = SQLAlchemy(app)\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(db.engine, reflect=True)\n\n# Save references to each table\nAquastat_table = Base.classes.Aquastat_table\nWQI_table = Base.classes.WQI_table\n\n## create table in sqlite with index column as primary key\n# sqlite> create table `WQITable`(\n# `index` int primary key,\n# `iso` varchar(20),\n# `country` varchar(30),\n# `H2O.current` float);\n\n## show table header in sqlite3\n# .headers on\n# .mode column\n\n# insert into `WQITable`(`iso`,`country`,`H2O.current`)\n# select `iso`,`country`,`H2O.current` FROM `WQI_table` ;\n\n# alter table `WQITable`\n# rename column `H2O.current` to `H2O_current`;\n\n@app.route(\"/\")\ndef index():\n \"\"\"Return the homepage.\"\"\"\n return render_template(\"index.html\")\n\n\n\n\n@app.route(\"/names\")\ndef names():\n \"\"\"Return a list of country names and iso.\"\"\"\n\n # Use Pandas to perform the sql query\n stmt = db.session.query(Aquastat_table).statement\n aqua_df = pd.read_sql_query(stmt, db.session.bind)\n\n name_df = aqua_df.drop_duplicates('iso')[['country','iso']]\n # Return a list of the column names (sample names)\n return jsonify( name_df.to_dict('records') ) \n\n\n@app.route(\"/aquadata/\")\ndef country_aquadata(iso):\n \"\"\"Return the Aqua stat table data for a given country(by iso code).\"\"\"\n #query aquastat table\n sel = [\n Aquastat_table.country,\n Aquastat_table.Variable,\n Aquastat_table.Year,\n Aquastat_table.Value,\n Aquastat_table.unit,\n Aquastat_table.iso,\n ]\n\n country_stmt = db.session.query(*sel).filter(Aquastat_table.iso == iso).statement\n country_df = pd.read_sql_query(country_stmt, db.session.bind)\n\n try: #for some country (Nauru) part of the data is missing, so we skip that by doing this try-except block\n #Build dictionary to return as json\n country_df_grouped = country_df.groupby(['country','Variable'])\n country_aquadata = {}\n\n country_aquadata['iso'] = iso\n country_aquadata['country'] = country_df['country'].iloc[0]\n \n #index = (country, variable) is a tuple, so index[1] is just country name\n for index, table in country_df_grouped:\n data={}\n data['Year'] = list(table.Year)\n data['Value'] = list(table.Value)\n country_aquadata[index[1]] = data\n #print(sample_metadata)\n return jsonify(country_aquadata)\n\n except:\n return \"\"\n\n@app.route(\"/wqidata/\")\ndef country_wqidata(iso):\n #query wqi table\n wqi_stmt = db.session.query(WQI_table.iso, WQI_table.H2O_current).filter(WQI_table.iso == iso).statement\n wqi_df = pd.read_sql_query(wqi_stmt, db.session.bind)\n\n\n #country_wqidata['wqi'] = wqi_df.iloc[0]['H2O_current']\n\n return jsonify( wqi_df.to_dict('records') ) \n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"tao-branch/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"131026254","text":"import codecs\nfrom gensim.models import Word2Vec\n\ndef main():\n path_to_model = '/data/corpus/GoogleNews-vectors-negative300.bin'\n output_file = '/data/corpus/GoogleNews-vectors-negative300_test.txt'\n export_to_file(path_to_model, output_file)\n\n\ndef export_to_file(path_to_model, output_file):\n output = codecs.open(output_file, 'w' , 'utf-8')\n model = Word2Vec.load_word2vec_format(path_to_model, binary=True)\n print('done loading Word2Vec')\n vocab = model.vocab\n for mid in vocab:\n #print(model[mid])\n #print(mid)\n vector = list()\n for dimension in model[mid]:\n vector.append(str(dimension))\n #line = { \"mid\": mid, \"vector\": vector }\n vector_str = \",\".join(vector)\n line = mid + \"\\t\" + vector_str\n #line = json.dumps(line)\n output.write(line + \"\\n\")\n output.close()\n\nif __name__ == \"__main__\":\n main()\n #cProfile.run('main()') # if you want to do some profiling","sub_path":"utils/convert_googlenews.py","file_name":"convert_googlenews.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"454841790","text":"'''\n\n변수 a에 1차원 배열 형태의 값으로 1,2,3 을 할당하고 변수 b에는 2차원 배열 형태의 값을 전달하였다.\n그리고 아래와 같이 add 키워드를 사용하여 더하고 출력하였다.\n\n'''\nimport tensorflow as tf\n\na = tf.constant([1, 2, 3])\nb = tf.constant([[10, 20, 30], [100, 200, 300]])\nc = tf.add(a, b)\n\nprint(c)\n#----------------------------------------------------------\n'''\n출력 예상\n[[ 11 22 33]\n [101 202 303]]\n \n실제출력\n Tensor(\"Add:0\", shape=(2, 3), dtype=int32)\n\n\n텐서플로우 프로그래밍 모델을 이해하면 알 수 있는데 이름에서 알 수 있 듯이 텐서(Tensor)라는 \n동적 사이즈의 다차원 데이터 배열 그리고 플로우(Flow)라는 이 텐서(Tensor)들의 흐름을 제어하는 의미인것으로 \n데이터 플로우 그래프 기반의 라이브러리이다. \n\n결과적으로 모든 것들은 이 텐서(Tensor)라는 것으로 이루어져 있고 이를 통하여 연산을 하고 \n결과를 출력한다고 보면 될 것 이다.\n따라서, 기본적으로 기본 전제하에 나는 텐서를 선언하였고 이를 프린트 하였으니 당연히 텐서의 정보가 출력된 것이다. \n위의 텐서는 (2,3) 형태의 배열에 자료형이 정수형임을 의미한다.\n\n따라서 그것을 첫번째 출력물과 같은 예상 결과물을 위해서는 이와 같이 작성하여야 한다. \n'''\n#----------------------------------------------------------//\nwith tf.Session() as sess:\n print(sess.run(c))\n'''\n출력\n[[ 11 22 33]\n [101 202 303]]\n \n'''\n","sub_path":"B01_기본문법_Constant.py","file_name":"B01_기본문법_Constant.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"70564462","text":"INF = 999999999 # 무한의 비용 선언\n\n# 2차원 리스트를 이용해 인접 행렬 표현\ngraph = [\n [0, 7, 5],\n [7, 0, INF],\n [5, INF, 0]\n]\n\nprint(graph)\n\n# 인접 행렬 방식은 2차원 배열에 각 노드가 연결된 형태를 기록하는 방식이다.\n# 연결된 그래프를 인접 행렬로 표현할때 파이썬에서는 2차원 리스트로 구현할 수 있다.\n# 연결이 되어 있지 않은 노드끼리는 무한(Infinity)의 비용이라고 작성한다.\n# 실제로 코드에서는 논리적으로 정답이 될 수 없는 큰 값 중에서 999999999, 987654321 등의 값으로 초기화 하는 경우가 많다.\n\n","sub_path":"KYJ/이코테/DFS & BFS/5-6 (인접 행렬 예제).py","file_name":"5-6 (인접 행렬 예제).py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"370993486","text":"#!/usr/bin/python3\n# rotary volume knob\n# these files belong all together:\n# RPi-Jukebox-RFID/scripts/rotary-encoder.py\n# RPi-Jukebox-RFID/scripts/ky040.py\n# RPi-Jukebox-RFID/misc/sampleconfigs/phoniebox-rotary-encoder.service.stretch-default.sample\n# See wiki for more info: https://github.com/MiczFlor/RPi-Jukebox-RFID/wiki\n\nimport RPi.GPIO as GPIO\n\nclass KY040:\n\n def __init__(self, arg_clockPin, arg_dataPin, arg_rotaryCallbackCW=None, arg_rotaryCallbackCCW=None, arg_rotaryBouncetime=100, arg_switchBouncetime=100):\n # persist values\n self.clockPin = arg_clockPin\n self.dataPin = arg_dataPin\n self.rotaryCallbackCW = arg_rotaryCallbackCW\n self.rotaryCallbackCCW = arg_rotaryCallbackCCW\n self.rotaryBouncetime = arg_rotaryBouncetime\n\n # setup pins\n GPIO.setup(self.clockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(self.dataPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n def start(self):\n GPIO.add_event_detect(self.clockPin, GPIO.FALLING, callback=self._clockCallback, bouncetime=self.rotaryBouncetime)\n\n def stop(self):\n GPIO.remove_event_detect(self.clockPin)\n\n def _clockCallback(self, pin):\n if GPIO.input(self.clockPin) == 0:\n data = GPIO.input(self.dataPin)\n if data == 1:\n self.rotaryCallbackCCW()\n else:\n self.rotaryCallbackCW()\n","sub_path":"scripts/ky040.py","file_name":"ky040.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"225786998","text":"\n# This program is used to calculate the green view index based on the collecte metadata. The\n# Object based images classification algorithm is used to classify the greenery from the GSV imgs\n# in this code, the meanshift algorithm implemented by pymeanshift was used to segment image\n# first, based on the segmented image, we further use the Otsu's method to find threshold from\n# ExG image to extract the greenery pixels.\n\n# For more details about the object based image classification algorithm\n# check: Li et al., 2016, Who lives in greener neighborhoods? the\n# distribution of street greenery and it association with residents'\n# socioeconomic conditions in Hartford, Connectictu, USA\n\n# This program implementing OTSU algorithm to chose the threshold automatically\n# For more details about the OTSU algorithm and python implmentation\n# cite:\n# http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html\n\n\n# Copyright(C) Xiaojiang Li, Ian Seiferling, Marwa Abdulhai, Senseable City Lab, MIT\n# First version June 18, 2014\n\nimport time\nfrom PIL import Image\nimport numpy as np\nimport requests\nimport sys\nfrom urllib.parse import urlencode\nimport pymeanshift as pms\n\n\ndef graythresh(array, level):\n '''array: is the numpy array waiting for processing\n return thresh: is the result got by OTSU algorithm\n if the threshold is less than level, then set the level as the threshold\n by Xiaojiang Li\n '''\n\n np.seterr(divide='ignore', invalid='ignore')\n\n maxVal = np.max(array)\n minVal = np.min(array)\n\n # if the inputImage is a float of double dataset then we transform the data\n # in to byte and range from [0 255]\n if maxVal <= 1:\n array = array * 255\n elif maxVal >= 256:\n array = np.int((array - minVal) / (maxVal - minVal))\n\n # turn the negative to natural number\n negIdx = np.where(array < 0)\n array[negIdx] = 0\n\n # calculate the hist of 'array'\n dims = np.shape(array)\n hist = np.histogram(array, range(257))\n P_hist = hist[0] * 1.0 / np.sum(hist[0])\n\n omega = P_hist.cumsum()\n\n temp = np.arange(256)\n mu = P_hist * (temp + 1)\n mu = mu.cumsum()\n\n n = len(mu)\n mu_t = mu[n - 1]\n\n sigma_b_squared = (mu_t * omega - mu)**2 / (omega * (1 - omega))\n\n # try to found if all sigma_b squrered are NaN or Infinity\n indInf = np.where(sigma_b_squared == np.inf)\n\n CIN = 0\n if len(indInf[0]) > 0:\n CIN = len(indInf[0])\n\n maxval = np.max(sigma_b_squared)\n\n IsAllInf = CIN == 256\n if IsAllInf != 1:\n index = np.where(sigma_b_squared == maxval)\n idx = np.mean(index)\n threshold = (idx - 1) / 255.0\n else:\n threshold = level\n\n if np.isnan(threshold):\n threshold = level\n\n return threshold\n\n\ndef VegetationClassification(Img):\n '''\n This function is used to classify the green vegetation from GSV image,\n This is based on object based and otsu automatically thresholding method\n The season of GSV images were also considered in this function\n Img: the numpy array image, eg. Img = np.array(Image.open(StringIO(response.content)))\n return the percentage of the green vegetation pixels in the GSV image\n\n By Xiaojiang Li\n '''\n\n # use the meanshift segmentation algorithm to segment the original GSV\n # image\n (segmented_image, labels_image, number_regions) = pms.segment(\n Img, spatial_radius=6, range_radius=7, min_density=40)\n\n I = segmented_image / 255.0\n\n red = I[:, :, 0]\n green = I[:, :, 1]\n blue = I[:, :, 2]\n\n # calculate the difference between green band with other two bands\n green_red_Diff = green - red\n green_blue_Diff = green - blue\n\n ExG = green_red_Diff + green_blue_Diff\n diffImg = green_red_Diff * green_blue_Diff\n\n redThreImgU = red < 0.6\n greenThreImgU = green < 0.9\n blueThreImgU = blue < 0.6\n\n shadowRedU = red < 0.3\n shadowGreenU = green < 0.3\n shadowBlueU = blue < 0.3\n del red, blue, green, I\n\n greenImg1 = redThreImgU * blueThreImgU * greenThreImgU\n greenImgShadow1 = shadowRedU * shadowGreenU * shadowBlueU\n del redThreImgU, greenThreImgU, blueThreImgU\n del shadowRedU, shadowGreenU, shadowBlueU\n\n greenImg3 = diffImg > 0.0\n greenImg4 = green_red_Diff > 0\n threshold = graythresh(ExG, 0.1)\n\n if threshold > 0.1:\n threshold = 0.1\n elif threshold < 0.05:\n threshold = 0.05\n\n greenImg2 = ExG > threshold\n greenImgShadow2 = ExG > 0.05\n greenImg = greenImg1 * greenImg2 + greenImgShadow2 * greenImgShadow1\n del ExG, green_blue_Diff, green_red_Diff\n del greenImgShadow1, greenImgShadow2\n\n # calculate the percentage of the green vegetation\n greenPxlNum = len(np.where(greenImg != 0)[0])\n greenPercent = greenPxlNum / (400.0 * 400) * 100\n del greenImg1, greenImg2\n del greenImg3, greenImg4\n\n return greenPercent\n\n\n# using 18 directions is too time consuming, therefore, here I only use 6 horizontal directions\n# Each time the function will read a text, with 1000 records, and save the\n# result as a single TXT\ndef GreenViewComputing_ogr_6Horizon(GSVinfoFolder, outTXTRoot, greenmonth):\n \"\"\"\n This function is used to download the GSV from the information provide\n by the gsv info txt, and save the result to a shapefile\n\n Required modules: numpy, requests, and PIL\n\n GSVinfoTxt: the input folder name of GSV info txt\n outTXTRoot: the output folder to store result green result in txt files\n greenmonth: a list of the green season, greenmonth = ['05','06','07','08','09']\n\n \"\"\"\n\n # read the Google Street View API key files, you can also replace these\n # keys by your own\n\n # set a series of heading angle\n headingArr = 360 / 6 * np.array([0, 1, 2, 3, 4, 5])\n\n # number of GSV images for Green View calculation, in my original Green\n # View View paper, I used 18 images, in this case, 6 images at different\n # horizontal directions should be good.\n numGSVImg = len(headingArr) * 1.0\n pitch = 0\n\n # create a folder for GSV images and grenView Info\n if not os.path.exists(outTXTRoot):\n os.makedirs(outTXTRoot)\n\n # the input GSV info should be in a folder\n if not os.path.isdir(GSVinfoFolder):\n print('You should input a folder for GSV metadata')\n return\n else:\n allTxtFiles = os.listdir(GSVinfoFolder)\n for txtfile in allTxtFiles:\n if not txtfile.endswith('.txt'):\n continue\n\n txtfilename = os.path.join(GSVinfoFolder, txtfile)\n panoIDLst, panoDateLst, panoLonLst, panoLatLst = get_pano_lists_from_file(\n txtfilename, greenmonth)\n\n # the output text file to store the green view and pano info\n gvTxt = 'GV_' + os.path.basename(txtfile)\n GreenViewTxtFile = os.path.join(outTXTRoot, gvTxt)\n\n # check whether the file already generated, if yes, skip.\n # Therefore, you can run several process at same time using this\n # code.\n print(\"Processing\", GreenViewTxtFile)\n if os.path.exists(GreenViewTxtFile):\n print(\"File already exists\")\n continue\n\n # write the green view and pano info to txt\n with open(GreenViewTxtFile, \"w\") as gvResTxt:\n for i in range(len(panoIDLst)):\n panoDate = panoDateLst[i]\n panoID = panoIDLst[i]\n lat = panoLatLst[i]\n lon = panoLonLst[i]\n\n # calculate the green view index\n greenPercent = 0.0\n\n for heading in headingArr:\n print(\"Heading is: \", heading)\n\n # using different keys for different process, each key\n # can only request 25,000 imgs every 24 hours\n URL = get_api_url(panoID, heading, pitch)\n\n # classify the GSV images and calcuate the GVI\n try:\n im = retreive_image(URL, panoID, heading)\n percent = VegetationClassification(im)\n greenPercent = greenPercent + percent\n\n # if the GSV images are not download successfully or\n # failed to run, then return a null value\n except BaseException:\n print(\"Unexpected error:\", sys.exc_info())\n greenPercent = -1000\n break\n\n # calculate the green view index by averaging six percents\n # from six images\n greenViewVal = greenPercent / numGSVImg\n print(\n 'The greenview: %s, pano: %s, (%s, %s)' %\n (greenViewVal, panoID, lat, lon))\n\n # write the result and the pano info to the result txt file\n lineTxt = 'panoID: %s panoDate: %s longitude: %s latitude: %s, greenview: %s\\n' % (\n panoID, panoDate, lon, lat, greenViewVal)\n gvResTxt.write(lineTxt)\n\n\ndef get_api_url(panoID, heading, pitch):\n params = {\n \"size\": \"400x400\",\n \"pano\": panoID,\n \"fov\": 60,\n \"heading\": heading,\n \"pitch\": pitch,\n \"sensor\": \"false\",\n \"key\": config.gcloud_key,\n \"source\": \"outdoor\"\n }\n URL = \"http://maps.googleapis.com/maps/api/streetview?\" + urlencode(params)\n return URL\n\n\ndef get_api_image(url, img_path):\n response = requests.get(url, stream=True)\n image = Image.open(response.raw)\n\n save_img_to_local(image, img_path)\n\n # let the code to pause by 1s, in order to not go over\n # data limitation of Google quota\n time.sleep(0.005)\n\n return np.array(image)\n\n\ndef save_img_to_local(image, path):\n # Saving the images to a local path\n os.makedirs(os.path.dirname(path), exist_ok=True)\n image.save(path)\n\n\ndef retreive_image(URL, panoID, heading):\n ''' A function that retreives an image it first cheks if it exists locally,\n if it doesn't it fetches the image from the API, save it and return it'''\n\n img_path = config.GVIfile['images'] + \\\n str(panoID) + '_' + str(heading) + '.jpg'\n\n # If the images exists locally it retreives it\n if os.path.isfile(img_path):\n return np.array(Image.open(img_path))\n else:\n return get_api_image(URL, img_path)\n\n\ndef get_pano_lists_from_file(txtfilename, greenmonth):\n lines = open(txtfilename, \"r\")\n\n # create empty lists, to store the information of panos,and remove\n # duplicates\n panoIDLst = []\n panoDateLst = []\n panoLonLst = []\n panoLatLst = []\n\n # loop all lines in the txt files\n for line in lines:\n metadata = line.split(\" \")\n panoID = metadata[1]\n panoDate = metadata[3]\n month = panoDate[-2:]\n lon = metadata[5]\n lat = metadata[7][:-1]\n\n # in case, the longitude and latitude are invalide\n if len(lon) < 3:\n continue\n\n # only use the months of green seasons\n if month not in greenmonth:\n continue\n if panoID in panoIDLst:\n continue\n else:\n panoIDLst.append(panoID)\n panoDateLst.append(panoDate)\n panoLonLst.append(lon)\n panoLatLst.append(lat)\n\n lines.close()\n\n return panoIDLst, panoDateLst, panoLonLst, panoLatLst\n\n\n# ------------------------------Main function-------------------------------\nif __name__ == \"__main__\":\n\n import os\n import os.path\n import config\n\n os.chdir(config.root_dir)\n root = os.getcwd()\n GSVinfoRoot = os.path.join(root, \"\")\n outputTextPath = os.path.join(root, config.GVIfile['data'])\n greenmonth = config.greenmonth\n\n GreenViewComputing_ogr_6Horizon(GSVinfoRoot, outputTextPath, greenmonth)\n","sub_path":"Treepedia/3.Greenview_Calculate.py","file_name":"3.Greenview_Calculate.py","file_ext":"py","file_size_in_byte":11971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"97100488","text":"\"\"\"UserLab URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nimport logging.config\nimport os\nfrom logging.handlers import SMTPHandler\n\nfrom django.urls import path\n\nfrom userlab import views\n\nlog = logging.getLogger(\"UserLab\")\n\nurlpatterns = [\n path(\"api/health\", views.Health.as_view(), name=\"health\"),\n path(\"api/loglevel/\", views.LogLevel.as_view()),\n path(\"api/userlab//\", views.UserLab.as_view(), name=\"userlab\"),\n path(\"api/userlab/\", views.UserLab.as_view(), name=\"userlab\"),\n path(\n \"api/userlab//////\",\n views.UserLab.as_view(),\n name=\"userlab\",\n ),\n path(\n \"api/userlab/////\",\n views.UserLab.as_view(),\n name=\"userlab\",\n ),\n]\n\n\ndef setUpLogger():\n # Who should receive the emails if an error or an exception occures?\n mail_env = os.environ.get(\"MAILRECEIVER\", \"\")\n if mail_env:\n mail = mail_env.split()\n else:\n mail = []\n\n logger = logging.getLogger(\"UserLab\")\n # In trace will be sensitive information like tokens\n logging.addLevelName(5, \"TRACE\")\n\n def trace_func(self, message, *args, **kws):\n if self.isEnabledFor(5):\n # Yes, logger takes its '*args' as 'args'.\n self._log(5, message, args, **kws)\n\n logging.Logger.trace = trace_func\n mail_handler = SMTPHandler(\n mailhost=os.environ.get(\"MAILHOST\"),\n fromaddr=os.environ.get(\"MAILFROM\"),\n toaddrs=mail,\n subject=os.environ.get(\"MAILSUBJECT\"),\n )\n mail_handler.setLevel(logging.ERROR)\n mail_handler.setFormatter(\n logging.Formatter(\n \"[%(asctime)s] %(levelname)s in %(filename)s ( Line=%(lineno)d ): %(message)s\"\n )\n )\n logging.config.fileConfig(os.environ.get(\"LOGGINGCONF\"))\n logger.addHandler(mail_handler)\n\n\ndef setUp():\n print(\"setUp\")\n setUpLogger()\n log.info(\"setup\")\n\n\ntry:\n setUp()\nexcept:\n print(\"Could not setup logger\")\n","sub_path":"userlab/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"173030474","text":"# https://github.com/zutotonno/char-rnn.pytorch\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\n\nclass CharRNN(nn.Module):\n def __init__(self, input_size, hidden_size, output_size, model=\"gru\", n_layers=1,\n dropout = 0, gpu = True, batch_size = 32, chunk_len = 30, learning_rate = 0.001, optimizer = \"adam\"):\n super(CharRNN, self).__init__()\n self.model = model.lower()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n self.gpu = gpu\n self.batch_size = batch_size\n self.chunk_len = chunk_len\n self.optimizer = optimizer\n\n self.encoder = nn.Embedding(input_size, hidden_size)\n if self.model == \"gru\":\n self.rnn = nn.GRU(hidden_size, hidden_size, n_layers, dropout=dropout)\n elif self.model == \"lstm\":\n self.rnn = nn.LSTM(hidden_size, hidden_size, n_layers, dropout=dropout)\n self.decoder = nn.Linear(hidden_size, output_size)\n if self.optimizer == \"adam\":\n self.optimizer = torch.optim.Adam(self.parameters(), lr=learning_rate)\n elif self.optimizer == \"rms\":\n self.optimizer = torch.optim.RMSprop(self.parameters(), lr=learning_rate)\n self.criterion = nn.CrossEntropyLoss()\n if self.gpu:\n self.cuda()\n\n def forward(self, input, hidden):\n batch_size = input.size(0)\n encoded = self.encoder(input)\n output, hidden = self.rnn(encoded.view(1, batch_size, -1), hidden)\n output = self.decoder(output.view(batch_size, -1))\n return output, hidden\n\n def forward2(self, input, hidden):\n encoded = self.encoder(input.view(1, -1))\n output, hidden = self.rnn(encoded.view(1, 1, -1), hidden)\n output = self.decoder(output.view(1, -1))\n return output, hidden\n\n def init_hidden(self, batch_size):\n if self.model == \"lstm\":\n return (Variable(torch.zeros(self.n_layers, batch_size, self.hidden_size)),\n Variable(torch.zeros(self.n_layers, batch_size, self.hidden_size)))\n return Variable(torch.zeros(self.n_layers, batch_size, self.hidden_size))\n\n \n def train(self,inp, target, validation):\n self.zero_grad()\n loss = 0\n hidden = self.init_hidden(self.batch_size)\n if self.cuda:\n if self.model == \"gru\":\n hidden = hidden.cuda()\n else:\n hidden = (hidden[0].cuda(), hidden[1].cuda())\n for c in range(self.chunk_len):\n output, hidden = self(inp[:, c], hidden)\n loss += self.criterion(output.view(self.batch_size, -1), target[:, c]) \n ### The losses are averaged across observations for each minibatch (see doc CrossEntropyLoss)\n if not validation:\n loss.backward()\n self.optimizer.step()\n currentLoss = loss.item()/ self.chunk_len\n return currentLoss\n\n \n\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"461593174","text":"import time\nimport board\nimport simple_hcsr04\n\nsonar = simple_hcsr04.HCSR04(trigger_pin=board.D5, echo_pin=board.D6)\n\nwhile True:\n try:\n print((sonar.distance,))\n except RuntimeError:\n print(\"Retrying!\")\n time.sleep(0.1)\n","sub_path":"examples/hcsr04_simpletest.py","file_name":"hcsr04_simpletest.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"331752558","text":"class algorithm_two:\n \"\"\"\n This is a Astar_Algorithm class. It is aim to achieve A star algorithm.\n map: a dictionary storing all Nodes; Structure: {(x,y): Node, (x`,y`): Node`, ...}\n starNode: star point and it's coordination is (-73.55, 45.49)\n endNode: end point and it;s coordination is (-73.59,45.53)\n path: a list storing the result path\n \"\"\"\n\n def __init__(self, map, startNode, endNode, blocklist):\n self.map = map\n self.startNode = startNode\n self.endNode = endNode\n self.path = []\n self.blocklist = blocklist\n\n # Finding a node in open list with smallest F value.\n def sort_openList_byF(self, open_list):\n min_node = open_list[0]\n for node in open_list:\n if node.f < min_node.f:\n min_node = node\n return min_node\n\n # Updating node information, like father node, g, h and f value.\n def update_node(self, current_node, adj_node, endNode, g):\n adj_node.father = current_node\n adj_node.g = current_node.g + g\n adj_node.distance(endNode)\n adj_node.safety_parameter(current_node,self.blocklist)\n # print(adj_node.s)\n adj_node.updateF()\n\n # Using searching parent node method to get a path from end point to start point.\n def get_path(self, endNode):\n path = []\n tmp = endNode\n while tmp is not None:\n location = (tmp.point.x, tmp.point.y)\n path.append(location)\n tmp = tmp.father\n return path\n\n # A star algorithm implementation\n def a_star(self):\n if len(self.startNode.weight_list) == 0 or len(self.endNode.weight_list) == 0:\n print(\" Due to blocks, no path is found. Please change the map and try again \")\n else:\n open_list = [self.startNode]\n close_list = []\n target = (self.endNode.point.x, self.endNode.point.y)\n\n while len(open_list) != 0:\n current_node = self.sort_openList_byF(open_list) # find a node with smallest F value\n open_list.remove(current_node)\n close_list.append(current_node)\n\n if len(current_node.weight_list) != 0:\n for item in current_node.weight_list:\n if item[0] == target: # if the end point coordination in weight_list then break\n self.endNode.father = current_node\n self.endNode.g = current_node.g + item[1]\n self.endNode.distance(self.endNode)\n self.endNode.updateF()\n break\n else:\n adj_node = self.map[item[0]]\n g = item[1]\n if adj_node not in close_list: # next node cannot in close list\n if adj_node in open_list: # if next node in open list, then judge the node whether need to be updated info or not\n if adj_node.g >= current_node.g + g + current_node.s:\n adj_node.g = current_node.g + g\n adj_node.updateF()\n adj_node.father = current_node\n else: # if next node doesn't in open list and close list, then updating it's info and put it into open list\n open_list.append(adj_node)\n self.update_node(current_node, adj_node, self.endNode, g)\n cost = 0\n path = self.get_path(self.endNode)\n if self.endNode.father is None:\n print(\" Due to blocks, no path is found. Please change the map and try again \")\n return path\n else:\n cost = self.endNode.g\n print(\"Method2: COST is :\" + str(cost))\n return path\n","sub_path":"methodTwo.py","file_name":"methodTwo.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"502637976","text":"#Time Complexity : O(logn)\n#Space Complexity : O(1)\n#Did this code successfully run on Leetcode : yes\n#Any problem you faced while coding this : no\n\n\n\nclass Solution(object):\n def findMin(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l =0 \n h = len(nums)-1\n \n if nums[0] nums[h]: # check if mid is > right, i.e pivot is in right side which is basically minimum\n l = mid+1\n else:\n h = mid\n return nums[l]","sub_path":"min_sorted_rotated_array.py","file_name":"min_sorted_rotated_array.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"275554268","text":"from collections import Counter\n\n# Check if one or more words from a list of candidates qualify as anagrams for a given word\ndef detect_anagrams(word,anagram_candidates):\n\n # Validate the inputs\n if isinstance(word, basestring) and isinstance(anagram_candidates,list):\n\n # List containing the matching anagrams\n result_anagrams = []\n\n # Set the word to lower case for doing case-insensitive comparisons\n word = word.lower()\n\n # Create a Counter object for keeping track of the character counts\n # and later comparing these counts against each candidate\n character_count = Counter()\n\n # Count the number of occurrences of a character in the word\n for character in word:\n character_count[character] += 1\n\n # Iterate across the list of anagram candidates\n for candidate in anagram_candidates:\n\n # Check if this candidate is a valid anagram for the given word\n # We send a lower case version of the candidate for case insensitive comparisons\n # We also need to send a new copy of the counter, as it will get modified during the comparison\n if is_anagram(word, candidate.lower(), character_count.copy()):\n result_anagrams.append(candidate)\n\n return result_anagrams\n\n# Check if this candidate is an anagram for the word, given the count of each of its characters\ndef is_anagram(word,candidate,character_count):\n\n # If the lengths of the strings are different, don't even bother comparing them further\n if len(word) == len(candidate):\n\n # An equal string doesn't count as an anagram\n if word != candidate:\n\n # Go through the list of characters in the candidate string\n for character in candidate:\n\n # If the character is missing from the string altogether, or if all of its occurrences\n # in the original word have already been consumed, then we know that this is not\n # a valid anagram\n if character_count[character] == 0:\n return False\n\n # Keep decreasing the count for this character\n character_count[character] -= 1\n\n return True\n","sub_path":"all_data/exercism_data/python/anagram/e1493e9bd2d044139701432df4e66cdd.py","file_name":"e1493e9bd2d044139701432df4e66cdd.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"293192265","text":"\nimport networkx as nx\nimport re\n\nclass TridentDemo(object):\n def __init__(self):\n self.topology = {}\n self.current_query = ''\n self.selected_path = []\n\n def set_topology(self, g):\n self.topology = g\n self.current_query = ''\n self.selected_path = []\n\n def get_topology(self):\n return self.topology\n\n def set_attribute(self, nid, attr_name, attr_value):\n self.g.nodes[nid][attr_name] = attr_value\n\n def query(self, query):\n pattern = 'src - dst where src.id = (\\w+) and dst.id = (\\w+)'\n m = re.search(pattern, query)\n if m is not None:\n src = m.group(1)\n dst = m.group(2)\n print(src, dst)\n g = self.topology\n path = nx.shortest_path(g, src, dst)\n pairs = list(zip(path[:-1], path[1:]))\n print(pairs)\n links = list(map(lambda p: g[p[0]][p[1]], pairs))\n links = list(map(lambda d: list(d.values())[0]['id'], links))\n return links\n","sub_path":"trident/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"602823695","text":"from GitReleaseNotesGenerator.translations.commit_hash_translation import CommitHashTranslation\nfrom GitReleaseNotesGenerator.translations.branch_translation import BranchTranslation\nfrom GitReleaseNotesGenerator.translations.tag_translation import TagTranslation\nfrom GitReleaseNotesGenerator.translations.merge_translation import MergeTranslation\nfrom GitReleaseNotesGenerator.translations.translation_types import TranslationTypes\nfrom GitReleaseNotesGenerator.translators.translator import Translator\nfrom GitReleaseNotesGenerator.translators.aggregators.git_log_aggregator import GitLogAggregator\nfrom GitReleaseNotesGenerator.utils.utils import Utils\nfrom GitReleaseNotesGenerator.utils.git_utils import GitUtils\n\n\nclass GitLogTranslator(Translator):\n def __init__(self, document):\n super().__init__(document=document)\n self.translation_types = TranslationTypes\n\n def translate(self, needle=None):\n for line in self.document:\n if needle is not None and self.__found_needle(needle, line):\n break\n\n self.__filter(line, CommitHashTranslation(line).apply(), self.translation_types.TRANSLATE_HASH)\n self.__filter(line, BranchTranslation(line).apply(), self.translation_types.TRANSLATE_BRANCHES)\n self.__filter(line, TagTranslation(line).apply(), self.translation_types.TRANSLATE_TAGS)\n self.__filter(line, MergeTranslation(line).apply(), self.translation_types.TRANSLATE_MERGE)\n\n return GitLogAggregator(self.log).aggregate()\n\n def __filter(self, line: str, translation: str, translated: TranslationTypes):\n if line != translation:\n self.log.put({translated: translation})\n\n def __found_needle(self, needle, line) -> bool:\n if Utils().is_sha1(needle) is True:\n haystack = CommitHashTranslation(line).apply()\n needle = GitUtils().get_short_sha(needle)\n else:\n haystack = TagTranslation(line).apply()\n\n return True if haystack == needle and needle is not None else False\n","sub_path":"GitReleaseNotesGenerator/translators/git_log_translator.py","file_name":"git_log_translator.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"153002032","text":"#!/usr/bin/python3.6\nclass DefenseGrid:\n\tdef __init__(self,owner):\n\t\tself.owner=owner\n\t\tself.lifespan=7\n\t\tself.frontline=False\n\t\tself.cooldown=1\n\t\tself.defaultBlocking=True\n\t\tself.health=7\n\t\tself.fragile=False\n\t\tself.attack=0\n\t\tself.startTurnDict={\n\n\t\t}\n\n\tdef __str__(self):\n\t\treturn \"Defense Grid\"\n\n\tdef startTurn(self):\n\t\tfor i in range(0,1):\n\t\t\tself.owner.addUnit(\"Drone,1,-1\")\n\n\t\treturn True\n\n\tdef info(self): \n\t\treturn {\n\t\t\"lifespan\":self.lifespan,\n\t\t\"health\":self.health}\n\ndef DefenseGridCost():\n\tbuyCostDict={\n\t\t\"gold\":16,\n\t\t\"blue\":3\n\t}\n\t\n\treturn buyCostDict,False,1,[],\"Defense Grid\"","sub_path":"units/DefenseGrid.py","file_name":"DefenseGrid.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"504615477","text":"import base64\nfrom wsgiref.simple_server import make_server\n\n\ndef application(environ, start_response):\n path = environ['PATH_INFO']\n method = environ['REQUEST_METHOD']\n try:\n import boto3\n ssm_client = boto3.client('ssm', region_name='us-east-2')\n\n response = ssm_client.get_parameter(\n Name=\"TestSecretParameter\",\n WithDecryption=True\n )['Parameter']['Value']\n\n except Exception as e:\n response = str(e)\n\n status = '200 OK'\n headers = [('Content-type', 'text/html')]\n\n start_response(status, headers)\n return [response]\n\n\nif __name__ == '__main__':\n httpd = make_server('', 8000, application)\n print(\"Serving on port 8000...\")\n httpd.serve_forever()\n","sub_path":"awssmps/beanstalk-python/python-v1/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"305881322","text":"import unittest\nimport paramunittest\nimport readConfig as readConfig\nfrom common import Log as Log\nfrom common import common\nfrom common import configHttp as ConfigHttp\nfrom common import businessCommon\n\naddAddress_xls = common.get_xls(\"userCase.xlsx\", \"addAddress\")\nlocalReadConfig = readConfig.ReadConfig()\nconfigHttp = ConfigHttp.ConfigHttp()\n\n\n@paramunittest.parametrized(*addAddress_xls)\nclass AddAddress(unittest.TestCase):\n def setParameters(self, description, sex, fname, lname, father_name, english_name, tel, standby_tel, address1, address2, city, state, postcode, country_id, tax_number, company, fax, is_default, street, msg, code):\n \"\"\"\n set params\n :param description:\n :param sex:\n :param fname:\n :param lname:\n :param father_name:\n :param english_name:\n :param tel:\n :param standby_tel:\n :param address1:\n :param address2:\n :param city:\n :param state:\n :param postcode:\n :param country_id:\n :param tax_number:\n :param company:\n :param fax:\n :param is_default:\n :param street:\n :param msg:\n :param code:\n :return:\n \"\"\"\n self.description = str(description)\n self.sex = str(sex)\n self.fname = str(fname)\n self.lname = str(lname)\n self.father_name = str(father_name)\n self.english_name = str(english_name)\n self.tel = tel\n self.standby_tel = str(standby_tel)\n self.address1 = str(address1)\n self.address2 = str(address2)\n self.city = str(city)\n self.state = str(state)\n self.postcode = str(postcode)\n self.country_id = int(country_id)\n self.tax_number = str(tax_number)\n self.company = str(company)\n self.fax = str(fax)\n self.is_default = str(is_default)\n self.street = str(street)\n self.code = str(code)\n self.msg = str(msg)\n self.info = None\n\n def description(self):\n \"\"\"\n\n :return:\n \"\"\"\n self.description\n\n def setUp(self):\n \"\"\"\n\n :return:\n \"\"\"\n self.log = Log.MyLog.get_log()\n self.logger = self.log.get_logger()\n # self.login_token = businessCommon.login()\n\n def testAddAddress(self):\n \"\"\"\n test body\n :return:\n \"\"\"\n # set url\n self.url = common.get_url_from_xml('addAddress')\n configHttp.set_url(self.url)\n\n # get token\n self.token = \"20253215139_5a2a0b68326238.31546893_653b9e2a804dd003fba87c7316a15019150d19df\"\n\n # set headers\n header = {\"token\": str(self.token),\n \"SiteUID\": \"rwm\"}\n configHttp.set_headers(header)\n\n # set data\n if self.country_id == 74 or self.country_id == 198:\n self.postcode = int(self.postcode)\n data = {\"sex\": self.sex,\n \"fname\": self.fname,\n \"lname\": self.lname,\n \"father_name\": self.father_name,\n \"english_name\": self.english_name,\n \"tel\": self.tel,\n \"standby_tel\": self.standby_tel,\n \"address1\": self.address1,\n \"address2\": self.address2,\n \"city\": self.city,\n \"state\": self.state,\n \"postcode\": self.postcode,\n \"country_id\": self.country_id,\n \"tax_number\": self.tax_number,\n \"company\": self.company,\n \"fax\": self.fax,\n \"is_default\": self.is_default,\n \"street\": self.street}\n configHttp.set_data(data)\n\n # test interface\n self.return_json = configHttp.post()\n\n # check result\n self.checkResult()\n\n def tearDown(self):\n \"\"\"\n\n :return:\n \"\"\"\n\n # logout\n # businessCommon.logout(self.token)\n self.log.build_case_line(self.description, self.info['code'], self.info['msg'])\n\n def checkResult(self):\n \"\"\"\n check test result\n :return:\n \"\"\"\n self.info = self.return_json.json()\n common.show_return_msg(self.return_json)\n\n if self.code == '0':\n self.assertEqual(self.info['code'], self.code)\n self.assertEqual(self.info['msg'], self.msg)\n self.assertEqual(self.sex, common.get_value_from_return_json(self.info, 'address', 'sex'))\n self.assertEqual(self.fname, common.get_value_from_return_json(self.info, 'address', 'fname'))\n if self.country_id == 38 or self.country_id == 137:\n self.assertEqual(\"\", common.get_value_from_return_json(self.info, 'address', 'lname'))\n else:\n self.assertEqual(self.lname, common.get_value_from_return_json(self.info, 'address', 'lname'))\n if self.country_id == 178:\n self.assertEqual(self.father_name, common.get_value_from_return_json(self.info, 'address', 'fatherName'))\n else:\n self.assertEqual(\"\", common.get_value_from_return_json(self.info, 'address', 'fatherName'))\n if self.country_id == 74 or self.country_id == 198:\n self.assertEqual(str(self.postcode), common.get_value_from_return_json(self.info, 'address', 'postcode'))\n else:\n self.assertEqual(self.postcode, common.get_value_from_return_json(self.info, 'address', 'postcode'))\n if self.country_id == 30:\n self.assertEqual(self.tax_number, common.get_value_from_return_json(self.info, 'address', 'taxNumber'))\n self.assertEqual(str(self.tel), common.get_value_from_return_json(self.info, 'address', 'tel'))\n self.assertEqual(self.address1, common.get_value_from_return_json(self.info, 'address', 'address1'))\n self.assertEqual(self.city, common.get_value_from_return_json(self.info, 'address', 'city'))\n self.assertEqual(self.state, common.get_value_from_return_json(self.info, 'address', 'state'))\n self.assertEqual(str(self.country_id), common.get_value_from_return_json(self.info, 'address', 'countryId'))\n\n else:\n self.assertEqual(self.info['code'], self.code)\n self.assertEqual(self.info['msg'], self.msg)\n","sub_path":"testCase/user/testAddAddress.py","file_name":"testAddAddress.py","file_ext":"py","file_size_in_byte":6282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"550139690","text":"# -*- coding: utf-8 -*-\n\"\"\"\n test_issue15\n ~~~~~~~~~~~~\n\n Test order of bibliography entries when using an unsorted style.\n\"\"\"\n\nfrom six import StringIO\nimport os.path\nimport re\n\nfrom util import path, with_app\n\nsrcdir = path(__file__).parent.joinpath('issue15').abspath()\nwarnfile = StringIO()\n\n\ndef teardown_module():\n (srcdir / '_build').rmtree(True)\n\n\n@with_app(srcdir=srcdir, warningiserror=True)\ndef test_duplicate_label(app):\n app.builder.build_all()\n with open(os.path.join(app.outdir, \"contents.html\")) as stream:\n assert re.search(\n '.*Test 1.* .*.*Test 2.* ',\n stream.read(), re.DOTALL)\n","sub_path":"test/test_issue15.py","file_name":"test_issue15.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"522639757","text":"import random\n\n\n# Suppose that you need to hire a new office assistant\n# You have N candidates and you need to interview them one by one daily\n# After each interview, if the candidate is better than the current assistant\n# you decide to hire the newly interviewed candidate\n# Interviewing has a low cost, whereas hiring is expensive since on each hiring\n# you need to give an employment package\n\n\ndef interview(candidate):\n return candidate ** 2\n\n\ndef hire(candidate):\n return candidate\n\n\n# if the candidates come in an increasing order\n# the overall cost would be very expensive because\n# you are basically hiring a new assistant after each interview\ndef hire_assistant(candidates):\n cost = 0\n best = 0\n for candidate in candidates:\n feedback = interview(candidate)\n if feedback > best:\n employment_package = hire(candidate)\n cost += employment_package\n best = feedback\n return cost\n\n\n# Candidates are hired approx. lnn times:\n# the probability that ith candidate will be hired: 1 / i\n# the overall expected hires:\n# E[hires] = 1/1 + 1/2 + 1/3 + ... + 1/n ≈ lnn\ndef randomized_hire_assistant(candidates):\n # randomly permute the candidates\n random.shuffle(candidates)\n return hire_assistant(candidates)\n\n\ncandidates = []\nfor i in range(10, 100):\n candidates.append(i)\noverall_cost = hire_assistant(candidates)\nprint(\"Overall cost = \", overall_cost)\n\noverall_cost = randomized_hire_assistant(candidates)\nprint(\"Overall cost = \", overall_cost)\n","sub_path":"Ch05. Probabilistic Analysis and Randomized Algorithms/hire_assistant.py","file_name":"hire_assistant.py","file_ext":"py","file_size_in_byte":1522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"411624104","text":"from pymongo import MongoClient\n\nclass Mongo():\n\tdef __init__(self, dbAddress, dbName):\n\t\tself.dbAddress = dbAddress\n\t\tself.dbName = dbName\n\t\tself.db = None\n\t\tself.connect()\n\n\tdef connect(self):\n\t\ttry:\n\t\t\tclient = MongoClient(self.dbAddress)\n\t\t\tself.db = client[self.dbName]\n\t\texcept (pymongo.errors.ConnectionFailure):\n\t\t\tprint(\"\\nCould not connect to db\")\n\n\n\tdef insertOne(self, collectionName, document):\n\t\ttry:\n\t\t\tresult = self.db[collectionName].insert_one(document)\n\t\t\tprint(\"\\nUser Inserted! -> {0}\".format(result.inserted_id))\n\t\t\treturn result\n\t\texcept:\n\t\t\tprint(\"\\nCould not insert in database\")\n\t\t","sub_path":"utils/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"148420287","text":"from setuptools import setup, find_packages\nfrom os import path\n\nchangelog_header = \"\"\"\nChangelog\n=========\n\n\"\"\"\n\ndesc_file = path.join(path.dirname(__file__), \"README.rst\")\nchangelog_file = path.join(path.dirname(__file__), \"CHANGELOG.rst\")\ndescription = (open(desc_file).read()\n + changelog_header\n + open(changelog_file).read())\n\nversion = '0.1'\n\nsetup(\n name='pygments-cl-repl',\n version=version,\n description=\"Pygments lexer for Common Lisp REPL\",\n long_description=description,\n license='GPLv3+',\n author='Russell Sim',\n author_email='russell.sim@gmail.com',\n url='https://github.com/russell/pygments-cl-repl',\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Plugins',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n test_suite='pygments_cl_repl.test.suite',\n install_requires=[\n # -*- Extra requirements: -*-\n 'pygments',\n ],\n entry_points={\n 'pygments.lexers':\n 'common-lisp-repl=pygments_cl_repl:CommonLispREPLLexer'}\n)\n","sub_path":"pypi_install_script/pygments-cl-repl-0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"563218994","text":"\n# ///// possible visualizations ///////// \ndef graph_distribution():\n x = np.arange(0,2000)/200.\n y = np.zeros(2000)\n for i in range(2000):\n y[i] = F_star(x[i])\n plt.plot (x, y)\n plt.show()\n\ndef graph_first_step_works(ind):\n p = np.arange(-20, 20)/20.\n y = np.zeros(40)\n yy = np.zeros(40)\n v = gammas[ind] #np.ones(n)/np.sqrt(n)\n vgamma = sum(a * v) * np.sqrt(n)\n coeff = first_step(v)\n for i in range(40):\n #y[i] = f_changed(p[i] * v, gp, gq)\n #yy[i] = polynom_normed(coeff, p[i]/np.sqrt(n))\n y[i] = phi(vgamma * p[i], gp, gq)\n yy[i] = polynom_normed(coeff, p[i])\n plt.plot(p, y)\n plt.plot(p, yy)\n plt.show()\n#////////////////////////////////////////////////////////\n","sub_path":"graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"179222822","text":"import pygame, random\nimport pygame, sys\nfrom pygame.locals import *\nfrom input_mech import *\nfrom sprite_classes import *\nfrom random import randint\nfrom spawn_handler import *\nfrom inventory_mech import *\n\nclass GUI:\n def load(self):\n self.gSelected = \"Home\"\n self.gHome = GUI_Button()\n self.gHome.lGui('sGui_hotbar.png', 0, 350, 50, 50, 0, 2, 1, 2)\n self.gMove = GUI_Button()\n self.gMove.lGui('sGui_hotbar.png', 60, 350, 50, 50, 0, 0, 1, 0)\n self.gItem = GUI_Button()\n self.gItem.lGui('sGui_hotbar.png', 120, 350, 50, 50, 0, 1, 1, 1)\n self.petamount = 1\n self.foodamount = 1\n self.pD = False\n \n def update(self, mouseDown, mouseX, mouseY):\n self.gHome.uGui(mouseDown, mouseX, mouseY)\n self.gMove.uGui(mouseDown, mouseX, mouseY)\n self.gItem.uGui(mouseDown, mouseX, mouseY)\n if self.gHome.clicked:\n self.gSelected = \"Home\"\n if self.petamount > 0:\n self.petamount = self.petamount - 1\n CreateCreatures()\n if self.gMove.clicked:\n self.gSelected = \"Move\"\n if self.foodamount > 0:\n self.foodamount = self.foodamount - 1\n CreateFoodItem(0)\n else:\n self.foodamount = 1\n \n def draw(self, ds):\n self.gHome.dGui(ds)\n self.gMove.dGui(ds)\n self.gItem.dGui(ds)\n","sub_path":"Python Game Development/gui_events.py","file_name":"gui_events.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"485903121","text":"from odoo import api, fields, models\nclass PlmConfigSettings(models.TransientModel):\n _inherit = 'res.config.settings'\n\n can_go_back = fields.Boolean('can go back',default=False)\n\n def set_values(self):\n res=super(PlmConfigSettings, self).set_values()\n fn=self.env['ir.config_parameter'].set_param\n fn('weOdooErpPlm.can_go_back',self.can_go_back)\n return res\n @api.model\n def get_values(self):\n res = super(PlmConfigSettings, self).get_values()\n fn = self.env['ir.config_parameter'].sudo().get_param\n can_go_back=fn('weOdooErpPlm.can_go_back')\n res.update({'can_go_back':can_go_back})\n return res","sub_path":"models/plm_settings.py","file_name":"plm_settings.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"435140000","text":"import requests\nimport codecs\nimport time\nfrom bs4 import BeautifulSoup as BS\n\nsession = requests.Session()\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:47.0) Gecko/20100101 '\n 'Firefox/47.0', 'Accept': 'text/html,application/xhtml+xml,'\n 'application/xml;q=0.9,*/*;q=0.8'}\n\nbase_url = 'https://jobs.dou.ua/vacancies/?city=%D0%9A%D0%B8%D1%97%D0%B2&' \\\n 'category=Python'\n\njobs = []\nurls = []\n\nurls.append(base_url)\n\nfor url in urls:\n time.sleep(1)\n req = session.get(url, headers=headers)\n if req.status_code == 200:\n bsObj = BS(req.content, \"html.parser\")\n div = bsObj.find('div', attrs={'id': 'vacancyListId'})\n\n if div:\n li_list = div.find_all('li', attrs={'class': 'l-vacancy'})\n for li in li_list:\n a = li.find('a', attrs={'class': 'vt'})\n title = a.text\n href = a['href']\n short = \"No description\"\n company = \"No name\"\n div = li.find('div', attrs={'class': 'sh-info'})\n short = div.text\n name = li.find('img', attrs={'class': 'f-i'})\n company = name.text\n jobs.append({'href': href,\n 'title': title,\n 'descript': short,\n 'company': company})\ntemplate = ' ' \\\n ' '\nend = ' '\ncontent = ' dou.ua '\n\nfor job in jobs:\n content += '{title} ' \\\n '{descript}' \\\n '
{company}
'.format(**job)\n content += ' '\n\ndata = template + content + end\n\nhandle = codecs.open('jobs.html', \"w\", \"utf-8\")\nhandle.write(str(data))\nhandle.close()\n","sub_path":"dou.py","file_name":"dou.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"23042737","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 18 13:04:17 2019\n@author: shimul\n\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\n\ndataset = pd.read_csv(\n '/mnt/1CD23A07D239E5A4/Bit_Factor/Machine_Learning/Projectml02/Machine Learning A-Z/Machine Learning A-Z Template Folder/Part 2 - Regression/Section 4 - Simple Linear Regression/Salary_Data.csv')\nX = dataset.iloc[:, :-1].values\nY = dataset.iloc[:, 1].values\n\n# Splitting the dataset into the Trainingset and Test set\nX_train, X_test, Y_train, Y_test = train_test_split(\n X, Y, test_size=1/3, random_state=0)\n\n#from sklearn.preprocessing import Normalizer\n# sc_x=Normalizer()\n# X_train=sc_x.fit_transform(X_train)\n# X_test=sc_x.fit_transform(X_test)\n# Y_train=sc_x.fit_transform(Y_train)\n#\n# Fitting Simple Linear Regression to the training set\nLinearRegressor = LinearRegression()\nLinearRegressor.fit(X_train, Y_train)\nyPrediction = LinearRegressor.predict(X_test)\n\nplt.scatter(X_train, Y_train, color='green')\nplt.plot(X_train, LinearRegressor.predict(X_train), color='red')\nplt.title('Salary vs Experience (Training set)')\nplt.xlabel('Years of Experience')\nplt.ylabel('Salary')\nplt.show()\n\n","sub_path":"Code/Linear_Regression.py","file_name":"Linear_Regression.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"615415034","text":"\"\"\"\nblaze run -c opt //experimental/users/jietan/ARS:eval_ars -- \\\n--logdir=/cns/ij-d/home/jietan/experiment/ARS/ars_react_nr01.191950338.191950550/ \\\n--checkpoint=lin_policy_plus_990.npz \\\n--num_rollouts=10\n\"\"\"\n\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os, inspect\nimport time\n\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nos.sys.path.insert(0,currentdir)\n\nfrom absl import app\nfrom absl import flags\n\nimport pdb\nimport os\nimport numpy as np\nimport gym\nimport config_ars\nimport utility\nimport policies\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_string('logdir', None, 'The path of the checkpoint.')\nflags.DEFINE_string('checkpoint', None, 'The file name of the checkpoint.')\nflags.DEFINE_integer('num_rollouts', 1, 'The number of rollouts.')\n\n\ndef main(argv):\n del argv # Unused.\n\n print('loading and building expert policy')\n checkpoint_file = os.path.join(FLAGS.logdir, FLAGS.checkpoint)\n lin_policy = np.load(checkpoint_file, encoding='bytes')\n lin_policy = lin_policy.items()[0][1]\n\n M = lin_policy[0]\n # mean and std of state vectors estimated online by ARS.\n mean = lin_policy[1]\n std = lin_policy[2]\n\n config = utility.load_config(FLAGS.logdir)\n print(\"config=\",config)\n env = config['env'](hard_reset=True, render=True)\n ob_dim = env.observation_space.shape[0]\n ac_dim = env.action_space.shape[0]\n\n # set policy parameters. Possible filters: 'MeanStdFilter' for v2, 'NoFilter' for v1.\n policy_params = {\n 'type': 'linear',\n 'ob_filter': config['filter'],\n 'ob_dim': ob_dim,\n 'ac_dim': ac_dim,\n \"weights\": M,\n \"mean\": mean,\n \"std\": std,\n }\n policy = policies.LinearPolicy(policy_params, update_filter=False)\n returns = []\n observations = []\n actions = []\n for i in range(FLAGS.num_rollouts):\n print('iter', i)\n obs = env.reset()\n done = False\n totalr = 0.\n steps = 0\n while not done:\n action = policy.act(obs)\n observations.append(obs)\n actions.append(action)\n\n obs, r, done, _ = env.step(action)\n time.sleep(1./100.)\n totalr += r\n steps += 1\n if steps % 100 == 0:\n print('%i/%i' % (steps, config['rollout_length']))\n if steps >= config['rollout_length']:\n break\n returns.append(totalr)\n\n print('returns', returns)\n print('mean return', np.mean(returns))\n print('std of return', np.std(returns))\n\n\nif __name__ == '__main__':\n flags.mark_flag_as_required('logdir')\n flags.mark_flag_as_required('checkpoint')\n app.run(main)\n","sub_path":"soccer-rl/pybullet/gym/pybullet_envs/ARS/eval_ars.py","file_name":"eval_ars.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"415751080","text":"#!env/bin/python3\n\nimport yaml\nimport sys\nimport json\nimport datetime\nfrom serverboards_google import get_service, async_execute\nfrom urllib.parse import urlparse\nfrom pcolor import printc\nimport serverboards_aio as serverboards\n\n\ndef get_spreadsheet_id(url):\n if url.startswith(\"https://\"):\n id = urlparse(url).path.split('/')[3]\n return id\n return url\n\n\n@serverboards.rpc_method(\"schema_sheets\")\n@serverboards.cache_ttl(60)\nasync def schema_sheets(config, table=None):\n config = config.get(\"config\", config)\n sheets = await get_service(config[\"service_id\"], \"sheets\", \"v4\")\n spreadsheetid = get_spreadsheet_id(config[\"spreadsheet\"])\n # printc(\"Real id is \", spreadsheetid)\n if not table:\n data = await async_execute(sheets.spreadsheets().get(spreadsheetId=spreadsheetid))\n tables = [x[\"properties\"][\"title\"].replace(\" \", \"_\") for x in data.get(\"sheets\", [])]\n return tables\n data = await async_execute(sheets.spreadsheets().values().get(spreadsheetId=spreadsheetid, range=(\"%s!A1:Z1\" % table)))\n # printc(data)\n if not 'values' in data: # bad formed\n return {\n \"columns\": []\n }\n return {\n \"columns\": data[\"values\"][0]\n }\n\n\n@serverboards.rpc_method(\"extractor_sheets\")\n@serverboards.cache_ttl(30)\nasync def extractor_sheets(config, table, quals, columns):\n config = config.get(\"config\", config)\n sheets = await get_service(config[\"service_id\"], \"sheets\", \"v4\")\n spreadsheetid = get_spreadsheet_id(config[\"spreadsheet\"])\n data = await async_execute(sheets.spreadsheets().values().get(spreadsheetId=spreadsheetid, range=(\"%s!A1:Z10000\" % table)))\n return {\n \"columns\": data[\"values\"][0],\n \"rows\": data[\"values\"][1:],\n }\n\n\n@serverboards.rpc_method\nasync def insert_sheets(config, table, columns, values):\n config = config.get(\"config\", config)\n sheets = await get_service(config[\"service_id\"], \"sheets\", \"v4\")\n spreadsheetid = get_spreadsheet_id(config[\"spreadsheet\"])\n\n rcolumns = await async_execute(sheets.spreadsheets().values().get(spreadsheetId=spreadsheetid, range=(\"%s!A1:Z1\" % table)))\n if not 'values' in rcolumns: # bad formed\n raise Exception(\"bad-formed-table\")\n else:\n rcolumns = rcolumns[\"values\"][0]\n\n # This is an array with the position on the final table of original columns\n orderedcols = [None] * len(rcolumns)\n for (i,c) in enumerate(columns):\n try:\n n = rcolumns.index(c)\n orderedcols[n] = i\n except:\n pass\n # printc(rcolumns, orderedcols)\n\n # we move them there\n ordered_values = []\n for row in values:\n r = [''] * len(rcolumns)\n for n, pos in enumerate(orderedcols):\n if pos is not None:\n v = row[pos]\n r[n] = v\n ordered_values.append(r)\n\n data = await async_execute(\n sheets.\n spreadsheets().\n values().\n append(\n spreadsheetId=spreadsheetid,\n range=(\"%s!A1:Z10000\" % table),\n body={\"values\": ordered_values},\n valueInputOption=\"RAW\"\n )\n )\n # printc(data)\n return {\"inserted\": len(values)}\n\n@serverboards.rpc_method\nasync def append_to_sheet(service_id, spreadsheet, table, data, *args, **kwargs):\n table = table or \"Sheet1\"\n printc(\"Append \", service_id, spreadsheet, data, color=\"yellow\")\n\n data = yaml.load(data)\n columns = list(data.keys())\n values = []\n for v in data.values():\n if v == \"NOW\":\n values.append(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\"))\n else:\n values.append(v)\n\n await insert_sheets(\n {\"service_id\": service_id, \"spreadsheet\": spreadsheet},\n table, columns, [values]\n )\n return True\n\n\nasync def test():\n mock_data = yaml.load(open(\"mock.yaml\"))\n config = mock_data[\"config\"]\n # res = await schema_sheets(config)\n # printc(\"tables\", res)\n #\n # res = await schema_sheets(config, \"Sheet1\")\n # printc(\"columns Sheet1\", res)\n #\n # res = await extractor_sheets(config, \"Sheet1\", [], [])\n # printc(\"Result\", json.dumps(res, indent=2))\n\n res = await insert_sheets(config, \"Sheet1\", [\"email\", \"name\"], [[\"Test email\", \"name test\"]])\n printc(\"Result\", json.dumps(res, indent=2))\n\n printc(\"ALL OK\", color=\"green\")\n sys.exit(0)\n\nif __name__ == '__main__':\n argv = sys.argv[1:]\n if argv and argv[0] == \"test\":\n import os\n if os.path.exists(\"extramock.yaml\"):\n mock_data = yaml.load(open(\"extramock.yaml\"))\n else:\n mock_data = yaml.load(open(\"mock.yaml\"))\n serverboards.test_mode(test, mock_data)\n printc(\"Failure\", color=\"red\")\n sys.exit(1)\n\n serverboards.loop()\n","sub_path":"google-drive/sheets.py","file_name":"sheets.py","file_ext":"py","file_size_in_byte":4823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"579637405","text":"import os\nimport pygame\nimport sys\nimport random\nimport time\n\n\ndef start_screen():\n intro_text = [\"ЗАСТАВКА\", \"\",\n \"Правила игры\",\n \"Выигрывайте\",\n \"Если проиграите, случится проигрыш\"]\n\n fon = pygame.transform.scale(load_image('fon.png', (W, H)), (W, H))\n screen.blit(fon, (0, 0))\n font = pygame.font.Font(None, 30)\n text_coord = 50\n for line in intro_text:\n string_rendered = font.render(line, 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n text_coord += 10\n intro_rect.top = text_coord\n intro_rect.x = 10\n text_coord += intro_rect.height\n screen.blit(string_rendered, intro_rect)\n\n a = 1\n while a:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n a = 0\n\n elif event.type == pygame.KEYDOWN or \\\n event.type == pygame.MOUSEBUTTONDOWN:\n return # начинаем игру\n pygame.display.flip()\n clock.tick(60)\n\n\ndef end_screen():\n intro_text = [\"ХАА ХАХАХАХАХ ВЫ ПРОИГРАЛИ !!!!!\", \"\",\n \"ВЫ ПРОИГРАЛИ ХАХАХАХАХ\",\n \"В СЛЕДУЮЩИЙ РАЗ НЕ ПРОИГРЫВАЙТЕ ХАХАХАХАХАХ\",\n \"Если проиграите еще раз, случится очередной проигрыш\"]\n\n fon = pygame.transform.scale(load_image('fon.png', (W, H)), (W, H))\n screen.blit(fon, (0, 0))\n font = pygame.font.Font(None, 30)\n text_coord = 50\n pygame.mixer.music.load('audio/end.mp3')\n pygame.mixer.music.play()\n for line in intro_text:\n string_rendered = font.render(line, 1, pygame.Color('black'))\n intro_rect = string_rendered.get_rect()\n text_coord += 10\n intro_rect.top = text_coord\n intro_rect.x = 10\n text_coord += intro_rect.height\n screen.blit(string_rendered, intro_rect)\n\n a = 1\n while a:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n a = 0\n pygame.display.flip()\n clock.tick(60)\n\n\ndef new_game(slozn):\n global sl\n hero = Hero(hero_sprite, 300, 520)\n for i in range(4):\n Building(buildings_sprites, 150 * i + 20, 460)\n for i in range(6 * int(slozn / 2)):\n for j in range(6):\n Enemy(enemy_sprites, 41 * i, 41 * j)\n while True:\n for i in pygame.event.get():\n if i.type == pygame.QUIT:\n sys.exit()\n if i.type == pygame.KEYDOWN:\n if i.key == pygame.K_RIGHT:\n hero_sprite.update(n=10)\n if i.key == pygame.K_LEFT:\n hero_sprite.update(n=-10)\n if i.key == pygame.K_SPACE and len(hero_bullets_sprites) < 1:\n HeroBullet(hero_bullets_sprites, hero.rect.x, hero.rect.y)\n screen.fill((0, 0, 0))\n hero_sprite.draw(screen)\n hero_bullets_sprites.draw(screen)\n hero_bullets_sprites.update()\n enemy_sprites.draw(screen)\n enemy_sprites.update()\n enemy_bullets_sprites.draw(screen)\n enemy_bullets_sprites.update()\n buildings_sprites.draw(screen)\n buildings_sprites.update()\n bang_sprites.draw(screen)\n bang_sprites.update()\n hero_sprite.update(n=0)\n font = pygame.font.Font(None, 25)\n text = font.render(f\"Your lives:{hero.health - 1}\", True, (100, 255, 100))\n text1 = font.render(f\"Hard:{slozn - 1}\", True, (100, 255, 100))\n screen.blit(text, (10, 520))\n screen.blit(text1, (10, 560))\n if len(enemy_sprites) == 0:\n return\n if len(buildings_sprites) == 0 or hero.health <= 0:\n sl = 0 - sl\n return\n for i in enemy_sprites:\n if i.rect.y > 600:\n sl = 0 - sl\n return\n pygame.display.update()\n fps = 720 / (len(enemy_sprites) + 1)\n\n clock.tick(fps)\n\n\ndef load_image(name, size, colorkey=None):\n fullname = os.path.join('img', name)\n if not os.path.isfile(fullname):\n print(f\"Файл с изображением '{fullname}' не найден\")\n sys.exit()\n image = pygame.image.load(fullname)\n image = pygame.transform.scale(image, size)\n if colorkey is not None:\n image = image.convert()\n if colorkey == -1:\n colorkey = image.get_at((0, 0))\n image.set_colorkey(colorkey)\n return image\n\n\nclass Enemy(pygame.sprite.Sprite):\n image = load_image(\"enemy.png\", (30, 30))\n image2 = load_image(\"enemy1.png\", (30, 30))\n\n def __init__(self, group, x, y):\n super().__init__(group)\n self.image = Enemy.image\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.o = 0\n self.k = 200\n\n def update(self, *args):\n\n if self.o < self.k:\n n = 1\n self.k = 200\n\n else:\n n = -1\n self.k = 0\n if n > 0:\n self.image = Enemy.image2\n else:\n self.image = Enemy.image\n if self.o == 0 or self.o == 200:\n self.rect = self.rect.move(n, 30)\n else:\n self.rect = self.rect.move(n, 0)\n self.o += n\n if pygame.sprite.spritecollideany(self, hero_bullets_sprites):\n self.kill()\n pygame.mixer.music.load('audio/pau.mp3')\n pygame.mixer.music.play()\n pygame.sprite.spritecollideany(self, hero_bullets_sprites).kill()\n Bang(bang_sprites, self.rect.x, self.rect.y)\n if random.randint(0, 2400 / sl) == 5:\n EnemyBullet(enemy_bullets_sprites, self.rect.x, self.rect.y)\n\n\nclass Hero(pygame.sprite.Sprite):\n image = load_image(\"hero.png\", (60, 60))\n\n def __init__(self, group, x, y):\n super().__init__(group)\n self.image = Hero.image\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.health = 4\n\n def update(self, *args, n):\n self.rect = self.rect.move(n, 0)\n if pygame.sprite.spritecollideany(self, enemy_bullets_sprites):\n self.health -= 1\n self.rect.x = 300\n self.rect.y = 520\n\n\nclass HeroBullet(pygame.sprite.Sprite):\n image = load_image(\"bullet1.png\", (5, 20))\n\n def __init__(self, group, x, y):\n super().__init__(group)\n pygame.mixer.music.load('audio/piu.mp3')\n pygame.mixer.music.play()\n self.image = HeroBullet.image\n self.rect = self.image.get_rect()\n self.rect.x = x + 20\n self.rect.y = y\n\n def update(self, *args):\n self.rect = self.rect.move(0, -20)\n if self.rect.y < 0:\n self.kill()\n if pygame.sprite.spritecollideany(self, enemy_bullets_sprites):\n self.kill()\n pygame.sprite.spritecollideany(self, enemy_bullets_sprites).kill()\n\n\nclass Bang(pygame.sprite.Sprite):\n image = load_image(\"babah.png\", (30, 30))\n\n def __init__(self, group, x, y):\n super().__init__(group)\n self.image = Bang.image\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.n = 0\n\n def update(self, *args):\n self.n += 1\n if self.n == 10:\n self.kill()\n\n\nclass EnemyBullet(HeroBullet):\n def update(self, *args):\n self.rect = self.rect.move(0, 20)\n\n\nclass Building(pygame.sprite.Sprite):\n image = load_image(\"building0.png\", (50, 50))\n\n def __init__(self, group, x, y):\n super().__init__(group)\n self.image = Building.image\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y\n self.health = 0\n\n def update(self, *args):\n if pygame.sprite.spritecollideany(self, enemy_sprites):\n pygame.mixer.music.load('audio/babah.mp3')\n pygame.mixer.music.play()\n pygame.sprite.spritecollideany(self, enemy_sprites).kill()\n self.kill()\n if pygame.sprite.spritecollideany(self, hero_bullets_sprites or enemy_bullets_sprites):\n self.health += 1\n if self.health == 5:\n self.kill()\n pygame.mixer.music.load('audio/babah.mp3')\n pygame.mixer.music.play()\n else:\n pygame.sprite.spritecollideany(self, hero_bullets_sprites or enemy_bullets_sprites).kill()\n self.image = load_image(\"building\" + str(self.health) + \".png\", (50, 50))\n pygame.mixer.music.load('audio/babah.mp3')\n pygame.mixer.music.play()\n\n\nif __name__ == '__main__':\n W = 600\n H = 600\n pygame.init()\n pygame.mixer.init()\n screen = pygame.display.set_mode((W, H))\n\n clock = pygame.time.Clock()\n start_screen()\n hero_bullets_sprites = pygame.sprite.Group()\n enemy_sprites = pygame.sprite.Group()\n bang_sprites = pygame.sprite.Group()\n enemy_bullets_sprites = pygame.sprite.Group()\n hero_sprite = pygame.sprite.Group()\n\n buildings_sprites = pygame.sprite.Group()\n\n sl = 1\n while sl != 0:\n new_game(sl)\n sl += 1\n hero_bullets_sprites.empty()\n enemy_sprites.empty()\n bang_sprites.empty()\n enemy_bullets_sprites.empty()\n hero_sprite.empty()\n\n buildings_sprites.empty()\n end_screen()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"637933309","text":"import random\n\ndef calc_bmi(h, w):\n bmi = w / (h/100) ** 2\n if bmi < 18.5: return 'thin'\n if bmi < 25: return 'normal'\n return 'fat'\n\ndef main():\n cnt = {'thin':0, 'normal':0, 'fat':0}\n\n with open('bmi.csv', 'w', encoding='utf-8') as fp:\n fp.write('height,weight,label\\r\\n')\n\n for i in range(20000):\n h = random.randint(120,200)\n w = random.randint(35,80)\n label = calc_bmi(h,w)\n cnt[label] += 1\n fp.write(\"{0},{1},{2}\\r\\n\".format(h,w,label))\n\n print('ok', cnt)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bmi/bmi-create.py","file_name":"bmi-create.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"32133043","text":"import datetime\nimport pandas as pd\nimport numpy as np\nimport random\n\nfrom scipy.optimize import SR1\nfrom scipy.optimize import Bounds\nfrom scipy.optimize import LinearConstraint\nfrom scipy.optimize import minimize\n\nimport pdb\n\n\nclass CorrelationUtils(object):\n \"\"\"\n https://stats.stackexchange.com/questions/110426/least-correlated-subset-of-random-variables-from-a-correlation-matrix\n https://stackoverflow.com/questions/33811240/python-randomly-fill-2d-array-with-set-number-of-1s\n \"\"\"\n\n corr_matrix = None\n\n def least_correlated_sub_matrix_by_approx(self, corr_matrix, max_dimension):\n while corr_matrix.columns.size > max_dimension:\n max_column_id = (corr_matrix ** 2).sum(axis=1).idxmax()\n corr_matrix = corr_matrix.drop(max_column_id, 1)\n corr_matrix = corr_matrix.drop(max_column_id, 0)\n return corr_matrix\n\n def least_correlated_sub_matrix_by_simu(self, corr_matrix,\n max_dimension, nr_trials=50000,\n corr_type=\"least\"):\n dim_matrix = corr_matrix.columns.size\n results = []\n for s in range(nr_trials):\n if s % (nr_trials / 5) == 0:\n print(s)\n vector_value = [0] * dim_matrix\n for pos in random.sample(range(dim_matrix), max_dimension):\n vector_value[pos] = 1\n mul_1 = np.matmul(np.asarray(vector_value),\n corr_matrix.as_matrix())\n mul_2 = np.matmul(mul_1, np.asarray(vector_value).T)\n results.append((mul_2, vector_value))\n\n # process results\n values = [r[0] for r in results]\n min_value = min(values) if corr_type == \"least\" else max(values)\n min_value_index = values.index(min_value)\n min_value_vector = results[min_value_index][1]\n uncorr_indices = [i for i, x in enumerate(min_value_vector) if x == 1]\n submatrix = corr_matrix.iloc[uncorr_indices, uncorr_indices]\n\n print(\"minimum found: \", min_value)\n print(\"corresponding min vector: \", min_value_vector)\n\n return submatrix\n\n def _corr_quad(self, x):\n tmp = np.matmul(x, self.corr_matrix)\n\n return np.matmul(tmp, x)\n\n def least_correlated_sub_matrix_by_optimization(\n self, corr_matrix,\n max_dimension):\n\n self.corr_matrix = corr_matrix\n nr_vars = corr_matrix.columns.size\n\n A_mat = np.array([[1] * nr_vars])\n b_vec = np.array([max_dimension])\n\n linear_constraint = LinearConstraint(A_mat, b_vec, b_vec)\n bounds = Bounds([0] * nr_vars, [1] * nr_vars)\n\n x0 = np.array([1] * nr_vars)\n\n res = minimize(self._corr_quad, x0, method='trust-constr',\n jac=\"2-point\", hess=SR1(),\n constraints=[linear_constraint],\n options={'verbose': 1}, bounds=bounds)\n\n x_res = res['x']\n x_res_sorted = np.sort(x_res)\n x_comp = (x_res >= x_res_sorted[nr_vars - max_dimension])\n x_hits = np.where(x_comp == True)\n index_hits = x_hits[0].tolist()\n\n return corr_matrix.iloc[index_hits, index_hits]\n","sub_path":"tfs/utils/corrutil.py","file_name":"corrutil.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"71842974","text":"from tensorflow.contrib.keras.api.keras.models import Sequential\nfrom tensorflow.contrib.keras.api.keras.layers import Dense, Dropout, LSTM, Embedding\nfrom tensorflow.contrib.keras.api.keras import utils\nimport numpy as np\n\n# Generate dummy data\nx_train = np.random.random((1000, 25))\ny_train = np.random.randint(2, size=(1000, 1))\nx_test = np.random.random((100, 25))\ny_test = np.random.randint(2, size=(100, 1))\n\nmax_features = 10000\nmodel = Sequential()\nmodel.add(Embedding(input_dim=max_features, output_dim=256, input_length=25))\nmodel.add(LSTM(128))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])\n\nmodel.fit(x_train, y_train, batch_size=16, epochs=10)\nscore = model.evaluate(x_test, y_test, batch_size=16)\nprint (score)","sub_path":"tfkeras/gettingStartedSequenceClassification.py","file_name":"gettingStartedSequenceClassification.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"445781936","text":"#\n'''\n项目管理器:用于创建/管理PyDatcomLab的各种项目,将项目串行化到磁盘,提供GUIs所需要的Model\n主要功能包括:\n1.创建项目目录结构\n2.创建飞行器描述\n3.创建执行算例\n4.形成结果数据\n主要说明:\n1. 目录结构包括\n'''\n\nimport os\nimport time \nimport uuid\n#from xml.dom.minidom import Document \nfrom PyDatcomLab.Core import tools as tl\nfrom PyDatcomLab.Core import dcModel as M\nfrom xml.etree import ElementTree as ET\n\n#from PyDatcomLab.Core import datcomDefine as dF \n\n\nclass projectManager(object):\n '''\n 项目管理器被设计为后台存储所有数据的核心数据结构\n 主要层级结构如下:\n projectManager #顶级Solution prjMXML文件\n project 1 #系统运行的基本单位 dcProject承载\n 目录结构\n case 1\n dcModel #dcXML *.inp\n reslut1 #dcResXML *.out\n case 2\n dcModel\n reslut1 \n project 2\n\n '''\n def __init__(self, mgrFile=''):\n \"\"\"\n 初始化创建一个manager对象\n 如果 mgrFile 存在,则从磁盘文件加载Manager配置\n \"\"\"\n \n self.managerTemplate = \"\"\"\\\n\n\n \n DefaultManager \n \n \n 某个项目 \n 项目样例 \n \n . \n False \n \n \n \n \n \"\"\"\n self.doc = ET.fromstring(self.managerTemplate)\n# self.doc = {\n# 'ManagerPath':'', \n# 'ProjectSet':[\n# {'ProjectFile':'', 'ProjectPath':''}\n# ]\n# \n# }\n #\n if os.path.isfile(mgrFile):\n tmpDoc = ET.parse(mgrFile) #parse是从文件,类名将是字符串\n if tmpDoc.getroot().tag == 'datcomProjectManager':\n self.doc = tmpDoc.getroot()\n self.checkProjectExist()\n tl.logInfo(u'成功加载datcomProjectManager %s'%tmpDoc.tostring())\n else:\n tl.logError(u'加载datcomProjectManager失败 %s'%tmpDoc.tostring())\n \n self.projectSet = {}\n\n\n def checkProjectExist(self, autoRemove = False):\n \"\"\"\n 检查Manager中的project是否存在与磁盘\n autoRemove True自动移除不存在的实例\n \"\"\"\n for prjNode in self.doc.findall('project'):\n tPath = prjNode.find('projectPath').text\n tPjName = prjNode.find('projectName').text\n tPrjFile = os.path.join(tPath, tPjName +'.dcprj')\n if os.path.exists(tPath) and os.path.isfile(tPrjFile):\n prjNode.find('canUse').text = r'True'\n else :\n prjNode.find('canUse').text = r'False'\n if autoRemove:\n self.doc.remove(prjNode) #移除对应的节点\n \n \n def CreateProject(self, tParentDir , tProjectName, tAerocraftName, prjDescribe =u\"\"):\n '''\n 创建一个新工程\n '''\n #校验\n if not os.path.exists(tParentDir) or tProjectName is None :\n tl.logError(u'错误!制定参数错误 dir:%s ,name:%s'%(tParentDir, tProjectName))\n return \n \n #开始创建项目结构的逻辑\n baseDir = os.path.join(os.path.abspath(tParentDir), tProjectName)\n try :\n os.mkdir(baseDir)\n os.makedirs(os.path.join(baseDir, r'3DModels')) #存放3D模型所需信息的目录\n os.makedirs(os.path.join(baseDir, r'Reports')) #存放结果文件的目录\n os.makedirs(os.path.join(baseDir, r'Problems')) #存放算例的目录\n os.makedirs(os.path.join(baseDir, r'Problems', r'defaultGroup')) #第一个算例组\n \n except IOError:\n tl.logError(u'无法创建项目目录!dir:%s ,name:%s'%(tParentDir, tProjectName))\n \n #创建基础的工程文件和目录\n \n #创建项目\n prj = dcProject(prjName=tProjectName, \n prjDescribe = prjDescribe, \n tAerocraftName = tAerocraftName)\n if prj is None: \n tl.logError(u'创建项目失败 %s - %s -%s '%(\n tProjectName, tAerocraftName,prjDescribe ))\n return None\n \n \n # 将dom对象写入本地xml文件\n filePath = os.path.join(baseDir, tProjectName+'.dcprj')\n tXML = ET.ElementTree(prj.doc)\n #ET.register_namespace('datcom', \"https://github.com/darkspring2015/PyDatcomLab/\")\n tXML.write(filePath ,encoding = 'utf-8',xml_declaration=True) \n \n # #追加到项目列表\n prjInfo = prj.getProjectInfo()\n node = ET.SubElement(self.doc, 'project') \n #循环拷贝project info 到相关节点\n for key in prjInfo:\n ET.SubElement(node, key).text = prjInfo[key]\n ET.SubElement(node, 'projectPath').text = baseDir\n ET.SubElement(node, 'canUse').text = r'True'\n \n tl.logInfo(u'创建项目工程文件 %s - %s'%(tProjectName, tAerocraftName))\n #添加到当前的管理器\n self.projectSet[filePath] = prj\n \n return filePath\n\n \n def AddProject(self, tPath):\n \"\"\"\n 将tPath指定的项目添加到项目管理器\n \"\"\"\n aPj = dcProject()\n if not aPj.loadProject(tPath):\n tl.logInfo(u'加载项目工程文件失败 %s'%tPath)\n return \n \n self.projectSet[tPath] = aPj\n tl.logInfo(u'添加项目到管理器 %s'%tPath)\n \n \n \n def deletePrject(self, tPath):\n \"\"\"\n 从管理器中移除工程,并不删除磁盘文件\n \"\"\" \n if not os.path.isfile(tPath):\n tl.logInfo('请输入合法的项目文件, %s'%tPath)\n return \n self.projectSet.pop(tPath)\n \n\n \n def removeProjectFromDisk(self, tPath):\n \"\"\"\n 从磁盘删除一个工程\n \"\"\"\n \n if not os.path.exists(tPath):\n tl.logInfo('无法删除不存在的工程: %s'%tPath)\n return \n \n #判断删除的内容 \n rootDir = tPath\n if os.path.isfile(tPath):\n rootDir = os.path.dirname(tPath)\n \n import shutil \n if os.path.exists(rootDir) :\n shutil.rmtree(rootDir)\n tl.logInfo('从磁盘删除:%s 工程!'%tPath)\n\n \n\n\n \nclass dcProject(object):\n \"\"\"\n Datcom Project的类,负责承载 \n \"\"\"\n \n def __init__(self, prjName=u'A Datcom project', \n prjDescribe =u'', tAerocraftName ='A earocraft'):\n \"\"\" \n prjName : 项目名称\n prjDescribe : 项目描述 \n tAerocraftName :飞行器的名称 \n \"\"\"\n \n self.prjName = prjName\n self.prjDescribe = prjDescribe \n self.aerocraftName = tAerocraftName\n self.uuid = str(uuid.uuid1())\n self.model = M.dcModel(aerocraftName = tAerocraftName, configuration='常规布局')\n \n self.prjTemplete = \"\"\"\\\n\n\n \n A Datcom project \n \n \n \n \n \n \n A aerocraft \n 常规布局 \n \n \n \n \n \n \n \"\"\"\n \n self.doc = ET.fromstring(self.prjTemplete)\n \n #创建项目名称 \n self.setNodeText(r'./projectInfo/projectName', self.prjName)\n self.setNodeText(r'./projectInfo/projectDescribe', self.prjDescribe)\n self.setNodeText(r'./projectInfo/projectUUID', self.uuid )\n self.setNodeText(r'./projectInfo/createTime', \n time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\n self.setNodeText(r'./projectInfo/modifyTime', \n time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))\n #飞行器名称\n self.setNodeText(r'./aerocraftInfo/aerocraftName', self.aerocraftName)\n\n def loadProject(self, prjFile):\n \"\"\"\n prjFile : 工程文件路径 \n \"\"\"\n if not os.path.exists(prjFile ) or not os.path.isfile(prjFile):\n tl.logError(u'输入路径错误 %s'%prjFile)\n \n tmpDoc = ET.parse(prjFile) #parse是从文件,类名将是字符串\n if not tmpDoc.getroot().tag == 'datcomProject':\n tl.logError(u'错误的工程文件格式 %s'%tmpDoc.tostring())\n return False\n self.doc = tmpDoc.getroot()\n \n return True\n \n \n\n \n def setNodeText(self, xpath, text):\n \"\"\"\n 设置doc中xpath对应节点的text\n 认为是叶节点\n xpath : r'./projectInfo/projectName'\n \"\"\"\n nodes = self.doc.findall(xpath)\n if len(nodes) is not 1:\n tl.logError(u\"查询%s 过程中出错!\"%xpath)\n return False\n if len(nodes[0].getchildren()) is not 0 :\n tl.logError(u\"查询%s ,不是叶节点!\"%xpath)\n return False\n nodes[0].text = text\n \n return True\n \n \n \n\n def addTextNode(self, parentNode, name, text =u''):\n \"\"\"\n 创建一个Node ,用name和value\n 并将这个Node添加到parentNode中\n 返回创建的这个Node\n \"\"\"\n if name is None or parentNode is None:\n tl.logError(\n u'尝试创建错误的节点 name %s ,parentNode %s'\\\n %(name, parentNode))\n return None\n \n node = self.doc.SubElement(parentNode, name) \n if not text is '': node.text = text\n \n return node\n \n def addNode(self, parentNode, name):\n \"\"\"\n 创建一个Node ,用name\n 并将这个Node添加到parentNode中\n 返回创建的这个Node\n \"\"\"\n if name is None or parentNode is None:\n tl.logError(\n u'尝试创建错误的节点 name %s ,parentNode %s'%(name, parentNode))\n return None\n node = self.doc.SubElement(parentNode, name) \n \n return node\n \n def addNodeWithAttribute(self, parentNode, name, attr ):\n \"\"\"\n 创建一个Node ,用name\n 并将这个Node添加到parentNode中\n 这个Node具有属性 attr :一个dict,key是属性名,value是属性值 \n 返回创建的这个Node\n \"\"\"\n \n if name is None or parentNode is None:\n tl.logError(\n u'尝试创建错误的节点 name %s ,parentNode %s'%(name, parentNode))\n return None\n \n node = self.doc.SubElement(parentNode, name) \n #设置属性值\n for atr in attr:\n node.set(atr, attr[atr])\n \n return node\n \n \n def getProjectInfo(self):\n \"\"\"\n 获得项目名称和项目描述 \n dict.keys = [\n \"projectName\"\n \"projectDescribe\"\n ]\n \"\"\"\n dict = {}\n for info in self.doc.findall('projectInfo'):\n for tInfo in info:\n dict[tInfo.tag] = tInfo.text\n \n return dict\n \n def setProjectInfo(self, info):\n \"\"\"\n 设置项目信息 : \n info = {\n \"projectName\":'new project Name', \n \"projectDescribe\":'new project describe'\n }\n \"\"\"\n if 'projectName' in info:\n self.setNodeText(r'/datcomProject/projectInfo/projectName', info['projectName'])\n if 'projectDescribe' in info :\n self.setNodeText(r'/datcomProject/projectInfo/projectDescribe', info['projectDescribe'])\n \n \n def getAerocraftInfo(self):\n \"\"\"\n 获得飞行器的描述信息 \n info.keys =[\n 'name','configuration']\n \n \"\"\"\n dict = {}\n for info in self.doc.findall('aerocraftInfo'):\n for tInfo in info:\n dict[tInfo.tag] = tInfo.text \n \n return dict\n \n \n def getNodeTextByXPath(self, xpath):\n \"\"\"\n 利用xml.etre.ElementTree 实现的xpath,当前仅支持部分功能\n 假设读取最终节点的text值\n etc r'./aerocraftInfo/aerocraftName'\n \"\"\"\n #转换当前doc \n\n nodes = self.doc.getroot().findall(xpath)\n if len(nodes) is 0 : \n tl.logError(\"不存在对应节点:%s\" % xpath )\n return nodes[0].text\n \n def newCASE(self, dict =None):\n \"\"\"\n 新建一个CASE\n dict 提供基本的数据定义,定义如下\n >>>from PyDatcomLab.Core import datcomDefine as dF \n >>>dict = dF.datcomDefine.dtNmlstExmple\n \n \n \"\"\"\n \n #导入Datcom的定义\n from PyDatcomLab.Core import datcomDefine as dF \n keyLst = dF.datcomDefine.reserved_NAMELISTS #定义了所有Namelist信息的list\n \n \n #获得CASE定义的跟节点\n casegroup = self.getNodeTextByXPath(r'./datcomProject/casegroup')\n newCASEID = casegroup.findall('CASE').count + 1\n #添加一个CASE到CASE集合\n newCase = ET.SubElement(casegroup,\"CASE\", {'INDEX':newCASEID})\n \n if dict is None: \n return\n \n #若干字典信息存在,则根据字典顺序下达信息\n for nmlst in dict.keys():\n if nmlst not in keyLst:\n continue\n #如果在,则创建响应的节点\n nmlstNode = ET.SubElement(newCase, nmlst)\n if dict[nmlst] is 'dict':\n for var in dict[nmlst].keys(): #添加遍历namelist下面的遍历\n varNode = ET.SubElement(nmlstNode, var)\n if len(dict[nmlst][var]) == 1: #如果变量时单值的直接添加\n ET.SubElement(varNode, dict[nmlst][var])\n continue\n for aVal in dict[nmlst][var]: #如果遍历是多值的,遍历变量的每一个值\n valNode = ET.SubElement(varNode, 'value')\n valNode.text = str(aVal)\n else:\n self.logger.info(\"异常的字典结构\")\n \n \n def setCASEModel(self, caseID=1, dict = None):\n \"\"\"\n 设置CASE的Model内容\n \"\"\"\n if dict is None:\n return\n \n #获得对应的CASE\n \n #root = self.doc\n #导入Datcom的定义\n \n\n\n\n \n \n\n","sub_path":"PyDatcomLab/Core/projectManager.py","file_name":"projectManager.py","file_ext":"py","file_size_in_byte":15336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"88576292","text":"#!/usr/bin/env python\n\n\"\"\"\nCopyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)\nSee the file 'doc/COPYING' for copying permission\n\"\"\"\n\nfrom lib.core.settings import WAF_ATTACK_VECTORS\n\n__product__ = \"ModSecurity: Open Source Web Application Firewall (Trustwave)\"\n\ndef detect(get_page):\n retval = False\n\n for vector in WAF_ATTACK_VECTORS:\n page, headers, code = get_page(get=vector)\n if code == 501:\n retval = True\n break\n\n return retval\n","sub_path":"waf/modsecurity.py","file_name":"modsecurity.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"5673737","text":"import time\nimport sys\nimport msvcrt\nimport os\nfrom view.inicio.inicio import test\n\n# La vista tiene que mandar donde esta, la primera vista siempre es el menu por defecto\n\nos.system(\"cls\")\ntest.menu()\nmensaje =\t(\"##################################\\n\" +\n\t\t\t\"# #\\n\" +\n\t\t\t\"# #\\n\" +\n\t\t\t\"# Naves Game Multiplayer #\\n\" +\n\t\t\t\"# #\\n\" +\n\t\t\t\"# #\\n\" +\n\t\t\t\"##################################\\n\")\n\n\nwhile True:\n\n\t## Controlador\n\n\tos.system(\"cls\") \t\t\t# Limpia la pantalla\n\tprint (mensaje)\n\ttest.menu()\t\t\t\t\t# Muestra el menu\n\n\tpulsacion = msvcrt.getch().decode(\"utf-8\", \"ignore\")\n\n\tif pulsacion == \"1\":\n\n\t\tprint (\"\\n 1. Empezar\")\t\t # La opción (Debugg)\n\n\telif pulsacion == \"2\":\n\n\t\tprint (\"\\n 2. Multiplayer\") # La opción (Debugg)\n\n\telif pulsacion == \"3\":\n\n\t\tprint (\"\\n 3. Configuración\") # La opción (Debugg)\n\n\telif pulsacion == \"4\": \n\n\t\tprint (\"\\n 4. Creditos\") \t # La opción (Debugg)\n\n\telif pulsacion == \"5\":\n\n\t\tprint (\"\\n 5. Salir\")\t\t # La opción (Debugg)\n\t\tsys.exit()\n\n\ttime.sleep(1/30)","sub_path":"controller/control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"507385658","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'notes'\n\nurlpatterns = [\n url(r'^(?P[0-9]+)/$', views.note_list, name='list'),\n url(r'^(?P[0-9]+)/new/$', views.note_new, name='new'),\n url(r'^create/$', views.note_create, name='note_create'),\n]\n","sub_path":"notes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"52103057","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 12 2020\n@author: Di\n\"\"\"\n# inputs\nDirectory = 'E:/Documents/patterns'\nfn = '2D_structures_symmetric.yaml' # yaml file name\n\n# define gds file names\n# File_names = ['loop-90deg-l1={l1}um-width={width}um', \\\n # 'loop-60deg-l1={l1}um-width={width}um', \\\n # 'loop-symmetric-l1={l1}um-width={width}um']\nFile_names = ['loop-symmetric-l1={l1}um-width={width}um'] # seperate each type in different yaml files - to avoid overflow\nEnable_file_names = [1, 1, 1] # 1: enable: True; 0: enable: False. Same size as File_names\nTwin_file_names = [1, 1, 1]\n\n# define corresponding types\nLoop_types = []\nfor i, File_name in enumerate(File_names):\n if File_name == 'loop-90deg-l1={l1}um-width={width}um':\n Loop_types.extend(['high-angle-90deg'])\n elif File_name == 'loop-60deg-l1={l1}um-width={width}um':\n Loop_types.extend(['high-angle-60deg'])\n elif File_name == 'loop-symmetric-l1={l1}um-width={width}um':\n Loop_types.extend(['high-angle-symmetric'])\n\n# parameters staying constant in a field\nwidth_settings = [0.02, 0.03, 0.04, 0.05]\nEnable_width = [1, 1, 1, 1] # 1: enable: True; 0: enable: False. Same size as width_settings\nTwin_width = [1, 1, 1, 1]\n\nl1_settings = [1, 1.3, 1.6, 2]\nEnable_l1 = [1, 1, 1, 1] # 1: enable: True; 0: enable: False. Same size as l1_settings\nTwin_l1 = [1, 1, 1, 1]\n\n# parameters varying in a field\nl2 = '[0.4, 0.5, 0.5, 0.6, 0.6, 0.7, 0.8]'\nd1 = '[2.1, 2.2, 2.3, 2.35, 2.4, 2.5, 2.6]'\n\n# parameters always staying constant\nd2 = 1.2\nla = 1\n\nlayer = 10\nsw_layer = 20\n\n'''\n======== main ==============\n'''\n\nind = ' '\n\nfile = open(fn, 'w+')\n\nfile.write('directory: ' + Directory + '\\n')\nfile.write('arrays:\\n')\n\nfor i1, File_name in enumerate(File_names):\n for i2, width in enumerate(width_settings):\n for i3, l1 in enumerate(l1_settings):\n file.write('-\\n')\n file.write(ind + 'file_name: ' + File_names[i1] + '\\n')\n if Enable_file_names[i1] == 1 and Enable_width[i2] == 1 and Enable_l1[i3] == 1:\n file.write(ind + 'enable: True\\n')\n else:\n file.write(ind + 'enable: False\\n')\n file.write(ind + 'y_labels: |\\n' + 2*ind + 'd1\\n' + 2*ind + '{Y}\\n')\n file.write(ind + 'x_labels: l2={X}um\\n')\n file.write(ind + 'x_key: l2\\n')\n file.write(ind + 'y_key: d1\\n')\n file.write(ind + 'parameters:\\n')\n file.write(ind + ind + 'width: ' + str(width) + '\\n')\n file.write(ind + ind + 'l1: ' + str(l1) + '\\n')\n file.write(ind + ind + 'l2: ' + l2 + '\\n')\n file.write(ind + ind + 'd1: ' + d1 + '\\n')\n file.write(ind + ind + 'd2: ' + str(d2) + '\\n')\n file.write(ind + ind + 'la: ' + str(la) + '\\n')\n file.write(ind + ind + 'loop_type: ' + Loop_types[i1] + '\\n')\n file.write(ind + ind + 'layer: ' + str(layer) + '\\n')\n file.write(ind + ind + 'sw_layer: ' + str(sw_layer) + '\\n')\n if Twin_file_names[i1] == 1 and Twin_width[i2] == 1 and Twin_l1[i3] == 1:\n file.write(ind + ind + 'twin_enable: True\\n')\n else:\n file.write(ind + ind + 'twin_enable: False\\n')\n","sub_path":"gdspy-drawings/generate_yaml.py","file_name":"generate_yaml.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"503636437","text":"from client import YoutubeDownloader\nfrom utils import create_and_set_directory, clearing_url\n\nif __name__ == '__main__':\n\tyt_dwn = YoutubeDownloader()\n\turl_list = []\n\turl = \"\"\n\tpath = None\n\tprint(\n\t\t\"########################################################################################\\n\"\n\t\t\"Welcome to ytDownloader, you can enter as much urls as you want and then write 'start'\\n\" \n\t\t\"(without quotes '') to start downloading\\n\"\n\t\t\"########################################################################################\"\n\t)\n\twhile url != \"start\":\n\t\turl = input(\"Write url: \")\n\t\tif url != \"start\" and url.find(\"www.youtube.com\") != -1:\n\t\t\turl_list.append(clearing_url(url))\n\t\telif url == \"start\":\n\t\t\tif len(url_list) == 0:\n\t\t\t\tprint(\"You have not write any url, please introduce one.\\n\")\n\t\t\t\turl = \"\"\n\t\telse:\n\t\t\tprint(\n\t\t\t\t\"Input '{}' not recognized, please try again (You can try with something like: \"\n\t\t\t\t\"https://www.youtube.com/watch?v=HQJ-LXzn9iw)\\n\".format(url)\n\t\t\t)\n\n\tresp = input(\"Do you want to set a directory to download? y/N: \")\n\tif resp == \"Y\" or resp == \"y\":\n\t\tpath = input(\"Write the path (e.g. /user/test_directory/music): \")\n\n\tpath = create_and_set_directory(path=path)\n\tyt_dwn.updating_path_for_saving(path=path)\n\tres = yt_dwn.download(url_list=url_list)\n\n\tif res == 0:\n\t\tprint(\"#################################################################################\")\n\t\tprint(\n\t\t\t\"SUCCESS DOWNLOADING!\\n\"\n\t\t\t\"Path of downloading: {}\".format(path)\n\t\t)\n\telse:\n\t\tprint(\"#################################################################################\")\n\t\tprint(\n\t\t\t\"ERROR DOWNLOADING!\\n\"\n\t\t\t\"Error -> {}\".format(res)\n\t\t)\n","sub_path":"ytDownloader/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"583275164","text":"import math\n\n# class implementing complex numbers\nclass complex:\n\n def __init__(self,r=0,i=0):\n self.real = r\n self.imaginary = i\n\n def __str__(self):\n if abs(self.imaginary)!=1:\n if self.imaginary>0:\n return \"{} + {}i\".format(self.real,self.imaginary)\n else:\n return \"{} - {}i\".format(self.real,abs(self.imaginary))\n else:\n if self.imaginary>0:\n return \"{} + i\".format(self.real)\n else:\n return \"{} - i\".format(self.real)\n\n def __add__(self,num2):\n ans = complex()\n ans.real = self.real + num2.real\n ans.imaginary = self.imaginary + num2.imaginary\n return ans\n\n def __sub__(self,num2):\n ans = complex()\n ans.real = self.real - num2.real\n ans.imaginary = self.imaginary - num2.imaginary\n return ans\n\n def __mul__(self,num2):\n ans = complex()\n ans.real = self.real*num2.real - self.imaginary*num2.imaginary\n ans.imaginary = self.real*num2.imaginary + self.imaginary*num2.real\n return ans\n\n def modulus(self):\n return math.sqrt(self.real**2 + self.imaginary**2)\n\n def display(self):\n if abs(self.imaginary)!=1:\n if self.imaginary>0:\n print(\"{} + {}i\".format(self.real,self.imaginary))\n else:\n print(\"{} - {}i\".format(self.real,abs(self.imaginary)))\n else:\n if self.imaginary>0:\n print(\"{} + i\".format(self.real))\n else:\n print(\"{} - i\".format(self.real))\n\n def conjugate(self):\n ans = complex()\n ans.real = self.real\n ans.imaginary = -1*self.imaginary\n return ans\n\n def inverse(self):\n ans = complex()\n m = self.modulus()\n ans.real = self.real/m\n ans.imaginary = (self.imaginary*(-1))/m\n return ans\n\n def add(self,num2):\n return self + num2\n\n def subtract(self,num2):\n return self - num2\n\n def multiply(self,num2):\n return self*num2\n\n\nprint(\"Enter four space seperated integers for test cases: \")\nnums = list(map(int,input().split()))\n\na = complex(nums[0],nums[1])\nb = complex(nums[2],nums[3])\n\n# test cases\nprint(a)\nprint(b)\nprint(a+b)\nprint(a-b)\nprint(a*b)\na.display()\nb.display()\nc=b.add(a)\nd=b.subtract(a) # subtract a from b\ne=b.multiply(a)\nprint(c)\nprint(d)\nprint(e)\nprint(a.modulus())\nprint(a.inverse())\nc.conjugate().display()\n\n","sub_path":"Python/Assignment 1/Question 3.py","file_name":"Question 3.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"232106265","text":"import pygame\nimport time\nimport random\npygame.mixer.pre_init()\npygame.init()\npygame.mixer.music.set_volume(1)\nscreenWidth = 1820\nscreenHeight = 980\ngameDisplay = pygame.display.set_mode((screenWidth, screenHeight))\nclock = pygame.time.Clock()\nfireBallImg = pygame.image.load('Python with AI - Level 2/pygame/carGame/fireBall.png')\ncarImg = pygame.image.load('Python with AI - Level 2/pygame/carGame/car.png')\npygame.display.set_caption('Car Dodging')\nenemyCars = [pygame.image.load('Python with AI - Level 2/pygame/carGame/car4.png'), pygame.image.load('Python with AI - Level 2/pygame/carGame/car2.png'), pygame.image.load('Python with AI - Level 2/pygame/carGame/car3.png')]\nenemyCarsWidths = [76, 76, 96]\nenemyCarsHeights = [166, 171, 201]\ndef car(x, y, carImage):\n gameDisplay.blit(carImage, (x, y))\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, (0, 0, 0))\n return textSurface, textSurface.get_rect()\n\ndef chrash():\n displayMsg(\"You died\", (int(screenWidth / 2), int(screenHeight / 2)), 115)\n frameUpdate()\n pygame.mixer.music.load(\"Python with AI - Level 2/pygame/carGame/Explosion+1.wav\")\n pygame.mixer.music.play()\n time.sleep(3)\n\ndef things(thingx, thingy, thingw, thingh, color):\n pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])\n\ndef playMus(musPath):\n pygame.mixer.music.load(musPath)\n pygame.mixer.music.play()\n\ndef playBackMus(backMusPath):\n pygame.mixer.music.load(backMusPath)\n pygame.mixer.music.play(-1)\n\ndef displayMsg(msg, pos, fontSize):\n largeText = pygame.font.Font('freesansbold.ttf', fontSize)\n TextSurf, TextRect = text_objects(msg, largeText)\n TextRect.center = (pos[0], pos[1])\n gameDisplay.blit(TextSurf, TextRect)\n\ndef button(activeColor, inactiveColor, buttonX, buttonY, buttonWidth, buttonHeight, msg):\n things(buttonX, buttonY, buttonWidth, buttonHeight, inactiveColor)\n if pygame.mouse.get_pos()[0] > buttonX and pygame.mouse.get_pos()[0] < buttonX + buttonWidth and pygame.mouse.get_pos()[1] > buttonY and pygame.mouse.get_pos()[1] < buttonY + buttonHeight:\n things(buttonX, buttonY, buttonWidth, buttonHeight, activeColor)\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n TextSurf, TextRect = text_objects(msg, largeText)\n TextRect.center = (buttonX + int(buttonWidth/2), buttonY + int(buttonHeight/2))\n gameDisplay.blit(TextSurf, TextRect)\n\ndef gameQuit():\n pygame.quit()\n quit()\n\ndef frameUpdate():\n pygame.display.update()\n clock.tick(60)\n\ndef fireBall(x, y):\n gameDisplay.blit(fireBallImg, (x, y))\n\nfirstZaWarudo = True\nvolume = 100\nfireBallsLeft = 5\n\nwhile True:\n \n #This is the reset code.\n\n if fireBallsLeft == \"infinity\":\n fireBallsLeft = 5\n startChoiceEnd = False\n resetting = False\n unlimitedFireBalls = False\n fireBallCoolDownTime = 60\n fireBallCoolDown = 0\n Ahit = False\n Bhit = False\n fireBallX = 0\n fireBallY = 0\n fireBallLaunched = False\n fireBallSpeed = 5\n firstZaWarudo = True\n Aresetted = False\n Await = 0\n Bresetted = False\n Bwait = 0\n gameDisplay.fill((255, 255, 255, 0))\n frameUpdate()\n menuEnd = False\n AbaseSpeed = random.randint(5, 10)\n BbaseSpeed = random.randint(5, 10)\n thingA_startx = random.randint(0, 600)\n thingA_starty = -600\n thingA_speed = 7\n AcarNum = random.randint(0, len(enemyCars) - 1)\n Acar = enemyCars[AcarNum]\n thingA_height = enemyCarsHeights[AcarNum]\n thingA_width = enemyCarsWidths[AcarNum]\n thingB_startx = random.randint(0, 600)\n thingB_starty = -600\n thingB_speed = 7\n BcarNum = random.randint(0, len(enemyCars) - 1)\n Bcar = enemyCars[BcarNum]\n thingB_height = enemyCarsHeights[BcarNum]\n thingB_width = enemyCarsWidths[BcarNum]\n points = 0\n passedA = False\n passedB = False\n speedIncreaseCounter = 3\n carSpeed = 5\n chrashed = False\n x_change = 0\n x = 400\n y = screenHeight - 166\n zaWarudoMaxTime = 600\n zaWarudoTime = 600\n zaWarudoEffect = False\n speedChange = 0\n zaWarudoCoolDownTime = 600\n zaWarudoCoolDown = 0\n\n # This is the start menu\n\n while not menuEnd:\n displayMsg(\"Car Dodging\", (int(1920 / 2), int(screenHeight / 2)), 115)\n displayMsg(\"press space to start and q to quit. or the buttons\", (int(1920/2), int(screenHeight/2) + 100), 20)\n button((255, 40, 0), (255, 0, 0), 1120, 780, 100, 100, \"Quit?\")\n button((0, 255, 0), (90, 238, 90), 600, 780, 100, 100, \"START?\")\n button((255, 255, 255), (100, 100, 100), 390, 780, 200, 100, \"Change Volume?\")\n button((255, 255, 255), (255, 255, 255), 200, 100, 1, 1, f\"Volume: {str(volume)}%\")\n for event in pygame.event.get():\n if (event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE) or (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 600 and event.pos[0] < 700 and event.pos[1] > 780 and event.pos[1] < screenHeight and event.button == 1):\n menuEnd = True\n if (event.type == pygame.KEYDOWN and event.key == pygame.K_q) or (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 1120 and event.pos[0] < 1220 and event.pos[1] > 780 and event.pos[1] < 880 and event.button == 1) or event.type == pygame.QUIT:\n gameQuit()\n if event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 390 and event.pos[0] < 590 and event.pos[1] > 780 and event.pos[1] < 880 and event.button == 1:\n if volume == 100:\n volume = 0\n else:\n volume += 10\n frameUpdate()\n gameDisplay.fill((255, 255, 255, 0))\n pygame.mixer.music.set_volume(volume / 100)\n\n # This part of the code decides whether you want to play 5 fireball or infinite fireball\n\n AfterMenu = True\n AfterMenuCount = 30\n while not startChoiceEnd:\n button((0, 255, 0), (90, 238, 90), 1020, 780, 200, 100, f\"{fireBallsLeft} Fireballs\")\n button((0, 255, 0), (90, 238, 90), 500, 780, 200, 100, \"Infinite Fireballs\")\n button((0, 255, 0), (90, 238, 90), 810, 780, 100, 100, \"Back\")\n button((0, 255, 0), (90, 238, 90), 1270, 830, 45, 45, \"More\")\n button((0, 255, 0), (90, 238, 90), 1270, 780, 45, 45, \"Less\")\n frameUpdate()\n gameDisplay.fill((255, 255, 255, 0))\n if not AfterMenu:\n for event in pygame.event.get():\n if (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 1020 and event.pos[0] < 1220 and event.pos[1] > 780 and event.pos[1] < screenHeight and event.button == 1):\n unlimitedFireBalls = False\n startChoiceEnd = True\n if (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 500 and event.pos[0] < 700 and event.pos[1] > 780 and event.pos[1] < screenHeight and event.button == 1):\n fireBallsLeft = \"infinity\"\n unlimitedFireBalls = True\n startChoiceEnd = True\n if (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 810 and event.pos[0] < 910 and event.pos[1] > 780 and event.pos[1] < screenHeight and event.button == 1):\n resetting = True\n startChoiceEnd = True\n if (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 1270 and event.pos[0] < 1350 and event.pos[1] > 780 and event.pos[1] < 825 and event.button == 1):\n if (fireBallsLeft > 0):\n fireBallsLeft += -1\n if (event.type == pygame.MOUSEBUTTONDOWN and event.pos[0] > 1270 and event.pos[0] < 1350 and event.pos[1] > 830 and event.pos[1] < 855 and event.button == 1):\n fireBallsLeft += 1\n if event.type == pygame.QUIT:\n gameQuit()\n elif AfterMenuCount == 0:\n AfterMenu = False\n AfterMenuCount += -1\n if resetting:\n continue\n\n # This line starts the background music\n\n playBackMus(\"Python with AI - Level 2/pygame/carGame/background.wav\")\n\n # This is the game's loop\n\n while not chrashed:\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n TextSurf, TextRect = text_objects(f\"score: {points}\", largeText)\n TextRect.center = (200, 50)\n gameDisplay.blit(TextSurf, TextRect)\n largeText = pygame.font.Font('freesansbold.ttf', 20)\n TextSurf, TextRect = text_objects(f\"fireballs left: {fireBallsLeft}\", largeText)\n TextRect.center = (1620, 50)\n gameDisplay.blit(TextSurf, TextRect)\n gameEvents = pygame.event.get()\n\n # This handles the game's functions\n\n for event in gameEvents:\n if event.type == pygame.QUIT:\n gameQuit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT or event.key == pygame.K_a:\n x_change = 0 - carSpeed - speedChange\n elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:\n x_change = carSpeed + speedChange\n if event.key == pygame.K_UP:\n speedChange = 5\n elif event.key == pygame.K_w:\n speedChange = 5\n elif event.key == pygame.K_DOWN or event.key == pygame.K_s:\n speedChange = -2\n if event.key == pygame.K_SPACE and zaWarudoCoolDownOver:\n zaWarudoEffect = True\n zaWarudoCoolDownOver = False\n zaWarudoCoolDown = int(zaWarudoCoolDownTime/1)\n zaWarudoTime = int(zaWarudoMaxTime/1) \n pygame.mixer.music.set_volume(3)\n playMus(\"Python with AI - Level 2/pygame/carGame/zaWarudo.wav\")\n if event.key == pygame.K_LSHIFT and not(fireBallLaunched) and ((not(unlimitedFireBalls) and fireBallsLeft > 0) or (unlimitedFireBalls and fireBallCoolDown == 0)):\n fireBall(x, y - 148)\n fireBallX = x\n fireBallY = screenHeight - 166 - 148\n fireBallLaunched = True\n fireBallCoolDown = fireBallCoolDownTime\n if not(unlimitedFireBalls):\n fireBallsLeft += -1\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_d or event.key == pygame.K_a:\n x_change = 0\n if event.key == pygame.K_UP or event.key == pygame.K_w or event.key == pygame.K_DOWN or event.key == pygame.K_s:\n speedChange = 0\n x += x_change\n\n # This area handles collision\n\n if x > screenWidth - 76 or x < 0:\n if not zaWarudoEffect:\n chrash()\n chrashed = True\n else:\n x += 0 - x_change\n if (y < thingA_starty + thingA_height and not(Aresetted)) or (y < thingB_starty + thingB_height and not(Bresetted)):\n if (((x > thingA_startx and x < thingA_startx + thingA_width) or (x + 76 > thingA_startx and x + 76 < thingA_startx + thingA_width)) and not(Aresetted) and y < thingA_starty + thingA_height) or ((x > thingB_startx and x < thingB_startx + thingB_width) or (x + 76 > thingB_startx and x + 76 < thingB_startx + thingB_width)) and not(Bresetted) and y < thingB_starty + thingB_height:\n if not zaWarudoEffect:\n chrash()\n chrashed = True\n break\n else:\n x += 0 - x_change\n if not(passedA) and (not(x > thingA_startx and x < thingA_startx + thingA_width) or (x + 76 > thingA_startx and x + 76 < thingA_startx + thingA_width) and not(Aresetted)):\n points += 10\n if zaWarudoMaxTime > 540:\n zaWarudoMaxTime += 10\n if zaWarudoCoolDown < 180:\n zaWarudoCoolDownTime += -10\n passedA = True\n if not(passedB) and (not(x > thingB_startx and x < thingB_startx + thingB_width) or (x + 76 > thingB_startx and x + 76 < thingB_startx + thingB_width) and not(Bresetted)):\n points += 10\n if zaWarudoMaxTime > 540:\n zaWarudoMaxTime += 10\n if zaWarudoCoolDown < 180:\n zaWarudoCoolDownTime += -10\n passedB = True\n if not zaWarudoEffect:\n thingA_starty += AbaseSpeed + speedChange\n thingB_starty += BbaseSpeed + speedChange\n zaWarudoCoolDown += -1\n\n # This area handles the fireball movement and resetting\n\n if fireBallLaunched:\n fireBallY += 0 - fireBallSpeed\n fireBall(fireBallX, fireBallY)\n \n if fireBallY <= -148:\n fireBallLaunched = False\n\n # This area handles the fireball collision\n\n if fireBallY < thingA_starty + thingA_height and fireBallX + 113 > thingA_startx and fireBallX < thingA_startx + thingA_width and fireBallLaunched:\n Await = 0\n Ahit = True\n fireBallLaunched = False\n if fireBallY < thingB_starty + thingB_height and fireBallX + 113 > thingB_startx and fireBallX < thingB_startx + thingB_width and fireBallLaunched:\n Bwait = 0\n Bhit = True\n fireBallLaunched = False\n \n # This area handles the enemy spawning.\n\n if thingA_starty < screenHeight and not(Ahit):\n car(thingA_startx, thingA_starty, Acar)\n elif (Await == 0 and Aresetted) or Ahit:\n if not(Ahit):\n speedIncreaseCounter = speedIncreaseCounter - 1\n passedA = False\n if speedIncreaseCounter == 0:\n speedIncreaseCounter = 3\n AbaseSpeed += 1\n BbaseSpeed += 1\n carSpeed += 1\n fireBallSpeed += 1\n AcarNum = random.randint(0, len(enemyCars) - 1)\n Acar = enemyCars[AcarNum]\n thingA_height = enemyCarsHeights[AcarNum]\n thingA_width = enemyCarsWidths[AcarNum]\n thingA_startx = random.randint(0, 1920 - thingA_width)\n thingA_starty = -100 - thingA_height\n car(thingA_startx, thingA_starty, Acar)\n Aresetted = False\n Ahit = False\n else:\n Aresetted = True\n Await = random.randint(0, 120)\n if thingB_starty < screenHeight and not(Bhit):\n car(thingB_startx, thingB_starty, Bcar)\n elif (Bwait == 0 and Bresetted) or Bhit:\n \n if not(Bhit):\n speedIncreaseCounter = speedIncreaseCounter - 1\n passedB = False\n if speedIncreaseCounter == 0:\n speedIncreaseCounter = 3\n AbaseSpeed += 1\n BbaseSpeed += 1\n carSpeed += 1\n fireBallSpeed += 1\n BcarNum = random.randint(0, len(enemyCars) - 1)\n Bcar = enemyCars[BcarNum]\n thingB_height = enemyCarsHeights[BcarNum]\n thingB_width = enemyCarsWidths[BcarNum]\n thingB_startx = random.randint(0, 1920 - thingB_width)\n thingB_starty = -100 - thingB_height\n car(thingB_startx, thingB_starty, Bcar)\n Bresetted = False\n Bhit = False\n else:\n Bresetted = True\n Bwait = random.randint(0, 120)\n\n # This handles most of the time stop functions\n\n if firstZaWarudo and zaWarudoEffect:\n displayMsg(\"You're DIO?\", (400, 300), 20)\n car(x, y, carImg)\n if zaWarudoEffect:\n zaWarudoTime += -1\n if zaWarudoTime == 90:\n playMus(\"Python with AI - Level 2/pygame/carGame/timeResumes.wav\")\n if zaWarudoTime <= 0 and zaWarudoEffect:\n zaWarudoEffect = False\n firstZaWarudo = False\n playBackMus(\"Python with AI - Level 2/pygame/carGame/background.wav\")\n if zaWarudoCoolDown <= 0:\n zaWarudoCoolDownOver = True\n\n # This handles the box respawn delays\n \n if Await > 0:\n Await += -1\n if Bwait > 0:\n Bwait += -1\n\n # This updates the game\n\n frameUpdate()\n\n # This is the fireball cooldown\n\n if not(fireBallLaunched) and fireBallCoolDown > 0:\n fireBallCoolDown += -1\n\n # This clears the screen for the next frame\n\n gameDisplay.fill((255, 255, 255, 0))","sub_path":"Python with AI - Level 2/pygame/carGame/racingCarGame.py","file_name":"racingCarGame.py","file_ext":"py","file_size_in_byte":16525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"441585081","text":"\nimport os\nimport ROOT\nimport HWWAnalysis.Misc.odict as odict\nimport HWWAnalysis.Misc.ROOTAndUtils as utils\nimport logging\nimport hwwtools\nimport pdb\n\n_defaults = odict.OrderedDict([ \n ('ggH', { 'color':ROOT.kRed+1, 'label':'ggH', }),\n ('vbfH', { 'color':ROOT.kRed+2, 'label':'qqH', }),\n ('wzttH',{ 'color':ROOT.kRed+3, 'label':'VH' , }),\n ('VH', { 'color':ROOT.kRed+3, 'label':'VH' , }),\n ('wH', { 'color':ROOT.kRed-3, 'label':'wH' , }),\n ('zH', { 'color':ROOT.kRed-4, 'label':'zH' , }),\n\n ('VV', { 'color':ROOT.kAzure-2, 'label':'WZ/ZZ' , }), \n ('DYTT', { 'color':ROOT.kGreen+2, 'label':'DY+jets' , }),\n ('DYLL', { 'color':ROOT.kGreen+3, 'label':'DY+jets' , }),\n ('DYee', { 'color':ROOT.kGreen+3, 'label':'DY+jets' , }),\n ('DYmm', { 'color':ROOT.kGreen+3, 'label':'DY+jets' , }),\n ('Vg', { 'color':ROOT.kMagenta+1, 'label':'V+#gamma' , }),\n ('VgS', { 'color':ROOT.kMagenta+2, 'label':'V+#gamma*' , }),\n ('WJet', { 'color':ROOT.kGray+1, 'label':'W+jets' , }),\n ('Top', { 'color':ROOT.kYellow, 'label':'top' , }),\n ('ttbar',{ 'color':ROOT.kYellow-4, 'label':'t#bar{t}' , }),\n ('tW', { 'color':ROOT.kOrange-2, 'label':'tW' , }),\n ('WW', { 'color':ROOT.kAzure-9, 'label':'WW' , }),\n ('ggWW', { 'color':ROOT.kAzure-7, 'label':'WW' , }),\n])\n\n\nif not ROOT.gROOT.GetListOfClasses().FindObject('PlotVHqqHggH'):\n shape_path = os.path.join(os.getenv('CMSSW_BASE'),'src/HWWAnalysis/ShapeAnalysis')\n\n hwwtools.loadAndCompile(shape_path+'/macros/PlotVHqqHggH.C')\n\nclass NullStdOutSentry:\n def __init__(self):\n\n ignlvl = ROOT.gErrorIgnoreLevel\n ROOT.gErrorIgnoreLevel = ROOT.kSysError\n self.rdbuf = ROOT.std.cout.rdbuf()\n ROOT.std.cout.rdbuf(0x0)\n ROOT.gErrorIgnoreLevel = ignlvl\n\n \n def __del__(self):\n ROOT.std.cout.rdbuf(self.rdbuf)\n\nclass HWWPlot(ROOT.PlotVHqqHggH):\n\n _log = logging.getLogger('HWWPlot') \n \n# _properties = ['label','color','scale','norm']\n\n #---\n def __init__(self, properties=_defaults):\n super(HWWPlot,self).__init__()\n\n self._properties = properties\n self._autosort = False\n self._order = None\n\n self._data = None\n self._sigs = odict.OrderedDict()\n self._bkgs = odict.OrderedDict()\n self._errors = None\n self._verbose = False\n\n @property\n def properties(self):\n return self._properties\n\n def _add(self, name, collection, h, **kwargs):\n collection[name] = (h,kwargs) \n\n def setautosort(self, auto=True):\n self._autosort = auto\n\n def setorder(self, order=None):\n self._order = order\n\n def seterror(self,eg):\n self._errors = eg\n\n def setdata(self, h):\n self._data = h\n\n def addsig(self, name, h, **kwargs):\n self._add( name, self._sigs, h, **kwargs) \n\n def addbkg(self, name, h, **kwargs):\n self._add( name, self._bkgs, h, **kwargs) \n\n def _fillvecs(self, collection ):\n\n # init the vectors\n vecs = {\n 'color' : ROOT.vector('int')(),\n# 'syst' : ROOT.vector('double')(),\n 'scale' : ROOT.vector('double')(),\n 'label' : ROOT.vector('std::string')(),\n 'norm' : ROOT.vector('double')(),\n 'th1' : ROOT.vector('TH1*')(),\n }\n \n\n # order takes precedence\n if self._order:\n iproc = self._order\n elif self._autosort:\n iproc = self._properties.iterkeys()\n else:\n iproc = collection.iterkeys()\n\n \n # and fill them\n for name in iproc:\n try:\n (h,props) = collection[name]\n except KeyError:\n # some of the processes might not be there\n continue\n # \n dummy = self._properties[name].copy()\n dummy.update(props)\n\n sentry = utils.TH1AddDirSentry()\n\n vecs['th1'] .push_back(h.Clone())\n vecs['label'].push_back( dummy.get('label',h.GetTitle() ) )\n vecs['color'].push_back( dummy.get('color',h.GetFillColor() ) )\n vecs['scale'].push_back( dummy.get('scale',1. ) )\n # negative normalisation is not applied\n vecs['norm'] .push_back( dummy.get('norm',-1. ) )\n\n return vecs\n\n # ---\n def prepare(self):\n if not self._verbose: sentry = NullStdOutSentry()\n\n if self._data: self.setDataHist(self._data)\n if self._errors: self.set_ErrorBand(self._errors)\n\n vecSig = self._fillvecs(self._sigs)\n vecBkg = self._fillvecs(self._bkgs)\n\n \n self.set_vectTHSig(vecSig['th1'])\n self.set_vectNameSig(vecSig['label'])\n self.set_vectColourSig(vecSig['color'])\n\n self.set_vectTHBkg(vecBkg['th1'])\n self.set_vectNameBkg(vecBkg['label'])\n self.set_vectColourBkg(vecBkg['color'])\n\n super(HWWPlot,self).prepare()\n\n # ---\n def draw(self,*args,**kwargs):\n if not self._verbose: sentry = NullStdOutSentry()\n super(HWWPlot,self).Draw(*args,**kwargs)\n \n # ---\n def mergeSamples(self,*args,**kwargs):\n if not self._verbose: sentry = NullStdOutSentry()\n super(HWWPlot,self).mergeSamples(*args,**kwargs)\n\nif __name__ == '__main__':\n # \n pass\n","sub_path":"ShapeAnalysis/python/hwwplot.py","file_name":"hwwplot.py","file_ext":"py","file_size_in_byte":5407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"74078705","text":"import pandas as pd\nimport plotly\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\nplotly.tools.set_credentials_file(username='anirudhkovuru', api_key='tAqAyR74bwrdbpQ02JxS')\n\nt_data = pd.read_csv('./stocks/AAL.csv')\nt_data = t_data.iloc[1:6, :]\nprint(t_data)\n\ntrace = go.Candlestick(x=t_data.date,\n open=t_data.open,\n high=t_data.high,\n low=t_data.low,\n close=t_data.close)\ndata = [trace]\nlayout = {\n 'title': 'Trends in AAL stocks',\n 'yaxis': {'title': 'AAL Stock'},\n 'xaxis': {\n 'title': 'Dates',\n 'rangeslider': {\n 'visible': False\n }\n },\n}\n\nfig = dict(data=data, layout=layout)\npy.iplot(fig, filename='simple_candlestick')\n","sub_path":"plot_vals.py","file_name":"plot_vals.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"220914591","text":"#!/usr/bin/env python3\n\"\"\"\n Author: Abdulrahman7ossam\n Version: 1.1\n Date: Sunday, June 5th 2015\n Description: This application uses the monte carlo simulation to estimate\n pi and then output the estimated value of pi with how far the\n calculated value is off the real one.\n\"\"\"\nfrom random import random\nimport time\nimport sys\n\n###\n# Object class for the simulation\n###\nclass MonteCarloSimulator(object):\n\n def __init__(self, value):\n self.value = value\n\n if sys.platform == \"win32\":\n self.G = ''\n self.R = ''\n self.END = ''\n else:\n self.G = '\\033[92m'\n self.R = '\\033[1;31m'\n self.END = '\\033[0m'\n\n def unit_circle(self, x, y):\n if (x ** 2 + y ** 2) <= 1:\n return True\n else:\n return False\n\n def simulate(self):\n print(\"\\nProcessing calculations with a repetition value of \" + self.R +\n str(self.value) + self.END + \" times.\")\n\n area_of_circle = 0\n area_of_square = 0\n\n start = time.clock()\n\n for i in range(1, self.value):\n x = random()\n y = random()\n\n if self.unit_circle(x, y):\n area_of_circle += 1\n area_of_square += 1\n\n pi = (area_of_circle * 4) / area_of_square\n\n runtime = time.clock() - start\n\n print(\"\\tCalculated Pi = \" + self.G + str(pi) + self.END +\n \" ({0} seconds, {1} minutes)\".format(round(runtime, 10),\n round(runtime / 60, 10)))\n\n print(\"Estimated Num of Pi is off by\", abs(pi - 3.14159265359))\n\n###\n# Tells the computer what to do\n###\ndef main():\n values = [1000, 10000, 100000, 1000000, 10000000, 100000000,1000000000, 10000000000]\n for value in values: MonteCarloSimulator(value).simulate()\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n print(\"\\nQuitting...\")\n sys.exit(1)\n","sub_path":"MonteCarloSimulation(EstimationOfPi).py","file_name":"MonteCarloSimulation(EstimationOfPi).py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"101856665","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jul 14 15:13:53 2017\nsimplified Foster Friess active growth strategy, use only one period data\n\nhttps://www.joinquant.com/post/3568?f=wx\n\n2017.07.14\n@author: talen\n\"\"\"\nimport pandas as pd\nimport os\nimport numpy as np\nos.chdir(os.getcwd())\n# data = pd.read_excel('用于积极成长策略的财务指标.xlsx')\ndata = pd.read_excel('用于积极成长策略的财务指标沪深300.xlsx')\ncolumns = data.columns\nfor i,u in enumerate(columns):\n if '资产负债率' in u:\n debt_index = u\n if '市盈率' in u:\n pe_index = u\n if '营业利润' in u:\n prof_index = u\n if '主营业务' in u:\n main_b_index = u\n\ntmp_debt = np.array(data[debt_index])\ndebt_stock_index = []\nfor i,u in enumerate(tmp_debt):\n if isinstance(u,float) and u < 50:\n debt_stock_index.append(i)\ndel tmp_debt\n\ntmp_pe = np.array(data[pe_index])\npe_stock_index = []\npe_threshold = 25\nfor i,u in enumerate(tmp_pe):\n if isinstance(u,float) and u < pe_threshold and u > 0:\n pe_stock_index.append(i)\ndel tmp_pe\n\ntmp_prof = np.array(data[prof_index])\nprof_stock_index = []\nprof_threshold = 10\nfor i,u in enumerate(tmp_prof):\n if isinstance(u,float) and u > prof_threshold:\n prof_stock_index.append(i)\ndel tmp_prof\n\ntmp_main_b = np.array(data[main_b_index])\nmain_b_stock_index = []\nmain_b_threshold = 80\nfor i,u in enumerate(tmp_main_b):\n if isinstance(u,float) and u > main_b_threshold:\n main_b_stock_index.append(i)\ndel tmp_main_b\n\nselected_index = list(set(main_b_stock_index) & set(prof_stock_index) & set(pe_stock_index) & set(debt_stock_index))\n\nstocks_selected = data.loc[selected_index]\nprint(\"Results are stored in the variable 'stocks_selected'.\")\n","sub_path":"runme.py","file_name":"runme.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"637147335","text":"\"\"\"\n\n Objects representing quotes. Simple right now.\n\n\"\"\"\nimport arrow\nfrom .assets import asset_factory, Option\nfrom .logic.ivolat3_option_greeks import get_option_greeks\n\n\ndef quote_factory(quote_date, asset, price = None, estimator=None):\n asset = asset_factory(asset)\n if isinstance(asset, Option):\n return OptionQuote(quote_date, asset, price, estimator)\n else:\n return Quote(quote_date, asset, price, estimator)\n\n\nclass Quote(object):\n\n def __init__(self, quote_date, asset, price=None, bid=0.0, ask=0.0, bid_size=0, ask_size=0):\n self.asset = asset_factory(asset)\n self.quote_date = quote_date\n self.bid = float(bid) if bid is not None else 0.0\n self.ask = float(ask) if ask is not None else 0.0\n self.bid_size = float(bid_size) if bid_size is not None else 0\n self.ask_size = float(ask_size) if ask_size is not None else 0\n self.price = float(price) if price is not None else None\n\n if self.price is None and self.bid + self.ask != 0.0:\n self.price = ((self.bid + self.ask) / 2)\n\n def is_priceable(self):\n return self.price is not None\n\n\n\n\n\nclass OptionQuote(Quote):\n def __init__(self, quote_date, asset, price=None, bid=0.0, ask=0.0, bid_size=0, ask_size=0, delta=None, iv=None, gamma=None, vega=None, theta=None, rho=None, underlying_price=None):\n super(OptionQuote, self).__init__(quote_date=quote_date, asset=asset, price=price, bid=bid, ask=ask, bid_size=bid_size, ask_size=ask_size)\n if not isinstance(self.asset, Option):\n raise Exception(\"OptionQuote(Quote): Must pass an option to create an option quote\");\n self.quote_type = 'option'\n self.days_to_expiration = (arrow.get(self.asset.expiration_date) - arrow.get(self.quote_date)).days\n\n if self.is_priceable() and underlying_price is not None:\n greeks = get_option_greeks(self.asset.option_type, self.asset.strike, underlying_price, self.days_to_expiration, self.price, dividend=0.0)\n self.delta = greeks['delta']\n self.iv = greeks['iv']\n self.gamma = greeks['gamma']\n self.vega = greeks['vega']\n self.theta = greeks['theta']\n self.rho = greeks['rho']\n else:\n self.delta = delta\n self.iv = iv\n self.gamma = gamma\n self.vega = vega\n self.theta = theta\n self.rho = rho\n\n def has_greeks(self):\n return self.iv is not None\n\n def get_intrinsic_value(self, underlying_price = None):\n return self.asset.get_intrinsic_value(underlying_price=underlying_price)\n\n def get_extrinsic_value(self, underlying_price=None):\n return self.asset.get_extrinsic_value(underlying_price=underlying_price, price=self.price)\n\n\n","sub_path":"paperbroker/quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"444404934","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.conf import settings\nfrom django.core.management import BaseCommand\nfrom rest_framework.exceptions import ValidationError\nimport ldb\nfrom samba4ui.models import DnsRecord\nfrom samba4ui.serializers import DnsRecordSerializer, DnsZoneSerializer, GroupSerializer\nfrom samba4ui.utils import get_samdb\n\n__author__ = 'Matthieu Gallet'\n\n\nclass Command(BaseCommand):\n def handle(self, *args, **options):\n\n\n print('-----------------------------------------------------------------')\n print('test_group')\n print('-----------------------------------------------------------------')\n\n print(GroupSerializer.list())\n group_name = 'TestGroup'\n serializer = GroupSerializer(data={'name': group_name, 'gid': 42, 'description': 'Ceci est une description',\n 'group_scope': 'Domain', 'group_type': 'Security', 'mail_address': 'test@test.org', })\n if serializer.is_valid():\n try:\n serializer.save()\n except ValueError:\n pass\n print(GroupSerializer.list())\n group = GroupSerializer.get_object(group_name)\n print(group)\n GroupSerializer.delete(group_name)\n print(GroupSerializer.list())\n","sub_path":"samba4ui/management/commands/test_smb.py","file_name":"test_smb.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"373373830","text":"\"\"\"\n72. Edit Distance\nGiven two words word1 and word2, find the minimum number of operations required to convert word1 to word2.\n\nYou have the following 3 operations permitted on a word:\n\nInsert a character\nDelete a character\nReplace a character\n\nExample 1:\nInput: word1 = \"horse\", word2 = \"ros\"\nOutput: 3\nExplanation: \nhorse -> rorse (replace 'h' with 'r')\nrorse -> rose (remove 'r')\nrose -> ros (remove 'e')\n\nExample 2:\nInput: word1 = \"intention\", word2 = \"execution\"\nOutput: 5\n\nExplanation: \nintention -> inention (remove 't')\ninention -> enention (replace 'i' with 'e')\nenention -> exention (replace 'n' with 'x')\nexention -> exection (replace 'n' with 'c')\nexection -> execution (insert 'u')\n\"\"\"\n# Time complexity: O(N*M)\n# Space complexity: O(N*M)\nclass Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n n = len(word1)\n m = len(word2)\n \n if n*m == 0:\n return n+m\n \n d = [[0] * (m+1) for _ in range(n+1)]\n \n for i in range(1, n+1):\n d[i][0] = i\n \n for j in range(1, m+1):\n d[0][j] = j\n \n for i in range(1, n+1):\n for j in range(1, m+1):\n left = d[i-1][j] + 1\n down = d[i][j-1] + 1\n diag = d[i-1][j-1]\n if word1[i-1] != word2[j-1]:\n diag += 1\n d[i][j] = min(left, down, diag)\n return d[n][m]\n","sub_path":"Leetcode/72. Edit Distance.py","file_name":"72. Edit Distance.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"611358942","text":"import os\nimport csv\nimport numpy as np\nimport pickle\nimport random\nfrom pathlib import Path\nfrom tqdm import tqdm\n\nimport pandas as pd\nfrom datasets import load_dataset, load_metric, Dataset\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom ast import literal_eval\n\nimport torch\nfrom transformers import AutoModelForSeq2SeqLM, AutoTokenizer\nfrom transformers import set_seed, DataCollatorForSeq2Seq\nfrom transformers import Seq2SeqTrainer, Seq2SeqTrainingArguments\nfrom transformers.utils import check_min_version\n\n\n# Will error if the minimal version of Transformers is not installed. Remove at your own risks.\ncheck_min_version(\"4.6.0.dev0\")\n\ndef generate_examples(row):\n hid1, hid2 = row['hid1'], row['hid2']\n loss1, loss2 = row['loss1'], row['loss2']\n diff1, diff2 = row['diff1'], row['diff2']\n ctx1, ctx2 = row['ctx1'], row['ctx2']\n ocr1, ocr2 = ctx1[diff1[0]:diff1[1]], ctx2[diff2[0]:diff2[1]]\n ex1 = ' '.join(ctx1[:diff1[0]]) + ' ' + ' '.join(ocr1) + ' ' + ' '.join(ctx1[diff1[1]:])\n ex2 = ' '.join(ctx2[:diff2[0]]) + ' ' + ' '.join(ocr2) + ' ' + ' '.join(ctx2[diff2[1]:])\n correct = \"\"\n if loss1 < loss2:\n if ocr1:\n correct = ' '.join(ocr1)\n return hid2, ex2, correct\n else:\n if ocr2:\n correct = ' '.join(ocr2)\n return hid1, ex1, correct\n\ndef preprocess_function(examples):\n inputs = examples['orig']\n targets = examples['corrected']\n inputs = [inp for inp in inputs]\n model_inputs = tokenizer(inputs, padding=True, truncation=True)\n\n # Setup the tokenizer for targets\n with tokenizer.as_target_tokenizer():\n labels = tokenizer(targets, padding=True, truncation=True)\n\n # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore\n # padding in the loss.\n labels[\"input_ids\"] = [\n [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels[\"input_ids\"]\n ]\n\n model_inputs[\"labels\"] = labels[\"input_ids\"]\n return model_inputs\n\n\nseed = 1729\nset_seed(seed)\nmodel_name = \"ocr_correction_model\"\n\nprint(\"Loading tokenizer\")\ntokenizer = AutoTokenizer.from_pretrained(model_name)\n\ntokenizer.add_tokens([\"\", \" \", \"\"], special_tokens=True) \ntokenizer.add_special_tokens({\"additional_special_tokens\": [\"\", \" \", \"\"]})\n\nprint(\"Loading test\")\nnum_samples = 200000\ntestp = Path('/home/allekim/ocr-detection/ocr_data/test.csv')\ndf = pd.read_csv(testp, converters={'ctx1': eval, 'ctx2': eval, 'diff1': eval, 'diff2': eval}, nrows=num_samples)\ndf = df.sample(num_samples, random_state=seed)\ndf[['hid', 'orig','corrected']] = df.apply(generate_examples, axis=1, result_type=\"expand\")\ntest_dataset = Dataset.from_pandas(df[['hid', 'orig', 'corrected']])\n\ntest_dataset = test_dataset.map(\n preprocess_function,\n batched=True,\n batch_size=None,\n num_proc=1,\n)\n\nprint(\"Loading model\")\nmodel = AutoModelForSeq2SeqLM.from_pretrained(model_name)\nmodel.resize_token_embeddings(len(tokenizer))\ndevice = \"cuda:4\"\nmodel.to(device)\n\nprint(\"Evaluating\")\nresults = []\ni = 0\nbatch_size = 64\nfor i in tqdm(range(0,len(test_dataset), batch_size)):\n x = test_dataset[i:i+batch_size]\n input_ids = torch.tensor(x['input_ids']).to(device)\n attention_mask = torch.tensor(x['attention_mask']).to(device)\n result = model.generate(input_ids=input_ids, attention_mask=attention_mask, output_scores=True, return_dict_in_generate=True)\n for j in range(len(x)):\n scores = np.array([y[j].detach().cpu().numpy() for y in result.scores])\n generated = result.sequences[j].detach().cpu().numpy()\n end_idx = np.where(generated==1)[0]\n if len(end_idx) > 0:\n outtoks = tokenizer.convert_ids_to_tokens(generated)\n final_string = tokenizer.convert_tokens_to_string(outtoks[1:end_idx[0]])\n results.append((x['hid'][j], x['orig'][j], x['corrected'][j], final_string, scores))\n\nwith open('results.pkl', 'wb') as f:\n pickle.dump(results, f, 4)\n\"\"\"\ndf = pd.DataFrame(results, columns=['sent', 'truth', 'gen', 'scores'])\ndf.to_csv('new_results.csv')\n\"\"\"\n","sub_path":"ocr_correction/eval_t5.py","file_name":"eval_t5.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"257314797","text":"# -*- coding: utf-8\nimport numpy as np\n\n# 移動平均線の計算(データ, 日数)\ndef move_average(data, day):\n return np.convolve(data, np.ones(day)/float(day), 'valid')\n\n# 重回帰分析(偏回帰係数の計算)\ndef stat(y, x):\n x = np.vstack([np.ones(x.shape[1]), x]) # 定数項, 説明変数\n return np.linalg.lstsq(x.T, y)[0] # 偏回帰係数\n\n# 前日から上昇・下落のチェック\ndef ud(f):\n # 勾配を計算\n df = np.gradient(f)\n df[df > 0] = 1\n df[df == 0] = 0\n df[df < 0] = -1\n\n return df\n \ndef main():\n # CSVのロード(2014年~2016年のデータ)\n data14 = np.genfromtxt(\"nikkei14.csv\", delimiter=\",\", skip_header=1, dtype='float')\n data15 = np.genfromtxt(\"nikkei15.csv\", delimiter=\",\", skip_header=1, dtype='float')\n data16 = np.genfromtxt(\"nikkei16.csv\", delimiter=\",\", skip_header=1, dtype='float')\n\n # 5列目の終値だけを古い順に並び替えて取り出し\n f14, f15, f16 = data14[:,4], data15[:,4], data16[:,4]\n f14, f15, f16 = f14[::-1], f15[::-1], f16[::-1]\n\n # 2015年分と2016年分の移動平均線を計算\n days = [5, 25, 75, 200]\n for day in days:\n data15 = np.r_[f14[len(f14)-day:len(f14)-1], f15] # 2015年の終値の一部と2016年の終値を結合\n data16 = np.r_[f15[len(f15)-day:len(f15)-1], f16] # 2015年の終値の一部と2016年の終値を結合\n if(day == days[0]):\n ma15 = move_average(data15, day)\n ma16 = move_average(data16, day)\n ma15 = np.vstack([ma15, move_average(data15, day)])\n ma16 = np.vstack([ma16, move_average(data16, day)])\n\n # 説明変数(2015年の移動平均線(前日)) \n x = np.array([ma15[0], ma15[1]])\n\n # 重回帰分析(偏回帰係数の計算)\n b, a1, a2 = stat(f15, x)\n \n # (前日の移動平均線)+(2015年データで求めた偏回帰係数)→2016年の株価を予測\n f16h = a1 * ma16[0] + a2 * ma16[1] + b\n \n df16 = ud(f16)\n df16h = ud(f16h)\n \n # 差分を計算\n result = df16 - df16h\n \n # 差分が0(当たり)の個数を計算\n hit = len(result) - np.count_nonzero(result)\n \n # 当たりの確率をパーセント表示\n score = 100*hit/len(result)\n print(round(score, 3), \"[%]\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/numpy/Stock/Nikkei/multiple_regression_x2_ma_result.py","file_name":"multiple_regression_x2_ma_result.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"459894270","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport os\r\nfrom six.moves.urllib.request import urlopen\r\nimport shutil\r\n\r\nfrom PIL import Image\r\nimport PIL.ImageOps\r\n\r\nimport numpy as np\r\n\r\nimport tensorflow as tf\r\n\r\n# récupération des bases de données\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n\r\nmnist = input_data.read_data_sets('./MNIST_data/')\r\n\r\n\r\n# Specify that all features have real-value data\r\nfeature_columns = [tf.feature_column.numeric_column(\"x\", shape=[784])]\r\n\r\n# sauvegarde en fin d'apprentissage\r\n# If the model_dir exists, we delete it.\r\n# to avoid accidental multiple trainings.\r\nvisuPath = './VisuDnn'\r\nif os.path.exists(visuPath):\r\n shutil.rmtree(visuPath)\r\nos.makedirs(visuPath)\r\n\r\n# Build 3 layer DNN with 10, 20, 10 units respectively.\r\nclassifier = tf.estimator.DNNClassifier(\r\n feature_columns=feature_columns,\r\n hidden_units=[256, 32],\r\n optimizer=tf.train.AdamOptimizer(1e-4),\r\n n_classes=10,\r\n dropout=0.1,\r\n model_dir=visuPath\r\n)\r\n\r\ndef input(dataset):\r\n return dataset.images, dataset.labels.astype(np.int32)\r\n \r\ndef getFeatures(dataset):\r\n return dataset.images\r\n\r\ndef getLabels(dataset):\r\n return dataset.labels.astype(np.int32)\r\n\r\n \r\n# Define the training inputs\r\ntrain_input_fn = tf.estimator.inputs.numpy_input_fn(\r\n x={\"x\": getFeatures(mnist.train)},\r\n y=getLabels(mnist.train),\r\n num_epochs=None,\r\n batch_size=50,\r\n shuffle=True\r\n)\r\n\r\n# Train model.\r\nclassifier.train(input_fn=train_input_fn, steps=10000)\r\n\r\n\r\n# Save Model\r\n\r\ndef serving_input_receiver_fn():\r\n feature_spec = {'x': tf.FixedLenFeature([784],tf.float32)}\r\n serialized_tf_example = tf.placeholder(dtype=tf.string,\r\n shape=[None],\r\n name='input_tensors')\r\n receiver_tensors = {'inputs': serialized_tf_example}\r\n features = tf.parse_example(serialized_tf_example, feature_spec)\r\n return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)\r\n\r\nsavePath = './SavedNetworksEstimator'\r\nif os.path.exists(savePath):\r\n shutil.rmtree(savePath)\r\nos.makedirs(savePath)\r\n \r\nclassifier.export_savedmodel(savePath, serving_input_receiver_fn)\r\n\r\n## Supression du repertoire Timestamp, remplace par lastSave\r\nfolderName = os.listdir(savePath)[0]\r\nfolderFullName = os.path.join(savePath, folderName)\r\ntargetFullName = os.path.join(savePath, 'lastSave')\r\n\r\nshutil.move(folderFullName,targetFullName)\r\n\r\n\r\n# Evaluation sur la base d'apprentissage\r\ntrain_input_eval_fn = tf.estimator.inputs.numpy_input_fn(\r\n x={\"x\": getFeatures(mnist.train)},\r\n y=getLabels(mnist.train),\r\n num_epochs=1,\r\n shuffle=False\r\n)\r\n\r\naccuracy_score = classifier.evaluate(input_fn=train_input_eval_fn)[\"accuracy\"]\r\nprint(\"Learning Accuracy: {0:f}\\n\".format(accuracy_score))\r\n\r\n# Define the test inputs\r\ntest_input_fn = tf.estimator.inputs.numpy_input_fn(\r\n x={\"x\": getFeatures(mnist.test)},\r\n y=getLabels(mnist.test),\r\n num_epochs=1,\r\n shuffle=False\r\n)\r\n\r\n# Evaluate accuracy.\r\naccuracy_score = classifier.evaluate(input_fn=test_input_fn)[\"accuracy\"]\r\n\r\nprint(\"Test Accuracy: {0:f}\\n\".format(accuracy_score))\r\n\r\n","sub_path":"TutosPython/Mnist/mnistDnnEstimatorTrain.py","file_name":"mnistDnnEstimatorTrain.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"575950776","text":"import math, random\nimport pygame as pg\nfrom .. import setup\n\n\nclass Person(pg.sprite.Sprite):\n \"\"\"Base class for all world characters\n controlled by the computer\"\"\"\n\n def __init__(self, sheet_key, x, y, direction='down', state='resting', index=0):\n super(Person, self).__init__()\n self.name = sheet_key\n self.get_image = setup.tools.get_image\n self.spritesheet_dict = self.create_spritesheet_dict(sheet_key)\n self.animation_dict = self.create_animation_dict()\n self.index = index\n self.direction = direction\n self.image_list = self.animation_dict[self.direction]\n self.image = self.image_list[self.index]\n self.rect = self.image.get_rect(left=x, top=y)\n self.origin_pos = self.rect.topleft\n self.state_dict = self.create_state_dict()\n self.vector_dict = self.create_vector_dict()\n self.x_vel = 0\n self.y_vel = 0\n self.timer = 0.0\n self.move_timer = 0.0\n self.current_time = 0.0\n self.state = state\n self.blockers = self.set_blockers()\n self.location = self.get_tile_location()\n self.dialogue = ['Location: ' + str(self.location)]\n self.default_direction = direction\n self.item = None\n self.wander_box = self.make_wander_box()\n\n def create_spritesheet_dict(self, sheet_key):\n \"\"\"Implemented by inheriting classes\"\"\"\n image_list = []\n image_dict = {}\n sheet = setup.GFX[sheet_key]\n\n image_keys = ['facing up 1', 'facing up 2',\n 'facing down 1', 'facing down 2',\n 'facing left 1', 'facing left 2',\n 'facing right 1', 'facing right 2']\n\n for row in range(2):\n for column in range(4):\n image_list.append(\n self.get_image(column*32, row*32, 32, 32, sheet))\n\n for key, image in zip(image_keys, image_list):\n image_dict[key] = image\n\n return image_dict\n\n def create_animation_dict(self):\n \"\"\"Return a dictionary of image lists for animation\"\"\"\n image_dict = self.spritesheet_dict\n\n left_list = [image_dict['facing left 1'], image_dict['facing left 2']]\n right_list = [image_dict['facing right 1'], image_dict['facing right 2']]\n up_list = [image_dict['facing up 1'], image_dict['facing up 2']]\n down_list = [image_dict['facing down 1'], image_dict['facing down 2']]\n\n direction_dict = {'left': left_list,\n 'right': right_list,\n 'up': up_list,\n 'down': down_list}\n\n return direction_dict\n\n def create_state_dict(self):\n \"\"\"Return a dictionary of all state methods\"\"\"\n state_dict = {'resting': self.resting,\n 'moving': self.moving,\n 'animated resting': self.animated_resting,\n 'autoresting': self.auto_resting,\n 'automoving': self.auto_moving,\n 'battle resting': self.battle_resting,\n 'attack': self.attack}\n\n return state_dict\n\n def create_vector_dict(self):\n \"\"\"Return a dictionary of x and y velocities set to\n direction keys.\"\"\"\n vector_dict = {'up': (0, -1),\n 'down': (0, 1),\n 'left': (-1, 0),\n 'right': (1, 0)}\n\n return vector_dict\n\n def update(self, current_time, *args):\n \"\"\"Implemented by inheriting classes\"\"\"\n self.blockers = self.set_blockers()\n self.current_time = current_time\n self.image_list = self.animation_dict[self.direction]\n state_function = self.state_dict[self.state]\n state_function()\n self.location = self.get_tile_location()\n\n\n\n def set_blockers(self):\n \"\"\"Sets blockers to prevent collision with other sprites\"\"\"\n blockers = []\n\n if self.state == 'resting' or self.state == 'autoresting':\n blockers.append(pg.Rect(self.rect.x, self.rect.y, 32, 32))\n\n elif self.state == 'moving' or self.state == 'automoving':\n if self.rect.x % 32 == 0:\n tile_float = self.rect.y / float(32)\n tile1 = (self.rect.x, math.ceil(tile_float)*32)\n tile2 = (self.rect.x, math.floor(tile_float)*32)\n tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)\n tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)\n blockers.extend([tile_rect1, tile_rect2])\n\n elif self.rect.y % 32 == 0:\n tile_float = self.rect.x / float(32)\n tile1 = (math.ceil(tile_float)*32, self.rect.y)\n tile2 = (math.floor(tile_float)*32, self.rect.y)\n tile_rect1 = pg.Rect(tile1[0], tile1[1], 32, 32)\n tile_rect2 = pg.Rect(tile2[0], tile2[1], 32, 32)\n blockers.extend([tile_rect1, tile_rect2])\n\n return blockers\n\n def get_tile_location(self):\n \"\"\"\n Convert pygame coordinates into tile coordinates.\n \"\"\"\n if self.rect.x == 0:\n tile_x = 0\n elif self.rect.x % 32 == 0:\n tile_x = (self.rect.x / 32)\n else:\n tile_x = 0\n\n if self.rect.y == 0:\n tile_y = 0\n elif self.rect.y % 32 == 0:\n tile_y = (self.rect.y / 32)\n else:\n tile_y = 0\n\n return [tile_x, tile_y]\n\n\n def make_wander_box(self):\n \"\"\"\n Make a list of rects that surround the initial location\n of a sprite to limit his/her wandering.\n \"\"\"\n x = int(self.location[0])\n y = int(self.location[1])\n box_list = []\n box_rects = []\n\n for i in range(x-3, x+4):\n box_list.append([i, y-3])\n box_list.append([i, y+3])\n\n for i in range(y-2, y+3):\n box_list.append([x-3, i])\n box_list.append([x+3, i])\n\n for box in box_list:\n left = box[0]*32\n top = box[1]*32\n box_rects.append(pg.Rect(left, top, 32, 32))\n\n return box_rects\n\n\n def resting(self):\n \"\"\"\n When the Person is not moving between tiles.\n Checks if the player is centered on a tile.\n \"\"\"\n self.image = self.image_list[self.index]\n\n assert(self.rect.y % 32 == 0), ('Player not centered on tile: '\n + str(self.rect.y) + \" : \" + str(self.name))\n assert(self.rect.x % 32 == 0), ('Player not centered on tile'\n + str(self.rect.x))\n\n def moving(self):\n \"\"\"\n Increment index and set self.image for animation.\n \"\"\"\n self.animation()\n assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \\\n 'Not centered on tile'\n\n def animated_resting(self):\n self.animation(500)\n\n def animation(self, freq=100):\n \"\"\"\n Adjust sprite image frame based on timer.\n \"\"\"\n if (self.current_time - self.timer) > freq:\n if self.index < (len(self.image_list) - 1):\n self.index += 1\n else:\n self.index = 0\n self.timer = self.current_time\n\n self.image = self.image_list[self.index]\n\n def begin_moving(self, direction):\n \"\"\"\n Transition the player into the 'moving' state.\n \"\"\"\n self.direction = direction\n self.image_list = self.animation_dict[direction]\n self.timer = self.current_time\n self.move_timer = self.current_time\n self.state = 'moving'\n\n if self.rect.x % 32 == 0:\n self.y_vel = self.vector_dict[self.direction][1]\n if self.rect.y % 32 == 0:\n self.x_vel = self.vector_dict[self.direction][0]\n\n\n def begin_resting(self):\n \"\"\"\n Transition the player into the 'resting' state.\n \"\"\"\n self.state = 'resting'\n self.index = 1\n self.x_vel = self.y_vel = 0\n\n def begin_auto_moving(self, direction):\n \"\"\"\n Transition sprite to a automatic moving state.\n \"\"\"\n self.direction = direction\n self.image_list = self.animation_dict[direction]\n self.state = 'automoving'\n self.x_vel = self.vector_dict[direction][0]\n self.y_vel = self.vector_dict[direction][1]\n self.move_timer = self.current_time\n\n def begin_auto_resting(self):\n \"\"\"\n Transition sprite to an automatic resting state.\n \"\"\"\n self.state = 'autoresting'\n self.index = 1\n self.x_vel = self.y_vel = 0\n self.move_timer = self.current_time\n\n\n def auto_resting(self):\n \"\"\"\n Determine when to move a sprite from resting to moving in a random\n direction.\n \"\"\"\n #self.image = self.image_list[self.index]\n self.image_list = self.animation_dict[self.direction]\n self.image = self.image_list[self.index]\n\n assert(self.rect.y % 32 == 0), ('Player not centered on tile: '\n + str(self.rect.y))\n assert(self.rect.x % 32 == 0), ('Player not centered on tile'\n + str(self.rect.x))\n\n if (self.current_time - self.move_timer) > 2000:\n direction_list = ['up', 'down', 'left', 'right']\n random.shuffle(direction_list)\n direction = direction_list[0]\n self.begin_auto_moving(direction)\n self.move_timer = self.current_time\n\n def battle_resting(self):\n \"\"\"\n Player stays still during battle state unless he attacks.\n \"\"\"\n pass\n\n def enter_attack_state(self, enemy):\n \"\"\"\n Set values for attack state.\n \"\"\"\n self.x_vel = 1\n self.state = 'attack'\n\n def attack(self):\n \"\"\"\n Player does an attack animation.\n \"\"\"\n SLOW_BACK = 1\n FAST_FORWARD = -5\n FAST_BACK = 5\n\n self.rect.x += self.x_vel\n\n if self.x_vel == SLOW_BACK:\n if self.rect.x >= self.origin_pos[0] + 10:\n self.x_vel = FAST_FORWARD\n elif self.x_vel == FAST_FORWARD:\n if self.rect.topleft >= self.origin_pos:\n self.image = self.spritesheet_dict['facing left 1']\n self.image = pg.transform.scale2x(self.image)\n elif self.rect.x <= self.origin_pos[0] - 100:\n self.x_vel = FAST_BACK\n else:\n if self.rect.x >= self.origin_pos[0]:\n self.rect.x = self.origin_pos[0]\n self.x_vel = 0\n self.state = 'battle resting'\n self.image = self.spritesheet_dict['facing left 2']\n self.image = pg.transform.scale2x(self.image)\n self.observer.on_notify('select action')\n\n\n\n def auto_moving(self):\n \"\"\"\n Animate sprite and check to stop.\n \"\"\"\n self.animation()\n\n assert(self.rect.x % 32 == 0 or self.rect.y % 32 == 0), \\\n 'Not centered on tile'\n\n\nclass Player(Person):\n \"\"\"\n User controlled character.\n \"\"\"\n\n def __init__(self, direction, x=0, y=0, state='resting', index=0):\n super(Player, self).__init__('player', x, y, direction, state, index)\n\n def create_vector_dict(self):\n \"\"\"Return a dictionary of x and y velocities set to\n direction keys.\"\"\"\n vector_dict = {'up': (0, -2),\n 'down': (0, 2),\n 'left': (-2, 0),\n 'right': (2, 0)}\n\n return vector_dict\n\n def update(self, keys, current_time):\n \"\"\"Updates player behavior\"\"\"\n self.blockers = self.set_blockers()\n self.keys = keys\n self.current_time = current_time\n self.check_for_input()\n state_function = self.state_dict[self.state]\n state_function()\n self.location = self.get_tile_location()\n\n def check_for_input(self):\n \"\"\"Checks for player input\"\"\"\n if self.state == 'resting':\n if self.keys[pg.K_UP]:\n self.begin_moving('up')\n elif self.keys[pg.K_DOWN]:\n self.begin_moving('down')\n elif self.keys[pg.K_LEFT]:\n self.begin_moving('left')\n elif self.keys[pg.K_RIGHT]:\n self.begin_moving('right')\n\n\n\n\nclass Well(pg.sprite.Sprite):\n \"\"\"Talking well\"\"\"\n def __init__(self, x, y):\n super(Well, self).__init__()\n self.image = pg.Surface((32, 32))\n self.image.set_colorkey((0,0,0))\n self.rect = self.image.get_rect(left=x, top=y)\n self.location = self.get_location()\n self.dialogue = [\"I'm a well!\"]\n self.blockers = [self.rect]\n self.x_vel = self.y_vel = 0\n self.state = 'resting'\n self.direction = 'down'\n self.default_direction = self.direction\n self.item = None\n self.wander_box = []\n\n def get_location(self):\n \"\"\"Get tile location\"\"\"\n x = self.rect.x / 32\n y = self.rect.y / 32\n\n return [x, y]\n\n def begin_auto_resting(self):\n \"\"\"Placeholder\"\"\"\n pass\n\n\n","sub_path":"data/components/person.py","file_name":"person.py","file_ext":"py","file_size_in_byte":13219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"40918626","text":"#!/usr/bin/python\nimport os\nimport time\n\nfrom apcaccess import status as apc\nfrom influxdb import InfluxDBClient\n\nhostname = os.getenv('HOSTNAME', 'apcupsd-influxdb-exporter')\ndbname = os.getenv('INFLUXDB_DATABASE', 'apcupsd')\nuser = os.getenv('INFLUXDB_USER')\npassword = os.getenv('INFLUXDB_PASSWORD')\nport = os.getenv('INFLUXDB_PORT', 8086)\nhost = os.getenv('INFLUXDB_HOST', 'localhost')\nclient = InfluxDBClient(host, port, user, password, dbname)\n\nclient.create_database(dbname)\n\nwhile True:\n ups = apc.parse(apc.get(host=os.getenv('APCUPSD_HOST', 'localhost')), strip_units=True)\n\n if os.environ['WATTS']:\n ups['NOMPOWER'] = os.getenv('WATTS')\n\n watts = float(ups['NOMPOWER']) * 0.01 * float(ups['LOADPCT'])\n json_body = [\n {\n 'measurement': 'apcaccess_status',\n 'fields': {\n 'WATTS': watts,\n 'LOADPCT': float(ups['LOADPCT']),\n 'BCHARGE': float(ups['BCHARGE']),\n 'TONBATT': float(ups['TONBATT']),\n 'TIMELEFT': float(ups['TIMELEFT']),\n 'NOMPOWER': float(ups['NOMPOWER']),\n 'CUMONBATT': float(ups['CUMONBATT']),\n 'BATTV': float(ups['BATTV']),\n 'OUTPUTV': float(ups['OUTPUTV']),\n 'ITEMP': float(ups['ITEMP'])\n },\n 'tags': {\n 'host': hostname\n }\n }\n ]\n\n if os.getenv('VERBOSE', 'false').lower() == 'true':\n print(json_body)\n print(client.write_points(json_body))\n else:\n client.write_points(json_body)\n time.sleep(5)\n","sub_path":"apcupsd-influxdb-exporter.py","file_name":"apcupsd-influxdb-exporter.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"512686622","text":"import os\nimport sys\n\nsys.path.append(os.getcwd())\n\nimport utils.runners as urun\n\nif __name__ == \"__main__\":\n exp_folder = \"experiments_2\"\n exp = \"bs3_exp5\"\n runner = urun.get_runner(sys.argv[1])\n run = 0\n for hidden in [0.2, 0.4]:\n for reg_type in ['l1', 'l2']:\n for reg_lambda in [1e-1, 1e-3, 1e-5, 1e-7, 1e-9]:\n runner(\n exp_folder, exp,\n f\"--exp_folder={exp_folder} --exp={exp} --run={run} --hidden={hidden} --reg_lambda={reg_lambda} --reg_type={reg_type}\", \n run\n )\n run += 1\n","sub_path":"experiments/experiments_2/bs3_exp5_runner.py","file_name":"bs3_exp5_runner.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"407531908","text":"class Solution:\n def searchMatrix(self, matrix, target):\n height = len(matrix)\n if height == 0:\n return False\n width = len(matrix[0])\n\n left = 0\n right = height * width - 1\n\n get_coords = lambda i: (i // width, i % width)\n\n while left <= right:\n middle = (right + left) // 2\n i, j = get_coords(middle)\n\n if matrix[i][j] == target:\n return True\n elif matrix[i][j] < target:\n left = middle + 1\n else:\n right = middle - 1\n\n return False\n\n\nclass TestSolution:\n\n def __init__(self):\n self.solution = Solution()\n\n def test_one_number_target_found(self):\n matrix = [[1]]\n target = 1\n\n expected = True\n actual = self.solution.searchMatrix(matrix, target)\n\n assert actual == expected\n\n def test_one_number_target_not_found(self):\n matrix = [[1]]\n target = 2\n\n expected = False\n actual = self.solution.searchMatrix(matrix, target)\n\n assert actual == expected\n\n def test_many_numbers_target_found(self):\n matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n\n target = 6\n\n expected = True\n actual = self.solution.searchMatrix(matrix, target)\n\n assert actual == expected\n\n def test_many_numbers_target_not_found(self):\n matrix = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12]\n ]\n\n target = 15\n\n expected = False\n actual = self.solution.searchMatrix(matrix, target)\n\n assert actual == expected\n\n def run_test(self, test, test_name):\n print('Running {}...'.format(test_name))\n\n try:\n test()\n except:\n print('Failed {}'.format(test_name))\n else:\n print('Passed {}!'.format(test_name))\n\n def run_tests(self):\n self.run_test(self.test_one_number_target_found, 'test_one_number_target_found')\n self.run_test(self.test_one_number_target_not_found, 'test_one_number_target_not_found')\n self.run_test(self.test_many_numbers_target_found, 'test_many_numbers_target_found')\n self.run_test(self.test_many_numbers_target_not_found, 'test_many_numbers_target_not_found')\n\n\ntester = TestSolution()\ntester.run_tests()\n","sub_path":"74_search_a_2d_matrix.py","file_name":"74_search_a_2d_matrix.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"570660370","text":"\"\"\"\nView for the website\n\"\"\"\nimport logging\nimport velruse\nimport colander\nfrom datetime import date\nfrom pyramid.httpexceptions import HTTPFound\nfrom pyramid.view import view_config\nfrom pyramid.security import has_permission, Authenticated\nfrom .models import Talk, TalkForm\n\nLOG = logging.getLogger(__name__)\n\n\n@view_config(route_name='root', renderer='index.jinja2')\ndef index(request):\n \"\"\" Render the base template \"\"\"\n return {'logged_in': has_permission('logged_in', request.context, request),\n 'can_upload': has_permission('upload', request.context, request),\n }\n\n@view_config(route_name='upload', request_method='POST', renderer='json', permission='upload')\ndef do_upload(request):\n \"\"\" Handle a form upload \"\"\"\n try:\n appstruct = TalkForm().deserialize(request.POST) #pylint: disable=E1101\n except colander.Invalid as e:\n return {'status':1, 'errors':e.asdict()}\n title = appstruct['title']\n author = appstruct['author']\n content = appstruct['content']\n desc = appstruct['description']\n month, day, year = [int(s) for s in appstruct['date'].split('/')]\n talk_date = date(year, month, day)\n if request.db.query(Talk).filter_by(title=title).first() is not None:\n return {'status':1, 'errors':\n {'title':'A talk with that name already exists!'}}\n new_talk = Talk(title, author, desc, talk_date, content)\n request.db.add(new_talk)\n return {'status':0, 'msg':'success'}\n\n@view_config(route_name='delete', request_method='DELETE', renderer='json', permission='delete')\ndef do_delete(request):\n \"\"\" Delete a talk \"\"\"\n talk = request.db.query(Talk).filter_by(id=request.matchdict['id']).first()\n request.db.delete(talk)\n return {'status':0}\n\n@view_config(route_name='talks', renderer='talk_list.jinja2')\ndef get_talks(request):\n \"\"\" Get a list of all talks ordered by date \"\"\"\n return {'talks':request.db.query(Talk).order_by(Talk.date.desc()).all()}\n\n@view_config(route_name='talk', renderer='talk.jinja2')\ndef get_talk(request):\n \"\"\" Get a single talk by id \"\"\"\n talk = request.db.query(Talk).filter_by(id=request.matchdict['id']).first()\n return {'talk': talk,\n 'can_delete':has_permission('delete', request.context, request),\n }\n\n@view_config(route_name='login')\ndef do_login(request):\n \"\"\" Store the redirect in the session and log in with google \"\"\"\n if 'next' in request.GET:\n request.session['next'] = request.GET['next']\n raise HTTPFound(location=velruse.login_url(request, 'google'))\n\n@view_config(route_name='logout')\ndef do_logout(request):\n \"\"\" Log the user out \"\"\"\n request.session.delete()\n raise HTTPFound(location=request.route_url('root'))\n\n@view_config(context='velruse.AuthenticationComplete')\ndef on_login(request):\n \"\"\" Called when a user successfully logs in \"\"\"\n context = request.context\n email, domain = context.profile['verifiedEmail'].split('@')\n if domain == 'highlig.ht':\n request.session['username'] = email\n next_url = request.session.pop('next', request.route_url('root'))\n raise HTTPFound(location=next_url)\n\n@view_config(context='velruse.AuthenticationDenied')\ndef on_login_denied(request):\n \"\"\" Called when the login is denied \"\"\"\n raise HTTPFound(location=request.route_url('root'))\n","sub_path":"mathclass/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"131371377","text":"## 01 Matrix\n\n# Example 1:\n# Input: mat = [[0,0,0],[0,1,0],[0,0,0]]\n# Output: [[0,0,0],[0,1,0],[0,0,0]]\n\n# Example 2:\n# Input: mat = [[0,0,0],[0,1,0],[1,1,1]]\n# Output: [[0,0,0],[0,1,0],[1,2,1]]\n\n# import math\nclass Solution:\n def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:\n \n M = len(mat)\n N = len(mat[0])\n \n visited = set()\n tempQ = []\n for i in range(M):\n for j in range(N):\n if mat[i][j]==0:\n tempQ.append((i,j))\n visited.add((i, j))\n \n \n dist = 0\n while tempQ:\n #print(\"Level: {}\\nQueue: {}\\nVisited: {}\\n\".format(dist, tempQ, visited))\n size = len(tempQ)\n for _ in range(size):\n \n (currX, currY) = tempQ.pop(0)\n #print(currX, currY)\n \n mat[currX][currY] = dist\n \n ## Add Neighbors\n if currX+1 < M and (currX+1, currY) not in visited:\n tempQ.append((currX+1, currY))\n visited.add((currX+1, currY))\n if 0 <= currX-1 and (currX-1, currY) not in visited:\n tempQ.append((currX-1, currY))\n visited.add((currX-1, currY))\n if currY+1 < N and (currX, currY+1) not in visited:\n tempQ.append((currX, currY+1))\n visited.add((currX, currY+1))\n if 0 <= currY-1 and (currX, currY-1) not in visited:\n tempQ.append((currX, currY-1))\n visited.add((currX, currY-1))\n \n dist+=1\n #print('-'*25) \n return mat\n \n \n# def helper(row, col, level):\n# #print(\"R:{} C:{} L:{}\".format(row,col,level))\n# if row<0 or row>M-1 or col<0 or col>N-1 or level>M+N:\n# return math.inf\n# elif mat[row][col]==0:\n# return level\n \n# return min(helper(row,col-1,level+1),\n# helper(row-1,col,level+1),\n# helper(row+1,col,level+1),\n# helper(row,col+1,level+1))\n# i=0\n# visitedHM = {}\n# while i epsilon and it < 100):\n alpha = self.forward(obs)\n beta = self.backward(obs)[1:]\n # E step\n xi = np.zeros((self.s_num, self.s_num))\n likelihood = (alpha * beta).T\n gamma = likelihood / likelihood.sum(axis=0).reshape(1, -1)\n xi = alpha[:-1].T.dot((beta[1:] / likelihood[:, :-1].sum(\n axis=0).reshape(-1, 1)) * self.B[:, obs[1:]].T) * self.A\n\n # M step\n self.pi = (beta[1, :] * self.B[:, obs[1]] / likelihood[:,\n 0].sum()).dot((self.A * alpha[0, :].reshape(-1, 1)).T)\n A = xi / xi.sum(axis=1).reshape(-1, 1)\n B = gamma.dot(obs_indicator) / gamma.sum(axis=1).reshape(-1, 1)\n\n error = (np.abs(A - self.A)).max() + (np.abs(B - self.B)).max()\n it += 1\n self.A, self.B = A, B\n\n def viterbi(self, obs):\n v = np.multiply(self.pi, self.B[:, obs[0]])\n vpath = np.arange(self.s_num).reshape(-1, 1).tolist()\n for i in range(1, len(obs)):\n prev = np.array([np.argmax(v * self.A[:, n])\n for n in range(self.s_num)])\n v = v[prev] * self.A.flatten()[prev * self.s_num +\n np.arange(self.s_num)] * self.B[:, obs[i]]\n vpath = [vpath[prev[i]] + [i] for i in range(self.s_num)]\n return vpath[np.argmax(v)]\n\n\ndef seq_generator():\n o_num, s_num = 2, 2\n A = np.array([[0.4, 0.6], [0.9, 0.1]])\n B = np.array([[0.49, 0.51], [0.85, 0.15]])\n pi = np.array([0.5, 0.5])\n #obs = np.array([0,1,1,0,1,1,0,0,1,1,0,1,1,1,0,0,1,0,0,1,1,0,1,1,1,1,0,1,0,0,1,0,1,0,0,1,1,1,0])\n '''\n\thmm.pi = np.array([0.25, 0.25, 0.25, 0.25])\n\thmm.A = np.array([[0.05,0.7, 0.05, 0.2],[0.1,0.4,0.3,0.2],[0.1,0.6,0.05,0.25],[0.25,0.3,0.4,0.05]])\n\thmm.B = np.array([[0.3,0.4,0.2,0.1],[0.2,0.1,0.2,0.5],[0.4,0.2,0.1,0.3],[0.3,0.05,0.3,0.35]])\n\tobs = np.array([3,1,1,3,0,3,3,3,1,1,0,2,2])\n\t'''\n '''\n\tA = np.array([[.4,.3,.1,.2],[.6,.05,.1,.25],[.7,.05,.05,.2],[.3,.4,.25,.05]])\n\tB = np.array([[.2,.1,.2,.5],[.4,.2,.1,.3],[.3,.4,.2,.1],[.3,.05,.3,.35]])\n\tpi = np.array([0.25,0.25,0.25,0.25])\n\t'''\n q = np.random.choice(s_num, 1, p=pi)[0]\n v = []\n for i in range(100):\n v.append(np.random.choice(o_num, 1, p=B[q].flatten())[0])\n q = np.random.choice(s_num, 1, p=A[q].flatten())[0]\n # print(np.array(q))\n obs = np.array(v)\n return obs, A, B, pi\n\n\ndef main():\n hmm1 = HMM(2, 2)\n obs, hmm1.A, hmm1.B, hmm1.pi = seq_generator()\n print(hmm1.forward(obs))\n print(hmm1.predict(obs))\n\n hmm2 = HMM(2, 2)\n hmm2.baum_welch(obs)\n print(hmm2.pi)\n print(hmm2.A)\n print(hmm2.B)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"hmm.py","file_name":"hmm.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"230869479","text":"import json\nimport traceback\nfrom uuid import uuid4\n\nfrom config_vars import API_GATEWAY_POST_JOB_URI, PIPELINE, TEMPLATE_COLLECTION, DEFAULT_SECTION\nfrom connections.mongodb import MongoDbConn\nfrom utilities.http import post\nfrom xpms_objects.models.elements import *\nfrom copy import deepcopy\n\nTEMPLATE_SCHEMA = {\n \"$schema\": \"http://json-schema.org/schema#\",\n \"type\": \"object\",\n \"properties\": {\n \"template_name\": {\"type\": \"string\"},\n \"solution_id\": {\"type\": \"string\"},\n \"doc_id\": {\"type\": \"string\"},\n \"elements\": {\"type\": \"array\"},\n \"template_type\": {\"type\": \"string\"},\n \"document_variables\": {\"type\": \"object\"},\n \"domain_object_mapping\": {\"type\": \"object\"}\n },\n \"required\": [\n \"template_name\",\n \"solution_id\",\n \"doc_id\",\n \"elements\",\n \"template_type\",\n \"document_variables\",\n \"domain_object_mapping\"\n ]\n}\nTEMPLATE_SAVE_URL = \"template/save\"\nTEMPLATE_PUBLISH_URL = \"template/publish\"\nTEMPLATE_INGEST_URL = \"insight/getInsight\"\n\n\ndef ingest_template(solution_id, payload, file_path=None):\n try:\n data = dict(template_name=payload[\"template_name\"], pipeline_name=\"ingest_template\")\n if file_path is not None:\n data[\"file_path\"] = file_path\n return post_save_template(solution_id, data, endpoint=PIPELINE[\"TRIGGER_PIPELINE\"])\n except Exception:\n return dict(success=False, error=traceback.format_exc(), msg=\"failed to ingest template\", status=\"success\")\n\n\ndef get_template(solution_id, template_type=\"\", template_id=\"\", payload={}):\n try:\n unknown_types = [\"unknown_known\", \"unknown_unknown\"]\n query = dict(solution_id=solution_id, is_deleted=False)\n\n if template_id != \"\":\n query[\"template_id\"] = template_id\n t = MongoDbConn.find_one(TEMPLATE_COLLECTION, query, {\"_id\": 0})\n\n # Constructing Response\n templates = json.loads(t[\"template\"]) if t else {}\n templates[\"template_id\"] = templates[\"doc_id\"]\n templates[\"no_of_pages\"] = len(templates[\"pages\"].keys())\n templates[\"elements\"] = convert_elements_old(templates[\"elements\"])\n count = 1\n else:\n t = MongoDbConn.find(TEMPLATE_COLLECTION, query, {\"_id\": 0})\n templates = list()\n for a in t:\n a = json.loads(a[\"template\"])\n a[\"template_id\"] = a[\"doc_id\"]\n templates.append(a)\n\n if template_type != \"\":\n if template_type == \"allpublished\":\n templates = [a for a in templates if not a[\"is_draft\"] or a[\"template_type\"] in unknown_types]\n else:\n template_type = unknown_types if template_type == \"unknown\" else [template_type]\n templates = [a for a in templates if a[\"template_type\"] in template_type]\n\n count = len(templates)\n page_no = payload[\"page_no\"] if \"page_no\" in payload else None\n limit = payload[\"no_of_recs\"] if \"no_of_recs\" in payload else None\n if page_no and count > limit:\n skip = (int(page_no) - 1) * limit\n templates = templates[skip:skip + limit]\n\n return dict(success=True, msg=\"Template data\", data=templates, total_count=count, status=\"success\")\n except Exception:\n return dict(success=False, error=traceback.format_exc(), msg=\"Failed to get template\", status=\"failure\")\n\n\ndef update_template(solution_id, payload):\n try:\n # Finding template\n filter_query = dict(solution_id=solution_id, template_id=payload.pop(\"template_id\"), is_deleted=False)\n template_data = MongoDbConn.find_one(TEMPLATE_COLLECTION, filter_query)\n template = json.loads(template_data[\"template\"]) if template_data else {}\n\n # Updating template\n endpoint = TEMPLATE_PUBLISH_URL if \"is_draft\" in payload else TEMPLATE_SAVE_URL\n template.update(payload)\n return post_save_template(solution_id, dict(document=template), endpoint=endpoint)\n except Exception:\n return dict(success=False, msg=\"Failed to publish template\", error=traceback.format_exc(), status=\"failure\")\n\n\ndef save_template_element(solution_id, data):\n try:\n query = dict(solution_id=solution_id, template_id=data.pop(\"template_id\"), is_deleted=False)\n template = MongoDbConn.find_one(TEMPLATE_COLLECTION, query)\n template = json.loads(template[\"template\"]) if template else {}\n\n # new element object\n new = data\n new[\"id\"], is_update = (str(uuid4()), False) if \"id\" not in new else (new[\"id\"], True)\n new[\"section_id\"] = new[\"id\"] if \"section_id\" not in new else new[\"section_id\"]\n new[\"is_deleted\"] = False\n\n if new[\"type\"] == \"table\":\n template[\"domain_object_mapping\"] = update_table_mapping(new, template[\"domain_object_mapping\"])\n else:\n if \"domain_mapping\" in new and new[\"domain_mapping\"] != \"\":\n template[\"domain_object_mapping\"] = update_template_domain_mapping(new[\"domain_mapping\"],\n new[\"id\"],\n template[\"domain_object_mapping\"])\n template[\"document_variables\"].pop(new[\"id\"], None)\n\n if \"doc_var\" in new and new[\"doc_var\"] != {}:\n template[\"document_variables\"] = update_template_document_variables(new[\"doc_var\"],\n new[\"id\"],\n template[\"document_variables\"])\n template[\"domain_object_mapping\"].pop(new[\"id\"], None)\n\n elements_reformatted = update_template_elements(new, _obj=template[\"elements\"], is_update=is_update)\n template[\"elements\"] = [elements_reformatted]\n\n resp = post_save_template(solution_id, dict(document=template))\n resp.update(dict(section_id=new['section_id'], id=new['id']))\n return resp\n except Exception:\n return dict(success=False, msg=\"Failed to save element\", error=traceback.format_exc(), status=\"failure\")\n\n\ndef update_template_elements(ele, _obj, is_update=False):\n \"\"\"\n Used to update old to new elements format.\n As json transformations required at child level as root as json does not handle these.\n :param ele:\n :param _obj:\n :param is_update:\n :return:\n \"\"\"\n ele_old = deepcopy(ele)\n _obj = remove_element(_obj, ele[\"id\"]) if is_update else _obj\n\n ele_tree = ElementTree(json_obj=_obj[0])\n root = ele_tree.find_one(lambda x: x.id == ele[\"section_id\"]) if ele[\"section_id\"] not in [\"default\"] else ele_tree\n\n cords = [dict(x1=a[\"x1\"], x2=a[\"x2\"], y1=a[\"y1\"], y2=a[\"y2\"], page_num=a[\"page_number\"])\n for a in ele[\"coordinates\"]] if \"coordinates\" in ele else []\n el = None\n\n if ele[\"type\"] == \"section\":\n el = SectionElement(parent=root, id=ele[\"id\"], node_type=\"section\", parent_id=ele[\"section_id\"])\n\n elif ele[\"type\"] == \"omr\":\n el = OmrFieldElement(parent=root, id=ele[\"id\"], name=ele[\"name\"], regions=cords, node_type=\"omr\",\n key=FieldKeyElement(), value=FieldValueElement(id=str(uuid4()), regions=cords))\n if \"has_label\" in ele[\"parameters\"]:\n el.has_label = ele[\"parameters\"][\"has_label\"]\n el.key.regions = [dict(x1=a[\"x1\"], x2=a[\"x2\"], y1=a[\"y1\"], y2=a[\"y2\"], page_num=a[\"page_number\"])\n for a in ele[\"parameters\"][\"label_coordinates\"]] if el.has_label else []\n el.fields = list()\n group = ele[\"groups\"][0] if \"groups\" in ele and len(ele[\"groups\"]) > 0 else {}\n el.is_multiselect = group[\"is_multiOption\"]\n for o in group[\"options\"]:\n o_el = FieldElement(id=str(uuid4()), node_type=\"omr_field\")\n o_el.key.text = o[\"label\"]\n o_el.key.regions = [dict(x1=a[\"x1\"], x2=a[\"x2\"], y1=a[\"y1\"], y2=a[\"y2\"], page_num=a[\"page_number\"])\n for a in o[\"coordinates\"]]\n el.fields.append(o_el)\n\n elif ele[\"type\"] == \"field\":\n el = FieldElement(parent=root, id=ele[\"id\"], name=ele[\"name\"], regions=cords, node_type=\"field\")\n el.value.regions = cords\n el.is_variable_field = ele[\"is_variable_field\"] if \"is_variable_field\" in ele else False\n if \"has_label\" in ele[\"parameters\"]:\n el.has_label = ele[\"parameters\"][\"has_label\"]\n el.key.regions = [dict(x1=a[\"x1\"], x2=a[\"x2\"], y1=a[\"y1\"], y2=a[\"y2\"], page_num=a[\"page_number\"])\n for a in ele[\"parameters\"][\"label_coordinates\"]] if el.has_label else []\n\n elif ele['type'] == 'paragraph':\n el.is_variable_field = ele[\"is_variable_field\"] if \"is_variable_field\" in ele else False\n el = ParagraphElement(parent=root, id=ele[\"id\"], name=ele[\"name\"], region=cords, node_type=\"paragraph\",\n top_keys=ele[\"top_keys\"] if \"top_keys\" in ele else [],\n bottom_keys=ele[\"bottom_keys\"] if \"bottom_keys\" in ele else [])\n\n elif ele['type'] == 'table':\n el = TableElement(parent=root, id=ele[\"id\"], name=ele[\"name\"], node_type=\"table\",\n top_keys=ele[\"top_keys\"] if \"top_keys\" in ele else [],\n bottom_keys=ele[\"bottom_keys\"] if \"bottom_keys\" in ele else [],\n is_transpose=ele[\"is_transpose\"] if \"is_transpose\" in ele else False)\n headings = ele[\"headings\"] if \"headings\" in ele else []\n el.headers = [TableHeaderElement(column_index=[h[\"column_no\"]], row_index=[0], text=h[\"column\"])\n for h in headings]\n if el:\n el.old_element = ele_old\n\n return json.loads(ele_tree.as_json(True))\n\n\ndef update_template_domain_mapping(new_map, element_id, domain_mapping):\n new_map_obj = dict(domain_object=new_map.rsplit(\".\", 1)[0], attribute=new_map.rsplit(\".\", 1)[1])\n domain_mapping[element_id] = [new_map_obj]\n return domain_mapping\n\n\ndef update_template_document_variables(new_var, element_id, document_variable):\n new_var_obj = dict(name=new_var[\"name\"], data_type=new_var[\"type\"], enable_rules=False, rules=new_var[\"rule_id\"])\n document_variable[element_id] = [new_var_obj]\n return document_variable\n\n\ndef update_table_mapping(ele, temp_mapping):\n table_id = ele[\"id\"]\n if \"parameters\" in ele and \"headings\" in ele[\"parameters\"]:\n domain_mapping = []\n for heading in ele[\"parameters\"][\"headings\"]:\n if \"domain_mapping\" in heading:\n map_data = heading[\"domain_mapping\"]\n new_map_obj = dict(domain_object=map_data.rsplit(\".\", 1)[0],\n attribute=map_data.rsplit(\".\", 1)[1],\n column_no=[heading[\"column_no\"]])\n domain_mapping.append(new_map_obj)\n temp_mapping[table_id] = domain_mapping\n return temp_mapping\n\n\ndef post_save_template(solution_id, data, endpoint=TEMPLATE_SAVE_URL):\n request = dict(data=data, solution_id=solution_id)\n response = post(API_GATEWAY_POST_JOB_URI + endpoint, request)\n if response[\"status\"] == \"success\":\n return dict(success=True, msg=\"Template Updated\", status=\"success\")\n else:\n return dict(success=False, msg=response[\"msg\"], status=\"failure\")\n\n\ndef delete_template_element(solution_id, data):\n try:\n query = dict(solution_id=solution_id, template_id=data.pop(\"template_id\"), is_deleted=False)\n template = MongoDbConn.find_one(TEMPLATE_COLLECTION, query)\n template = json.loads(template[\"template\"]) if template else {}\n\n id = data[\"id\"]\n template[\"elements\"] = remove_element(template[\"elements\"], id)\n template[\"domain_object_mapping\"].pop(id, None)\n template[\"document_variables\"].pop(id, None)\n\n return post_save_template(solution_id, dict(document=template))\n except Exception:\n return dict(success=False, msg=\"failed to delete template\", error=traceback.format_exc(), status=\"failure\")\n\n\ndef remove_element(elements, id):\n for e in elements:\n if e[\"id\"] == id:\n elements.remove(e)\n break\n elif \"children\" in e:\n remove_element(e[\"children\"], id)\n else:\n continue\n return elements\n\n\ndef save_unknown_template(solution_id, payload):\n if \"template_id\" in payload:\n query = dict(solution_id=solution_id, template_id=payload[\"template_id\"], is_deleted=False)\n template = MongoDbConn.find_one(TEMPLATE_COLLECTION, query)\n template = json.loads(template[\"template\"]) if template else {}\n template[\"elements\"] = payload[\"elements\"]\n return post_save_template(solution_id, dict(document=template))\n else:\n payload[\"request_type\"] = \"ingest_template\"\n return post_save_template(solution_id, data=payload, endpoint=TEMPLATE_INGEST_URL)\n\n\ndef add_temp_id(elements, temp_id=None):\n for e in elements:\n e[\"temp_id\"] = str(temp_id) + str(e[\"id\"]) if temp_id else str(e[\"id\"])\n if \"elements\" in e:\n add_temp_id(e[\"elements\"], e[\"temp_id\"])\n else:\n continue\n return elements\n\n\ndef convert_elements_old(elements, temp_id=None):\n for element in elements:\n element[\"type\"] = element.pop(\"node_type\")\n del_keys = [key for key in element.keys() if key not in [\"old_element\", \"elements\", \"id\", \"children\"]]\n\n if element[\"type\"] == \"default_section\":\n assert pop_keys(element, del_keys)\n element.update(DEFAULT_SECTION)\n element[\"temp_id\"] = element[\"id\"]\n else:\n assert pop_keys(element, del_keys)\n element.update(element[\"old_element\"])\n element[\"temp_id\"] = temp_id + \"_\" + element[\"id\"]\n element.pop(\"old_element\")\n\n if \"children\" in element:\n element[\"elements\"] = element.pop(\"children\")\n convert_elements_old(element[\"elements\"], element[\"temp_id\"])\n return elements\n\n\ndef pop_keys(d: dict, k: list):\n for i in k:\n d.pop(i, None)\n return True\n","sub_path":"services/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":14318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"156181050","text":"from flask import Flask, jsonify, request\nimport translator, postman\n\n\napp = Flask(__name__)\n\n\n@app.route('/interpret_webhook', methods=['POST'])\ndef form():\n request_payload = request.get_json()\n translated_payload = translator.translate_payload(request_payload)\n posted = postman.post_payload(request.args['hook_url'], translated_payload)\n return jsonify(posted)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"558373004","text":"import socket\n\nimport hashlib\nimport hmac\nimport binascii\n\nimport time\n\nfrom urllib.parse import quote\n\nimport json\n\nimport oauth2 as oauth\n\n\ndef get_batch(filtering):\n host = \"api.twitter.com\"\n port = 80\n\n get_time = lambda: str(int(time.clock()))\n get_nonce = lambda x: \"a\" + hashlib.md5(x.encode()).hexdigest()[2:] + \"a\"\n\n time_stamp = get_time()\n\n url = \"/statuses/sample.json\"\n urlq = quote(url, safe = \"\")\n \n authd = {\"oauth_consumer_key\": \"10jGXLl57d1pfR3GUvv6ETIHc\", \"oauth_nonce\": get_nonce(time_stamp), \\\n \"oauth_signature_method\": \"HMAC-SHA1\", \"oauth_timestamp\": time_stamp, \\\n \"oauth_token\": \"132268211-4PSyzYksnZnqSIGZvvWcqm2v1lve8MXUg02Vm4R5\", \"oauth_version\": \"1.0\",\n \"url\": urlq}\n \n GET_base = \"\"\"GET&https%3A%2F%2Fapi.twitter.com%2F1.1{url}&oauth_consumer_key\n%3D{oauth_consumer_key}%26oauth_nonce%3D{oauth_nonce}%26\noauth_signature_method%3D{oauth_signature_method}%26oauth_timestamp%3D{oauth_timestamp}%26oauth_token%3D\n{oauth_token}%26oauth_version%3D{oauth_version}\"\"\".replace(\"\\n\", \"\")\n\n GET_actual_old = \"\"\"GET&https%3A%2F%2Fapi.twitter.com%2F1.1{url}&oauth_consumer_key\n%3D{oauth_consumer_key}%26oauth_nonce%3D{oauth_nonce}%26\noauth_signature_method%3D{oauth_signature_method}%26oauth_signature%3D{oauth_signature}%26oauth_timestamp%3D{oauth_timestamp}%26oauth_token%3D\n{oauth_token}%26oauth_version%3D{oauth_version}\"\"\".replace(\"\\n\", \"\")\n\n GET_actual = '''GET /1.1{url} HTTPS/1.1\nHost: api.twitter.com\nAuthorization: OAuth oauth_consumer_key=\"{oauth_consumer_key}\", oauth_nonce=\"{oauth_nonce}\", oauth_signature=\"{oauth_signature}\", oauth_signature_method=\"{oauth_signature_method}\", oauth_timestamp=\"{oauth_timestamp}\", oauth_token=\"{oauth_token}\", oauth_version=\"{oauth_version}\"'''\n\n \n for k in authd.keys():\n if k != \"oauth_signature\":\n GET_base = GET_base.replace(\"{\"+k+\"}\", authd[k])\n\n CONSUMER_SECRET = \"eZi8SRZl6lOH9OAB0ZmTYgle1rbl1MHWEBR2bOIzHRUA9VCPIO\"\n TOKEN_SECRET = \"FaSl2jb50y7gbOTGgwCXf1fxE982Gbwnlh6I1vdHAE79z\"\n key = (CONSUMER_SECRET + \"&\" + TOKEN_SECRET).encode()\n raw = GET_base.encode()\n hashed = hmac.new(key, raw, hashlib.sha1)\n unquoted_signature = binascii.b2a_base64(hashed.digest()).decode().rstrip(\"\\n\")\n signature = quote(unquoted_signature, safe = \"\")\n #signature = unquoted_signature\n authd[\"oauth_signature\"] = signature\n\n authd[\"url\"] = url\n\n for k in authd.keys():\n GET_actual = GET_actual.replace(\"{\"+k+\"}\", authd[k])\n\n #GET_actual = quote(GET_actual, safe=\"\")\n print(GET_actual)\n\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((host, port))\n\n sock.send(GET_actual.encode())\n data = sock.recv(1024)\n print(data)\n\ndef get_batch_easy(filtering):\n CONSUMER_KEY = \"10jGXLl57d1pfR3GUvv6ETIHc\"\n CONSUMER_SECRET = \"eZi8SRZl6lOH9OAB0ZmTYgle1rbl1MHWEBR2bOIzHRUA9VCPIO\"\n ACCESS_KEY = \"132268211-4PSyzYksnZnqSIGZvvWcqm2v1lve8MXUg02Vm4R5\"\n ACCESS_SECRET = \"FaSl2jb50y7gbOTGgwCXf1fxE982Gbwnlh6I1vdHAE79z\"\n\n consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)\n access_token = oauth.Token(key=ACCESS_KEY, secret=ACCESS_SECRET)\n client = oauth.Client(consumer, access_token)\n\n timeline_endpoint = \"http://api.twitter.com/1.1/statuses/sample.json\"\n response, data = client.request(timeline_endpoint)\n\n tweets = json.loads(data.decode())\n for tweet in tweets.keys():\n print(tweet, tweets[tweet])\n\n \nget_batch(0)\n","sub_path":"twits.py","file_name":"twits.py","file_ext":"py","file_size_in_byte":3500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"61237584","text":"# -*- coding: utf-8 -*-\nimport httplib as http\nimport sys\nimport inspect\nimport pkgutil\n\nimport mock\n\nfrom nose.tools import * # flake8: noqa\n\nfrom tests.base import ApiTestCase\nfrom tests import factories\n\nfrom api.base.settings.defaults import API_BASE\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated\nfrom api.base.permissions import TokenHasScope\n\nfrom framework.auth.oauth_scopes import CoreScopes\n\nclass TestApiBaseViews(ApiTestCase):\n\n def test_root_returns_200(self):\n res = self.app.get('/{}'.format(API_BASE))\n assert_equal(res.status_code, 200)\n\n def test_view_classes_have_minimal_set_of_permissions_classes(self):\n base_permissions = [ \n TokenHasScope,\n (IsAuthenticated, IsAuthenticatedOrReadOnly)\n ]\n view_modules = [name for _, name, _ in pkgutil.iter_modules(['api'])]\n for module in view_modules:\n for name, view in inspect.getmembers(sys.modules['api.{}.views'.format(module)], inspect.isclass):\n if hasattr(view, 'permission_classes'):\n for cls in base_permissions:\n if isinstance(cls, tuple):\n has_cls = any([c in view.permission_classes for c in cls])\n assert_true(has_cls, \"{0} lacks the appropriate permission classes\".format(name))\n else:\n assert_in(cls, view.permission_classes, \"{0} lacks the appropriate permission classes\".format(name))\n for key in ['read', 'write']: \n scopes = getattr(view, 'required_{}_scopes'.format(key), None)\n assert_true(bool(scopes))\n for scope in scopes:\n assert_is_not_none(scope) \n\n @mock.patch('framework.auth.core.User.is_confirmed', mock.PropertyMock(return_value=False))\n def test_unconfirmed_user_gets_error(self):\n\n user = factories.AuthUserFactory()\n\n res = self.app.get('/{}nodes/'.format(API_BASE), auth=user.auth, expect_errors=True)\n assert_equal(res.status_code, http.BAD_REQUEST)\n \n @mock.patch('framework.auth.core.User.is_disabled', mock.PropertyMock(return_value=True))\n def test_disabled_user_gets_error(self):\n\n user = factories.AuthUserFactory()\n\n res = self.app.get('/{}nodes/'.format(API_BASE), auth=user.auth, expect_errors=True)\n assert_equal(res.status_code, http.BAD_REQUEST)\n \n","sub_path":"tests/api_tests/base/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"76848243","text":"import argparse\nimport logging\nimport pickle\nimport torch\nimport os\nimport aer\nfrom make_aer_pred import make_pred\nfrom tqdm import tqdm\nimport torch.nn as nn\nimport matplotlib\nmatplotlib.use('Agg')\nfrom torch import optim\nfrom collections import defaultdict, Counter\nfrom random import shuffle\nfrom data import Corpus\nfrom matplotlib import pyplot as plt\nfrom sklearn.decomposition import PCA\nfrom Encoder import Encoder\nfrom Decoder import Decoder\n\n\ndef get_aer(corpus, decoder, encoder):\n \"\"\"Calculate the Alignment Error Rate.\n\n Args:\n w2i_e: dict mapping English words to indices\n w2i_f: dict mapping French words to indices\n decoder: Embed Align decoder\n encoder: Embed Align encoder\n \"\"\"\n make_pred('./../data/wa/test.en', './../data/wa/test.fr',\n './alignment.pred', corpus.dictionary_e.word2index,\n corpus.dictionary_f.word2index, decoder, encoder)\n AER = aer.test('./../data/wa/test.naacl', './alignment.pred') \n logging.info('alignment error rate: {}'.format(AER))\n\n\ndef validate(corpus, pairs, encoder, decoder, i, enable_cuda):\n \"\"\"Compute AER and LST scores.\n\n Args:\n corpus: Corpus object containing w2i and i2w dictionaires\n pairs: list of tuples with testing data\n encoder: Embed Align encoder model\n decoder: Embed Align decoder model\n i: what epoch you're in\n enable_cuda: whether GPU is available\n \"\"\"\n w2i = corpus.dictionary_e.word2index\n i2w = corpus.dictionary_e.index2word\n outputs = []\n for orig_centre, (pre, post), n, term, candidates, candidates_rest in pairs:\n # Prepare centre vector\n if orig_centre not in w2i: \n centre = term.split('.')[0]\n else:\n centre = orig_centre\n original_tensor = torch.autograd.Variable(torch.LongTensor([\n [w2i[w] for w in pre + [centre] + post if w in w2i]])\n )\n if enable_cuda: original_tensor = original_tensor.cuda()\n\n # Rank candidates one by one\n ranking = Counter()\n for candidate in candidates:\n if not centre in w2i:\n ranking[candidate] = 0\n else:\n candidate_tensor = torch.autograd.Variable(torch.LongTensor([\n [w2i[w] for w in pre + [candidate] + post if w in w2i]])\n )\n if enable_cuda: candidate_tensor = candidate_tensor.cuda()\n mu_o, sigma_o = encoder.forward(original_tensor)\n mu_c, sigma_c = encoder.forward(candidate_tensor)\n KL = decoder.KL(mu_c, sigma_c, mu_o, sigma_o)\n ranking[candidate] = - 1 * KL.data[0]\n\n # Use format specified in LST README\n output = \"RANKED\\t{} {}\".format(term, n)\n for j, (candidate, score) in enumerate(ranking.most_common()):\n output += \"\\t{} {}\".format(candidate, score)\n for candidate in candidates_rest:\n output += \"\\t{} {}\".format(candidate, 0)\n outputs.append(output)\n\n with open(\"epoch_{}.out\".format(i + 1), 'w') as f:\n f.write(\"\\n\".join(outputs))\n os.system(\"python ../data/lst/lst_gap.py ../data/lst/lst_valid.gold epoch_{}.out out no-mwe\".format(i + 1))\n\n\ndef prepare_test(w2i, window, sentences_path=\"../data/lst/lst_test.preprocessed\",\n cand_path=\"../data/lst/lst.gold.candidates\"):\n \"\"\"Prepare the test set for evaluation for the LST task.\n\n Args:\n w2i: dictionary mapping words to indices\n window: integer marking the context window\n sentences_path: LST file with word, sentence pairs\n cand_path: file containing LST substitution candidates\n\n Returns:\n a list of tuples\n \"\"\"\n test_pairs = []\n candidates = dict()\n missing_candidates = dict()\n with open(cand_path, 'r') as f:\n for line in f:\n term, term_candidates = tuple(line.split(\"::\"))\n term_candidates = term_candidates.strip().split(\";\")\n candidates[term] = [ c for c in term_candidates if c in w2i]\n missing_candidates[term] = [ c for c in term_candidates if c not in w2i]\n\n with open(sentences_path, 'r') as f:\n for line in f:\n # Read in data line by line\n term, number, pos, sentence = tuple(line.split(\"\\t\"))\n pos = int(pos)\n sentence = sentence.split()\n\n # Extract the context of the term and pad with or \n pre = sentence[max(pos - window, 0):pos]\n post = sentence[pos+1:min(pos + window + 1, len(sentence))]\n context = (pre, post)\n centre = sentence[pos]\n test_pairs.append((centre, context, int(number), term,\n candidates[term], missing_candidates[term]))\n return test_pairs\n\n\ndef train(corpus, encoder, decoder, epochs, lr, batch_size, enable_cuda,\n test_pairs, do_validation=True):\n \"\"\"Train Embed-Align multiple iterations.\n\n Args:\n corpus: Corpus instance containing training data and dictionaries\n encoder: inference part of the Embed Align model\n decoder: generative part of the Embed Align model\n epochs: number of iterations\n lr: float, the learning rate\n batch_size: integer indicating the batch size used\n enable_cuda: boolean indicating whether GPU is present\n test_pairs: tuples of test pairs for the LST task\n do_validation: flag indicating whether to perform validation\n\n Returns:\n list of losses, one number per iteration\n \"\"\"\n\n losses = []\n optimizer = optim.Adam(\n list(encoder.parameters()) + list(decoder.parameters()), lr=lr\n )\n n = len(corpus.batches)\n get_aer(corpus, decoder, encoder)\n for i in range(epochs):\n if do_validation:\n validate(corpus, test_pairs, encoder, decoder, i, enable_cuda)\n all_loss = 0\n all_ll = 0\n all_KL = 0\n logging.info(\"Epoch {}\".format(i+1))\n for (english, french) in corpus.batches:\n optimizer.zero_grad()\n mu, sigma = encoder.forward(english)\n ll, KL = decoder.forward(mu, sigma, english, french)\n loss = -1 * (ll - KL)\n all_ll += ll.data[0]\n all_KL += KL.data[0]\n loss.backward()\n optimizer.step()\n all_loss += loss.data[0] \n get_aer(corpus, decoder, encoder)\n torch.save(encoder, \"encoder_epoch_{}.pt\".format(i))\n torch.save(decoder, \"decoder_epoch_{}.pt\".format(i))\n pickle.dump(list(corpus.dictionary_e.word2index.items()),\n open(\"w2i_e.pickle\", 'wb'))\n pickle.dump(list(corpus.dictionary_f.word2index.items()),\n open(\"w2i_f.pickle\", 'wb'))\n\n losses.append(all_loss / n / batch_size)\n logging.info(\"Avg. loss per sample: {}\".format(all_loss/n/batch_size))\n logging.info(\"KL {}, LL {}\".format(all_KL/n/batch_size, all_ll/n/batch_size))\n return losses\n\n\nif __name__ == \"__main__\":\n p = argparse.ArgumentParser(description='Embed-Align.')\n p.add_argument('--english', type=str, default='../data/hansards/training.en',\n help='path to Fnglish data.')\n p.add_argument('--french', type=str, default='../data/hansards/training.fr',\n help='path to French data.')\n p.add_argument('--lr', type=float, default=0.01, help='learning rate')\n p.add_argument('--batch_size', type=int, default=10, help='batch size')\n p.add_argument('--enable_cuda', action='store_true', help='use CUDA')\n p.add_argument('--save', type=str, help='path for saving model')\n p.add_argument('--epochs', type=int, default=10, help='#epochs')\n p.add_argument('--window', default=5, type=int)\n p.add_argument('--dim', default=50, type=int)\n p.add_argument('--nr_sents', default=-1, type=int)\n p.add_argument('--unique_words', default=10000, type=int)\n p.add_argument('--candidates', default='../data/lst/lst.gold.candidates')\n p.add_argument('--valid', default='../data/lst/lst_valid.preprocessed')\n p.add_argument('--gold', default='../data/lst/lst_valid.gold')\n \n args = p.parse_args()\n logging.basicConfig(level=logging.INFO)\n\n # Check whether GPU is present\n if args.enable_cuda and torch.cuda.is_available():\n enable_cuda = True\n #torch.cuda.set_device(0)\n logging.info(\"CUDA is enabled\")\n else:\n enable_cuda = False\n logging.info(\"CUDA is disabled\")\n\n # Prepare corpus + dictionaries, create training batches\n corpus = Corpus(args.english, args.french, args.batch_size, args.nr_sents,\n args.unique_words, args.enable_cuda)\n test_pairs = prepare_test(corpus.dictionary_e.word2index, args.window,\n args.valid, args.candidates)\n\n logging.info(\"Loaded data.\")\n\n # Initialize model and cuda if necessary\n encoder = Encoder(corpus.vocab_size_e, args.dim, enable_cuda)\n decoder = Decoder(corpus.vocab_size_e, corpus.vocab_size_f, args.dim,\n args.batch_size, enable_cuda)\n if enable_cuda:\n encoder.cuda()\n decoder.cuda()\n\n # Train\n logging.info(\"Training will start shortly.\")\n losses = train(corpus, encoder, decoder, args.epochs, args.lr,\n args.batch_size, enable_cuda,test_pairs, True)\n","sub_path":"Lab2/EmbedAlign/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":9382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"131025283","text":"#Generator function which each reads each file in the director and perform following functions:\r\n# 1.Reads file and skips first header line\r\n# 2.Split the comma separated file using strip\r\n# 3.Yield flight number from 5th column\r\ndef gener(file):\r\n with open(file, 'r') as f:\r\n first_line=f.readline() #This will read first line and will skip it when we read from file below\r\n for line in f:\r\n flight_no=line.strip().split(',')[4]\r\n yield flight_no\r\n \r\n \r\nimport os\r\nimport glob\r\n\r\ndt={} #dictionary for storing flight# and total no of flights by airline and then sorting by no of flights \r\n\r\n\r\n#Read all csv files from data sub directory and call generator and add flight# into dictionary\r\n#Data subdirectory is in the directory where we ran this python program.Using glob to list all csv files in data subdirectory\r\nfor file in glob.glob(\"data/*.csv\"):\r\n m=gener(file) \r\n for fl in m:\r\n dt[fl]=dt.get(fl,0)+1\r\n\r\n#Sort dictionary on descending order\r\nst=sorted(dt.items(),key=lambda x:x[1],reverse=True)\r\n\r\noutput_file=open('flights_by_airline.csv','w')\r\n\r\ntot_flights=0\r\noutput_file.write(\"Airline,# Flights\\n\") #Writing header to output file\r\n\r\n#Loop through dictionary and write into output files\r\nfor fl,no in st:\r\n output_file.write(f\"{fl},{no}\\n\")\r\n tot_flights=int(no)+tot_flights\r\n\r\noutput_file.write(f\"Total ,{tot_flights}\")\r\n\r\noutput_file.close()\r\n","sub_path":"SOlutions/hw4-1(1).py","file_name":"hw4-1(1).py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"313787456","text":"from datetime import date, datetime, timedelta\nfrom core.models import DrugSchedule\n\n\ndef test_drug_schedule_get_time_thrice(fixture_user):\n schedule = DrugSchedule(\n drug_name=\"Tabletki\",\n user=fixture_user,\n type_schedule=DrugSchedule.TYPE_THRICE,\n notify_time_before=30,\n date_from=date(2018, 8, 28),\n date_to=date(2018, 11, 1),\n )\n\n today = date.today()\n equal_time_ones = [\n datetime(today.year, today.month, today.day, 7, 30),\n datetime(today.year, today.month, today.day, 13, 30),\n datetime(today.year, today.month, today.day, 19, 30),\n ]\n assert schedule.get_times == equal_time_ones","sub_path":"meds/tests/core/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"64002646","text":"from flask import Flask, request, jsonify, render_template, make_response\nfrom flask_cors import CORS,cross_origin\nimport json\nimport requests\nfrom pathlib import Path\nfrom datetime import datetime\nfrom hashlib import sha256\napplication = Flask(__name__)\ncors = CORS(application, supports_credentials=True, resources={r\"/*\": {\"origins\": \"*\"}})\n\n@application.route(\"/\")\ndef home():\n\tdata = json.load(fp=open('../../cold_start_from_facebook_score/pre_calculated_jsons/default_facebook_datum.json'))\n\tdata = [(url, datum) for url, datum in data.items()]\n\tr = render_template('home.html', data=data)\n\treturn r\n\n@application.route(\"/log\", methods=['POST'])\ndef log():\n\t\tpayload = request.json\n\t\tprint(payload)\n\t\tr = requests.post('http://localhost:8000/log', json=payload)\n\t\tprint(r.text)\n\t\treturn 'ok'\n\nif __name__ == \"__main__\":\n\t\tapplication.run(host='0.0.0.0')\n","sub_path":"contents_distribution/myproject/myproject.py","file_name":"myproject.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"422221505","text":"from django.conf.urls import patterns, url\nfrom communication import views\n\n__author__ = 'asifalidauva'\n\nurlpatterns = patterns('',\n url(r'^$', views.index, name='correspondence_index'),\n url(r'^add$', views.correspondence_add, name='correspondence_add'),\n url(r'^edit/(?P\\w+)/$', views.correspondence_edit,\n name='correspondence_edit'),\n url(r'^delete/(?P\\w+)/$', views.correspondence_delete,\n name='correspondence_delete'),\n url(r'^message/$', views.message_list, name='message_index'),\n url(r'^message/add/(?P[A-Z]{1})/$', views.message_add, name='message_add'),\n url(r'^message/edit/(?P[0-9]+)/$', views.message_change, name='message_edit'),\n url(r'^message/delete/(?P[0-9]+)/$', views.message_delete, name='message_delete'),\n url(r'^message/clearall$', views.mark_all_dismissed, name='message_clearall'),\n url(r'^message_change_status/(?P[0-9]+)/(?P[A-Z]+)/$',\n views.message_change_status, name='message_change_status'))\n","sub_path":"communication/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"447929912","text":"from __future__ import division, print_function, unicode_literals\n\nimport subprocess, os, pickle, time, argparse\nimport WriteFeaturesKernFDK, WriteFeaturesMarkFDK\nimport hindkit as kit\n\nclass Builder(object):\n\n def __init__(\n self,\n family,\n fontrevision = '1.000',\n devanagari_offset_matrix = ((0, 0), (0, 0)),\n ):\n\n self.family = family\n self.fontrevision = fontrevision\n self.devanagari_offset_matrix = devanagari_offset_matrix\n\n for module in [\n 'kerning',\n 'mark_positioning',\n 'mark_to_mark_positioning',\n 'devanagari_matra_i_variants',\n ]:\n if self.family.__dict__['has_' + module]:\n self.__dict__['enable_' + module] = True\n else:\n self.__dict__['enable_' + module] = False\n\n self.prepare_styles = False\n self.prepare_features = False\n self.compile = False\n\n self.makeinstances = False\n self.checkoutlines = False\n self.autohint = False\n\n self.do_style_linking = False\n self.use_os_2_version_4 = False\n self.prefer_typo_metrics = False\n self.is_width_weight_slope_only = False\n\n self.keep_build_directory = False\n\n self.parser = argparse.ArgumentParser()\n options = self.parser.add_argument_group(\n title = 'build options',\n description = 'execute `python build.py` to run stages as specified in build.py, or append arguments to override.'\n )\n options.add_argument(\n '-s', '--stages', action = 'store',\n help = '\"1\" for \"prepare_styles\", \"2\" for \"prepare_features\", and \"3\" for \"compile\".'\n )\n options.add_argument(\n '-o', '--options', action = 'store',\n help = '\"0\" for none, \"1\" for \"makeinstances\", \"2\" for \"checkoutlines\", and \"3\" for \"autohint\".'\n )\n\n def _parse_args(self):\n args = self.parser.parse_args()\n if args.stages:\n stages = str(args.stages)\n self.prepare_styles = True if '1' in stages else False\n self.prepare_features = True if '2' in stages else False\n self.compile = True if '3' in stages else False\n if args.options:\n options = str(args.options)\n self.makeinstances = True if '1' in options else False\n self.checkoutlines = True if '2' in options else False\n self.autohint = True if '3' in options else False\n\n def _check_master_files(self):\n is_missing = False\n message_lines = ['[WARNING] UFO master files missing:']\n for master in self.family.masters:\n if not os.path.exists(master.path):\n is_missing = True\n message_lines.append('\\t' + master.path)\n if is_missing:\n message_lines.extend(['', '[Note] Exit.', ''])\n raise SystemExit('\\n'.join(message_lines))\n\n def set_options(self, options = []):\n\n for supported_option in [\n\n 'prepare_styles',\n 'prepare_features',\n 'compile',\n\n 'makeinstances',\n 'checkoutlines',\n 'autohint',\n\n 'do_style_linking',\n 'use_os_2_version_4',\n 'prefer_typo_metrics',\n 'is_width_weight_slope_only',\n\n 'keep_build_directory',\n\n ]:\n if supported_option in options:\n self.__dict__[supported_option] = True\n\n def generate_designspace(self):\n\n process = subprocess.Popen(\n ['python', 'AFDKOPython/generate_designspace.py'],\n stdin = subprocess.PIPE,\n cwd = kit.__path__[0],\n )\n process.communicate(pickle.dumps(self.family.dump()))\n\n def generate_fmndb(self):\n\n f_name = self.family.output_name\n lines = []\n \n for style in self.family.styles:\n\n lines.append('')\n lines.append('[{}]'.format(style.output_full_name_postscript))\n lines.append(' f = {}'.format(f_name))\n lines.append(' s = {}'.format(style.name))\n\n l_name = style.output_full_name\n comment_lines = []\n\n if self.do_style_linking:\n if style.name == 'Regular':\n l_name = l_name.replace(' Regular', '')\n else:\n if style.is_bold:\n comment_lines.append(' # IsBoldStyle')\n l_name = l_name.replace(' Bold', '')\n if style.is_italic:\n comment_lines.append(' # IsItalicStyle')\n l_name = l_name.replace(' Italic', '')\n\n if l_name != f_name:\n lines.append(' l = {}'.format(l_name))\n\n lines.extend(comment_lines)\n\n with open(kit.paths.FMNDN, 'w') as f:\n f.write(kit.templates.FMNDB_HEAD)\n f.write('\\n'.join(lines))\n f.write('\\n')\n\n def reset_build_directory(self):\n print('[Note] Resetting the build directory...\\n')\n subprocess.call(['rm', '-fr', kit.paths.BUILD])\n subprocess.call(['mkdir', kit.paths.BUILD])\n\n def build(self, additional_arguments = []):\n\n self._parse_args()\n\n print()\n print('[Note] {} Building...\\n'.format(time.strftime('%H:%M:%S')))\n\n if self.makeinstances:\n self.enabled_styles = self.family.styles\n else:\n if len(self.family.masters) == 1 and len(self.family.styles) == 1:\n self.enabled_styles = self.family.styles\n else:\n self.enabled_styles = [self.family.styles[0], self.family.styles[-1]]\n\n if self.family.script in ['Devanagari', 'Gujarati']:\n from hindkit.scripts import devanagari\n devanagari.SCRIPT_PREFIX = kit.linguistics.INDIC_SCRIPTS[self.family.script.lower()]['abbreviation']\n\n if self.prepare_styles:\n\n self._check_master_files()\n\n if self.enable_mark_positioning:\n\n print('[Note] Generating the glyph class for combining marks...\\n')\n\n glyph_classes = []\n\n glyph_classes.extend([('generated_MARKS', glyph_filter_marks)])\n\n if self.enable_devanagari_matra_i_variants:\n print('[Note] Generating glyph classes for mI and mII matching...\\n')\n glyph_classes.extend([\n ('generated_MATRA_I_ALTS', devanagari.glyph_filter_matra_i_alts),\n ('generated_BASES_FOR_MATRA_I', devanagari.glyph_filter_bases_for_matra_i),\n ('generated_BASES_FOR_WIDE_MATRA_II', devanagari.glyph_filter_bases_for_wide_matra_ii),\n ])\n\n generate_glyph_classes(\n self.family,\n self.family.masters[0].open_font(),\n glyph_classes,\n output_path = 'features/GENERATED_classes.fea'\n )\n\n print('[Note] Resetting instance directories...\\n')\n subprocess.call(['rm', '-fr', kit.paths.INSTANCES])\n subprocess.call(['mkdir', kit.paths.INSTANCES])\n for style in self.enabled_styles:\n subprocess.call(['mkdir', style.directory])\n\n if self.makeinstances:\n\n print('[Note] Start interpolating masters...\\n')\n\n # Prepare makeInstancesUFO arguments\n\n arguments = ['-d', 'font.designspace']\n\n if not self.checkoutlines:\n arguments.append('-c')\n if not self.autohint:\n arguments.append('-a')\n\n # Run makeInstancesUFO\n\n subprocess.call(['makeInstancesUFO'] + arguments)\n\n # Remove the log file\n\n subprocess.call(['rm', '-f', 'mutatorMath.log'])\n\n print()\n print('[Note] Done interpolating masters.\\n')\n\n else:\n\n print('[Note] Copying masters to be instances.\\n')\n\n for index, (master, style) in enumerate(zip(self.family.masters, self.enabled_styles)):\n\n subprocess.call(['cp', '-fr', master.path, style.path])\n\n font = style.open_font()\n font.info.postscriptFontName = style.output_full_name_postscript\n\n if index != 0:\n font.groups.update(self.family.masters[0].open_font().groups)\n font.save()\n\n if self.checkoutlines:\n subprocess.call(['checkOutlinesUFO', '-e', '-all', style.path])\n\n if self.autohint:\n subprocess.call(['autohint', '-q','-nb', style.path])\n\n if self.prepare_features and (self.enable_kerning or self.enable_mark_positioning):\n\n self._check_master_files()\n\n for style in self.enabled_styles:\n\n print('[Note] Generating features for \"{}\":\\n'.format(style.name))\n\n if self.enable_kerning:\n WriteFeaturesKernFDK.KernDataClass(\n font = style.open_font(),\n folderPath = style.directory,\n minKern = 3,\n writeTrimmed = False,\n writeSubtables = True,\n fileName = 'kern.fea',\n )\n\n if self.enable_mark_positioning:\n\n WriteFeaturesMarkFDK.kCombMarksClassName = 'generated_MARKS'\n\n WriteFeaturesMarkFDK.MarkDataClass(\n font = style.open_font(),\n folderPath = style.directory,\n trimCasingTags = False,\n genMkmkFeature = self.enable_mark_to_mark_positioning,\n writeClassesFile = True,\n indianScriptsFormat = (\n True if self.family.script.lower() in kit.linguistics.INDIC_SCRIPTS\n else False\n ),\n )\n\n if self.enable_devanagari_matra_i_variants:\n\n print()\n print('\\t[Note] mI matching...')\n\n light, bold = self.devanagari_offset_matrix\n light_min, light_max = light\n bold_min, bold_max = bold\n\n ratio = style.interpolation_value / self.family.masters[-1].interpolation_value\n\n offset_tuple = (\n light_min + (bold_min - light_min) * ratio,\n light_max + (bold_max - light_max) * ratio,\n )\n\n devanagari.match_matra_i_alts(\n style,\n offset_range = offset_tuple\n )\n\n print()\n\n print('[Note] Done generating features.\\n')\n\n if self.compile:\n\n if not self.keep_build_directory:\n self.reset_build_directory()\n\n for style in self.enabled_styles:\n\n print('[Note] Compiling OTFs for \"{}\":'.format(style.name))\n\n font = style.open_font()\n if font.info.postscriptFontName != style.output_full_name_postscript:\n font.info.postscriptFontName = style.output_full_name_postscript\n print('\\n[Note] Fixed the PostScript name.')\n font.save()\n\n with open(os.path.join(style.directory, 'features'), 'w') as file:\n file.write(kit.templates.FEATURES)\n\n with open(os.path.join(style.directory, 'weightclass.fea'), 'w') as file:\n file.write(kit.templates.WEIGHTCLASS.format(str(style.weight_class)))\n\n otf_name = style.output_full_name_postscript + '.otf'\n otf_path = os.path.join(kit.paths.BUILD, otf_name)\n\n # Prepare makeotf arguments\n\n arguments = [\n '-f', style.path,\n '-o', otf_path,\n '-mf', kit.paths.FMNDN,\n '-gf', self.family.goadb_path,\n '-r',\n '-shw',\n '-rev', self.fontrevision\n ]\n\n # Style linking:\n\n if self.do_style_linking:\n if style.is_bold:\n arguments.append('-b')\n if style.is_italic:\n arguments.append('-i')\n\n # New bits in OS/2.fsSelection\n\n if self.use_os_2_version_4:\n for digit, boolean in [\n ('7', self.prefer_typo_metrics),\n ('8', self.is_width_weight_slope_only),\n ('9', style.is_oblique),\n ]:\n arguments.append('-osbOn' if boolean else '-osbOff')\n arguments.append(digit)\n\n arguments.extend(additional_arguments)\n\n # Run makeotf\n\n subprocess.call(['makeotf'] + arguments)\n\n # Remove the project file\n\n project_file_path = os.path.join(style.directory, 'current.fpr')\n subprocess.call(['rm', '-f', project_file_path])\n\n # Copy the compiled font file to Adobe's fonts folder\n\n if os.path.exists(otf_path) and os.path.exists(kit.paths.OUTPUT):\n subprocess.call(['cp', '-f', otf_path, kit.paths.OUTPUT])\n\n print()\n\n print('[Note] Done compiling OTFs.\\n')\n\n print('[Note] {} Done building.\\n'.format(time.strftime('%H:%M:%S')))\n\ndef sort_glyphs(glyph_order, glyph_names):\n sorted_glyphs = (\n [i for i in glyph_order if i in glyph_names] +\n [i for i in glyph_names if i not in glyph_order]\n )\n return sorted_glyphs\n\ndef compose_glyph_class_def_lines(class_name, glyph_names):\n if glyph_names:\n glyph_class_def_lines = (\n ['@{} = ['.format(class_name)] +\n [' {}'.format(glyph_name) for glyph_name in glyph_names] +\n ['];', '']\n )\n else:\n glyph_class_def_lines = ['# @{} = [];'.format(class_name), '']\n return glyph_class_def_lines\n\ndef glyph_filter_marks(glyph):\n has_mark_anchor = False\n for anchor in glyph.anchors:\n if anchor.name.startswith('_'):\n has_mark_anchor = True\n break\n return has_mark_anchor\n\ndef generate_glyph_classes(family, font, glyph_classes, output_path = None):\n glyph_order = [\n development_name for\n production_name, development_name, unicode_mapping in\n family.goadb\n ]\n output_lines = []\n for class_name, filter_function in glyph_classes:\n glyph_names = [glyph.name for glyph in filter(filter_function, font)]\n glyph_names = sort_glyphs(glyph_order, glyph_names)\n font.groups.update({class_name: glyph_names})\n if output_path:\n output_lines.extend(\n compose_glyph_class_def_lines(class_name, glyph_names)\n )\n font.save()\n if output_path:\n with open(output_path, 'w') as file:\n file.write('\\n'.join(output_lines))\n","sub_path":"hindkit/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":15414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"310691678","text":"import getpass\nimport pickle\nimport os\nimport subprocess\n\n\nclass Shopping:\n def __init__(self, file_goods, file_vip, file_user):\n self.file_goods = file_goods\n self.file_vip = file_vip\n self.file_user = file_user\n\n self.login_user = []\n\n self.goods_list = []\n self.user_list = [{'admin': 'admin'}]\n self.vip_list = []\n\n # *****************************************#\n # ************数据写入文件**********************#\n # ******************************************#\n\n def save_data(self, file, data):\n with open(file, 'wb') as fobj:\n for item in data:\n pickle.dump(item, fobj)\n\n # *****************************************#\n # ************提示信息**********************#\n # ******************************************#\n\n def show_menu(self, type):\n main_menu = \"\"\"\n********欢迎使用wjy系统**********\n0) 销售系统\\n1) 会员系统\\n2) 商品系统\\n3) 退出\\n请选择: \"\"\"\n\n vip_menu = \"\"\"\n************会员系统************\n0) 新增\\n1) 修改\\n2) 查询\\n3) 返回\\n请选择: \"\"\"\n\n goods_menu = \"\"\"\n************商品系统************\n0) 新增\\n1) 修改\\n2) 查询\\n3) 返回\\n请选择: \"\"\"\n all_info = {'main': main_menu, 'goods': goods_menu, 'vip': vip_menu}\n\n return all_info[type]\n\n # *********************************************##\n # **************商品管理系统***********************#\n # **********************************************#\n\n def add_goods(self):\n while True:\n name = input('品名(输入end退出): ')\n if name == 'end':\n break\n price = input('单价: ')\n number = input('数量: ')\n states = 1\n new_data = {'code': '1', 'name': name, 'price': float(price), 'number': int(number), 'states': states}\n c = 0\n n = 1\n for data in self.goods_list:\n c += 1\n if data['name'] == name:\n data['price'] = price\n data['number'] = number\n n = 0\n break\n if n:\n new_data['code'] = str(c)\n self.goods_list.append(new_data)\n print('商品数据更新成功!')\n self.save_data(self.file_goods, self.goods_list)\n\n def update_goods(self):\n name = input('修改商品: ')\n n = 0\n for data in self.goods_list:\n if data['name'] == name:\n print(data)\n price = input('调整后单价: ')\n number = input('调整后数量: ')\n data['price'] = price\n data['number'] = number\n n = 1\n break\n if n:\n print('修改成功!')\n\n else:\n print('没有此商品!')\n self.save_data(self.file_goods, self.goods_list)\n\n def query_goods(self):\n print('品名\\t价格($)\\t库存')\n for data in self.goods_list:\n print('%s\\t%s\\t%s' % (data['name'], data['price'], data['number']))\n\n def sys_goods(self):\n goods_cmds = {'0': self.add_goods, '1': self.update_goods, '2': self.query_goods}\n while True:\n try:\n choice = input(self.show_menu('goods')).strip()[0]\n except IndexError:\n break\n if choice not in '0123':\n print('Invalid input')\n if choice == '3':\n break\n goods_cmds[choice]()\n\n # *********************************************#\n # *****************销售系统**********************#\n # *********************************************#\n\n def show_goods_info(self):\n c = 1\n nums = []\n for item in self.goods_list:\n if item['states']:\n nums.append(item['code'])\n if c % 5 == 0:\n print('(%s)%s ' % (item['code'], item['name']))\n else:\n print('(%s)%s ' % (item['code'], item['name']), end='')\n c += 1\n return nums\n\n def print_info(self, array):\n codelist = []\n for item in array:\n for sp in self.goods_list:\n if sp['code'] == item[0]:\n sp['number'] = sp['number'] - item[1]\n codelist.append([sp['name'], item[1], float(item[1]) * float(sp['price'])])\n continue\n\n print('*********商品详情**********')\n sumMoney = 0\n count = 0\n for goods in codelist:\n print(\"\"\"%s\\t%s\\t%s\"\"\" % (goods[0], goods[1], goods[2]))\n sumMoney += goods[2]\n count += int(goods[1])\n print('***************************')\n print('合计: %s\\t数量: %s' % (sumMoney, count))\n money = input('实收金额: ')\n give = float(money) - float(sumMoney)\n print('实收金额: %s\\t找零: %s' % (money, give))\n self.save_data(self.file_goods, self.goods_list)\n input('')\n\n def sys_pay(self):\n che = []\n\n while True:\n codes = self.show_goods_info()\n code = input('\\n选择编码(输入end结束):')\n if code == 'end':\n break\n if code not in codes:\n print('无效商品!')\n continue\n num = input('购买数量: ')\n che.append([code, int(num)])\n\n print('')\n if len(che):\n self.print_info(che)\n\n # **********************************************#\n # ****************会员系统************************#\n # **********************************************#\n\n def add_vip(self):\n hname = input('会员姓名: ')\n htel = input('电话: ')\n n = 1\n for data in self.vip_list:\n if data['tel'] == htel:\n n = 0\n break\n\n if n:\n data = {'name': hname, 'tel': htel}\n self.vip_list.append(data)\n print('新增会员:\\n', data)\n else:\n print('电话为%s的会员已存在!')\n self.save_data(self.file_vip, self.vip_list)\n\n def update_vip(self):\n htel = input('旧电话: ')\n n = 1\n for data in self.vip_list:\n if data['tel'] == htel:\n newhtel = input('新号码: ')\n data['tel'] = newhtel\n print('操作成功!')\n n = 0\n break\n\n if n: print('没有此会员')\n self.save_data(self.file_vip, self.vip_list)\n\n def query_vip(self):\n print('*' * 30)\n print('%-8s%-8s' % ('姓名', '电话'))\n for data in self.vip_list:\n print('%-8s%-8s' % (data['name'], data['tel']))\n\n print(\"*\" * 30)\n\n def sys_vip(self):\n vip_cmds = {'0': self.add_vip, '1': self.update_vip, '2': self.query_vip}\n while True:\n choice = input(self.show_menu('vip')).strip()[0]\n if choice not in '0123':\n print('Invalid input')\n if choice == '3':\n break\n vip_cmds[choice]()\n\n # *************初始化数读取数据***************#\n\n def check_file(self):\n if not os.path.exists(self.file_goods):\n subprocess.call('touch %s' % self.file_goods, shell=True)\n if not os.path.exists(self.file_vip):\n subprocess.call('touch %s' % self.file_vip, shell=True)\n if not os.path.exists(self.file_user):\n with open(self.file_user, 'wb') as fobj:\n data = {\"admin\": 'admin'}\n pickle.dump(data, fobj)\n\n def init_data(self, file, data_list):\n with open(file, 'rb') as fobj:\n while True:\n try:\n data = pickle.load(fobj)\n except EOFError:\n break\n data_list.append(data)\n\n # *****************登陆验证******************#\n\n def check_login(self, loginName, loginPass):\n n = 0\n for item in self.user_list:\n if item.get(loginName, 0) and item[loginName] == loginPass:\n n = 1\n break\n\n return n\n\n # *****************菜单入口*****************#\n\n def _main(self):\n self.check_file()\n self.init_data(self.file_goods, self.goods_list)\n self.init_data(self.file_vip, self.vip_list)\n self.init_data(self.file_user, self.user_list)\n\n uname = input('用户名: ')\n upass = getpass.getpass('密码: ')\n\n if self.check_login(uname, upass):\n self.login_user.append(uname)\n main_cmds = {'0': self.sys_pay, '1': self.sys_vip, '2': self.sys_goods}\n while True:\n choice = input(self.show_menu('main')).strip()[0]\n if choice not in '0123':\n print('Invalid input')\n if choice == '3':\n break\n main_cmds[choice]()\n\n\nif __name__ == '__main__':\n goods_info = '/root/shopping/goods.data'\n vip_info = '/root/shopping/vip.data'\n user_info = '/root/shopping/user.data'\n shopping = Shopping(goods_info, vip_info, user_info)\n shopping._main()\n","sub_path":"python2/day1/shopping.py","file_name":"shopping.py","file_ext":"py","file_size_in_byte":9276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"638700270","text":"#!/usr/bin/env python3\nimport os, socket\nimport hashlib, binascii\nfrom Crypto.Cipher import AES\nimport base64\n\n\n\nsalt='fdgdsfsdfksd48u48rh4ethdgdsfasfasddsvfbmfignspwiopetcosdfxz'\nkey=1\n# авторизация пользователя.\n\ndef crypto(what,crypt):\n BLOCK_SIZE = 32\n PADDING = '{'\n pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING\n\n EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))\n DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)\n\n secret = os.urandom(BLOCK_SIZE)\n\n cipher = AES.new(secret)\n\n if what == 1:\n # шифруем строку\n encoded = EncodeAES(cipher, crypt)\n true_key = encoded\n else:\n # расшифровываем строку\n decoded = DecodeAES(cipher, crypt)\n true_key = decoded\n return true_key\n\ndef get_key(s_key):\n\n\n f_key = open('/usr/local/my_vk/vk.conf', 'w')\n put_key = crypto(1, s_key)\n\n f_key.write(put_key)\n f_key.close()\n\n\n\ndef start():\n if os.path.exists(\"/usr/local/my_vk/vk.conf\"):\n print('pshel nax')\n else:\n os.mkdir('/usr/local/my_vk/')\n f = open('/usr/local/my_vk/vk.conf','w')\n f.close()\n print('Готово, чувак!')\n\n\n\n key = input(\"Введите ваш ключ \\n\"\n \"Очень просто получить ключ, для этого нужно пройти по ссылке: \\n\"\n \"https://oauth.vk.com/authorize?client_id=5725898&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends,photos,audio,video,docs,notes,pages,status,wall,groups,messages,notifications,offline&response_type=token \\n\")\n\n if key != 1:\n get_key(key)\n\n\n\n\nstart()\n","sub_path":"vk.py","file_name":"vk.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"393250800","text":"import csv\nimport math\nimport setting\n\n# def\ndef analyzeRules(sourceCSV):\n #1, 1~0.9, 0.9~-0.8\n num1 = 0\n num2 = 0\n num3 = 0\n with open(sourceCSV) as f:\n reader = csv.DictReader(f)\n for row in reader:\n rule = row[\"rules\"]\n ruleParts = rule.replace(\"{\", \"\").replace(\"}\", \"\").split(\"=>\")\n preArr = ruleParts[0].split(\",\")\n laterArr = ruleParts[1].split(\",\")\n allArr = preArr+laterArr\n if len(allArr) == 2:\n confidence = float(row[\"confidence\"])\n if confidence == 1:\n num1 += 1\n elif confidence >=0.9:\n num2 += 1\n else:\n num3 += 1\n print(num1)\n print(num2)\n print(num3)\n\n\n\n#\ndef analyzeTime(sourceCSV, saveCSV):\n frequentItemDict = {}\n itemCountDict = {}\n with open(sourceCSV) as f:\n reader = csv.DictReader(f)\n for row in reader:\n rule = row[\"rules\"]\n ruleParts = rule.replace(\"{\", \"\").replace(\"}\", \"\").split(\"=>\")\n preArr = ruleParts[0].split(\",\")\n laterArr = ruleParts[1].split(\",\")\n allArr = []\n for i in preArr:\n i = i.strip()\n allArr.append(i)\n for i in laterArr:\n i = i.strip()\n allArr.append(i)\n allArr = sorted(allArr)\n allStr = \"\"\n for index in range(0, len(allArr)):\n allStr += allArr[index]\n if index != len(allArr) - 1:\n allStr += \"|\"\n if allStr in frequentItemDict.keys():\n count = frequentItemDict[allStr]\n count += 1\n frequentItemDict[allStr] = count\n # print(count)\n else:\n frequentItemDict[allStr] = 1\n itemCountDict[allStr] = len(allArr)\n if str(len(allArr)) not in itemCountDict.keys():\n itemCountDict[str(len(allArr))] = 1\n else:\n count1 = itemCountDict[str(len(allArr))]+1\n itemCountDict[str(len(allArr))] = count1\n # for i in itemCountDict.keys():\n # print(i + \":\" + str(itemCountDict[i]))\n # for i in frequentItemDict.keys():\n # itemNumber = itemCountDict[i]\n # count = frequentItemDict[i]\n # if count == math.pow(2, itemNumber)-2 :\n # print(i)\n # print(itemNumber)\n # print(count)\n with open(saveCSV, \"w\") as f:\n writer = csv.DictWriter(f, fieldnames=[\"frequent_items\", \"count\"])\n writer.writeheader()\n for i in frequentItemDict.keys():\n writer.writerow({\"frequent_items\":i, \"count\":frequentItemDict[i]})\n\n\n# def\ndef calculateTransationItems(sourceCSV, saveCSV):\n arr = []\n with open(sourceCSV) as f:\n for line in f.readlines():\n lineArr = line.replace(\"\\n\", \"\").split(\",\")\n arr.append(len(lineArr))\n with open(saveCSV, \"w\") as f:\n writer = csv.DictWriter(f, fieldnames=[\"items\"])\n writer.writeheader()\n for i in arr:\n writer.writerow({\"items\":i})\n\n\n# def two itemset\ndef twoItemset(sourceCSV, saveCSV):\n twoItemSetDict = {}\n with open(sourceCSV) as f:\n reader = csv.DictReader(f)\n for row in reader:\n rule = row[\"rules\"]\n count = int(row[\"count\"])\n ruleParts = rule.replace(\"{\", \"\").replace(\"}\", \"\").split(\"=>\")\n pre = ruleParts[0].split(\",\")[0].strip()\n later = ruleParts[1].split(\",\")[0].strip()\n twoArr = sorted([pre, later])\n twoStr = \"\"\n for index in range(0, len(twoArr)):\n twoStr += twoArr[index]\n if index != len(twoArr) - 1:\n twoStr += \"|\"\n if twoStr not in twoItemSetDict.keys():\n twoItemSetDict[twoStr] = count\n # 对字典排序\n sortedItemsList = sorted(twoItemSetDict.items(),key=lambda x:x[1], reverse=True)\n with open(saveCSV, \"w\") as f:\n writer = csv.DictWriter(f, fieldnames=[\"twoItems\", \"count\"])\n writer.writeheader()\n for (key, value) in sortedItemsList:\n writer.writerow({\"twoItems\":key, \"count\":value})\n\n\n\n\n# def get n_items\ndef allFrequentItems(sourceCSV, saveCSV):\n saveDict = {}\n itemCountDict = {}\n frequentItemDict = {}\n with open(sourceCSV) as f:\n reader = csv.DictReader(f)\n for row in reader:\n rule = row[\"rules\"]\n ruleParts = rule.replace(\"{\", \"\").replace(\"}\", \"\").split(\"=>\")\n preArr = ruleParts[0].split(\",\")\n laterArr = ruleParts[1].split(\",\")\n allArr = []\n for i in preArr:\n i = i.strip()\n allArr.append(i)\n for i in laterArr:\n i = i.strip()\n allArr.append(i)\n allArr = sorted(allArr)\n itemCount = len(allArr)\n allStr = \"\"\n for index in range(0, len(allArr)):\n allStr += allArr[index]\n if index != len(allArr) - 1:\n allStr += \"|\"\n itemCountDict[allStr] = itemCount\n if allStr in frequentItemDict.keys():\n count = frequentItemDict[allStr]\n count += 1\n frequentItemDict[allStr] = count\n else:\n frequentItemDict[allStr] = 1\n for i in frequentItemDict.keys():\n if frequentItemDict[i] == itemCountDict[allStr]:\n saveDict[i] = 1\n with open(saveCSV, \"w\") as f:\n writer = csv.DictWriter(f, fieldnames=[\"items\"])\n writer.writeheader()\n for i in saveDict.keys():\n writer.writerow({\"items\":i})\n\n\ndef saveDependency(dependencyListCSV, sourceCSVArr, saveCSV):\n saveArr =[]\n allDict = readToOne(sourceCSVArr)\n # for i in allDict:\n # print(len(list(allDict[i].keys())))\n\n dependencyList = []\n with open(dependencyListCSV) as f:\n for line in f.readlines():\n dependencyArr = line.replace(\"\\n\", \"\").split(\",\")\n newDict = {}\n # print(len(dependencyArr))\n for i in dependencyArr:\n i = i.strip()\n newDict[i] = 1\n dependencyList.append(newDict)\n\n for index in range(0, len(dependencyList)):\n newDict = dependencyList[index]\n dependencies = list(newDict.keys())\n # print(dependencies)\n count = len(dependencies)\n largestStr = \"\"\n largest = 0\n\n for i in allDict.keys():\n i = int(i)\n if not i > count:\n numberDict = allDict[i]\n for allStr in numberDict.keys():\n freArr = allStr.split(\"|\")\n # freDict = {}\n notFit = False\n for h in freArr:\n if h not in newDict.keys():\n notFit = True\n break\n if notFit == False:\n if len(freArr) > largest:\n largest = len(freArr)\n largestStr = allStr\n print(largest)\n saveStr = \"\"\n for m in newDict.keys():\n saveStr += (m+\"|\")\n saveStr = saveStr[0:-1]\n saveArr.append((saveStr,largestStr, count, largest))\n with open(saveCSV, \"w\") as f:\n writer = csv.DictWriter(f, fieldnames=[\"dependency\", \"largestItems\", \"count\", \"largest\"])\n for (saveStr,largestStr, count, largest) in saveArr:\n writer.writerow({\"dependency\":saveStr, \"largestItems\":largestStr, \"count\":count, \"largest\":largest})\n\n\n\n\n# read all the Dict\ndef readToOne(sourceCSVArr):\n allDict = {}\n for index in range(0, len(sourceCSVArr)):\n number = index+2\n newDict = {}\n with open(sourceCSVArr[index]) as f:\n lines = f.readlines()\n for index in range(1, len(lines)):\n allStr = lines[index].replace(\"\\n\", \"\").split(\",\")[0]\n newDict[allStr] = 1\n allDict[number] = newDict\n return allDict\n\n\n\n\n\n\n# def main():\n# # allFrequentItems(\"/Users/hiumei/Documents/Trivial_CSV/fre_15_40_05.csv\", \"/Users/hiumei/Documents/Trivial_CSV/fre_15_40_05_frequent_items.csv\")\n# #saveDependency(setting.DEPENDENCY_LIST_CSV, setting.ALL_FREQUENT_CSV_ARR, setting.COMBINE_INTO_A_LARGE_ONE_CSV)\n# main()\n\n\n\n","sub_path":"frequent_item_set.py","file_name":"frequent_item_set.py","file_ext":"py","file_size_in_byte":8497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"650753026","text":"import json\nimport urllib.parse\nimport urllib.request\nimport os\n\ndef read_serpwow_key():\n\n\tserpwow_api_key = None\n\tabsolute_path = os.path.abspath(os.path.dirname(__file__))\n\n\n\ttry:\n\t\tif os.path.isfile(os.path.join(absolute_path, 'search.key')):\n#\t\t\tprint(\"found 1\")\n\t\t\twith open(os.path.join(absolute_path, 'search.key'), 'r') as f:\n\t\t\t\tserpwow_api_key = f.readline().strip()\n\t\telse:\n#\t\t\tprint(\"found 2\")\n\t\t\twith open(os.path.join(os.path.join(absolute_path, '..'), 'search.key'), 'r') as f:\n\t\t\t\tserpwow_api_key = f.readline().strip()\t\t\n\n\texcept:\n\t\traise IOError('search.key file not found')\n\n\treturn serpwow_api_key\n\t\n\ndef run_query(search_terms, size=10):\n\n\tserpwow_api_key = read_serpwow_key()\n\tprint(serpwow_api_key)\n\tif not serpwow_api_key:\n\t\traise KeyError('Serpwow Key not found')\n\n\troot_url = 'https://api.serpwow.com/live/search'\n\n\tquerystring = urllib.parse.quote(search_terms)\n\tsearch_url = ('{root_url}?api_key={key}&q={query}&num={size}').format(root_url=root_url, key=serpwow_api_key, query=querystring, size=size)\n\n\tresults = []\n\n\ttry:\n\t\tresponse = urllib.request.urlopen(search_url).read().decode('utf-8')\n\t\tjson_response = json.loads(response)\n\n\t\tfor post in json_response['organic_results']:\n\t\t\tif 'snippet' in post:\n\t\t\t\tresults.append({'title' : post['title'], 'link': post['link'], 'summary': post[\"snippet\"][:200] })\n\t\t\telse :\n\t\t\t\tresults.append({'title' : post['title'], 'link': post['link']})\n\n\texcept:\n\t\tprint(\"Error while querying the Serpwow API\")\n\n\treturn results\n\t\ndef main():\t\n\tsearch_terms = input(\"Enter Query : \")\n\tresults = run_query(search_terms)\n\tfor post in results:\n\t\tprint(\"title : {0} - link : {1}\".format(post['title'], post['link']))\n\t\tif 'summary' in post:\n\t\t\tprint(post['summary'])\n\t\tprint('\\n \\n')\n\n\n\n\n\nif __name__ == '__main__':\n\tmain()\n\t\n\n\n","sub_path":"TwD/rango/serpwow_search.py","file_name":"serpwow_search.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"140746304","text":"__author__ = 'Wilson'\n\n\nclass Person:\n def __init__(self, gender, name):\n self.gender = gender\n self.name = name\n\n def display(self):\n print(\"You're a \", self.gender, \", and your name is \", self.name)\n\npeople = Person('Male', 'Wilson')\n\npeople.display()\n\npeople.name = 'WilsonK'\npeople.gender = 'Female'\n\npeople.display()\n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"104626925","text":"# Copyright 2015 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\n\"\"\"Simple, end-to-end, LeNet-5-like convolutional MNIST model example.\nThis should achieve a test error of 0.7%. Please keep this model as simple and\nlinear as possible, it is meant as a tutorial for simple convolutional models.\nRun with --self_test on the command line to execute a short self-test.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport matplotlib.pyplot as plt\nimport numpy\nimport tensorflow as tf\nimport settings\nfrom common import label\nfrom common.mnist import extract_cnn_images, extract_cnn_labels\nfrom solve import model\nfrom solve.solve_arguments import parse_arguments\n\n\ndef show_top_5(y):\n \"\"\"Print top 5 matches from the probability distribution returned by softmax\"\"\"\n top_5_indices = numpy.argpartition(y, -5)[-5:]\n top_5_prob = y[top_5_indices]\n\n top_5 = list(zip(top_5_indices, top_5_prob))\n top_5.sort(key=lambda x: x[1], reverse=True)\n for idx, prob in top_5:\n print('%s %s' % (label.get_character_from_label(idx), prob * 100))\n\n\ndef visualize(dataset):\n \"\"\"Visualize dataset\"\"\"\n \"\"\"Visualize dataset and infer\"\"\"\n for img, lbl in dataset:\n plt.imshow(img.reshape((settings.WINDOW_HEIGHT, settings.WINDOW_WIDTH)), cmap='gray')\n plt.show()\n\n\ndef visualize_qa(network, sess, dataset):\n \"\"\"Visualize dataset and infer\"\"\"\n for img, lbl in dataset:\n solved = network.eval_one(img)\n\n actual = label.get_character_from_label(numpy.argmax(solved))\n expected = label.get_character_from_label(lbl)\n print('%r guess(%s) answer(%s)' % (actual == expected, actual, expected))\n\n show_top_5(solved)\n\n plt.imshow(img.reshape((settings.WINDOW_HEIGHT, settings.WINDOW_WIDTH)), cmap='gray')\n plt.show()\n\n\ndef main(argv=None): # pylint: disable=unused-argument\n args = parse_arguments()\n\n test_data_filename = os.path.join(\n args.data_dir, 't10k-images-idx3-ubyte.gz')\n test_labels_filename = os.path.join(\n args.data_dir, 't10k-labels-idx1-ubyte.gz')\n\n # Extract it into numpy arrays.\n test_data = extract_cnn_images(open(test_data_filename, 'rb'))\n test_labels = extract_cnn_labels(open(test_labels_filename, 'rb'))\n\n # Create a local session to run the training.\n dataset = zip(test_data, test_labels)\n\n if args.visualize_without_ai:\n visualize(dataset)\n else:\n with tf.Session() as sess:\n network = model.restore_classification_network(\n sess, args.session_file, label.get_count())\n if args.print_accuracy:\n test_error = model.error_rate(network.eval(test_data), test_labels)\n print('Test error: %.1f%%' % test_error)\n elif args.visualize:\n visualize_qa(network, sess, dataset)\n\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"solve/solve_classification.py","file_name":"solve_classification.py","file_ext":"py","file_size_in_byte":3575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"203197463","text":"from http.server import *\nimport random\nimport string\nimport ssl\nfrom command_control.models import pwnedHost\n\n\nclass Server_Response(BaseHTTPRequestHandler):\n\n # chars = string.ascii_letters + string.digits\n # session_value = ''.join(random.choice(chars) for i in range(20))\n global session_value, user_agent, value\n session_value = \"6Q2HydryJknyIyyVv8Om\"\n user_agent = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36\"\n # trantab = str.maketrans(\"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz\",\"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm\")\n value = session_value # .translate(trantab)\n\n def set_attributes(self):\n global ip\n global host\n ip = self.client_address[0]\n if pwnedHost.objects.filter(ip=ip):\n host = pwnedHost.objects.get(ip=ip)\n else:\n try:\n content_length = int(self.headers['Content-Length'])\n post_data = self.rfile.read(content_length)\n data = post_data.decode('utf-8')\n except:\n pass\n host = pwnedHost(author=author, ip=ip, username=\"\")\n host.save()\n\n def set_headers(self):\n self.send_response(200, \"ok\")\n self.send_header('Content-type', 'text/html')\n self.send_header('Set-Cookie',session_value)\n # self.send_header('Server', 'Microsoft IIS/7.5')\n self.end_headers()\n\n def unauth_set_headers(self):\n self.send_response(403, \"forbidden\")\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n\n # Allow GET\n def do_GET(self):\n\n self.set_attributes()\n\n global URI, cookie, agent\n print(self.headers)\n try:\n URI = self.raw_requestline.decode().split(\" \")[1]\n cookie = self.headers['Cookie'].split(\" = \")[-1]\n agent = self.headers['User-agent']\n except:\n pass\n\n message = host.cmd[6:]\n print(host.cmd)\n\n if URI == \"/wp-post.php\" and cookie == session_value and agent == user_agent:\n self.set_headers()\n if message:\n self.wfile.write(bytes(message).encode(\"utf-8\"))\n host.cmd = \"\"\n host.save()\n else:\n self.unauth_set_headers()\n msg = \" You are not authorized. Your access is forbidden.\"\n self.wfile.write(msg.encode('utf-8'))\n\n\n # Allow POST\n def do_POST(self):\n self.set_attributes()\n global URI, cookie, agent\n try:\n URI = self.raw_requestline.decode().split(\" \")[1]\n cookie = self.headers['Cookie'].split(\" = \")[-1]\n agent = self.headers['User-agent']\n except:\n pass\n\n if URI == \"/wp-admin/admin-ajax.php\" and cookie == session_value and agent == user_agent:\n self.set_headers()\n content_length = int(self.headers['Content-Length'])\n post_data = self.rfile.read(content_length)\n data = post_data.decode('utf-8')\n data_len = int(len(data) - 20)\n\n if data[-20:] != str(value):\n print(\"The verification code %s was not received\" %value)\n\n if data:\n host.result = data[:data_len] + \"\\n\"\n host.save()\n\n else:\n self.unauth_set_headers()\n msg = \" You are not authorized. Your access is forbidden.\"\n self.wfile.write(msg.encode('utf-8'))\n\n\ndef run(auth_user, ip , port, enc_key):\n global author\n global secret\n global cipher\n secret = enc_key\n author = auth_user\n global Server_Response\n print(\"Server Started ..!!\")\n server_address = (ip, port)\n httpd = HTTPServer(server_address, Server_Response)\n # httpd.socket = ssl.wrap_socket (httpd.socket, certfile='server.cert', keyfile='server.key', server_side=True)\n httpd.socket = ssl.wrap_socket(httpd.socket, certfile='/var/www/desi_command_control/server.cert', keyfile=\"/var/www/desi_command_control/server.key\", server_side=True)\n print('running server...')\n httpd.serve_forever()\n\n\n","sub_path":"c2.py","file_name":"c2.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"97807807","text":"'''\nYou are given a non-empty, zero-indexed array A of n (1 � n � 100 000) integers\na0, a1, . . . , an−1 (0 � ai � 1 000). This array represents number of mushrooms growing on the\nconsecutive spots along a road. You are also given integers k and m (0 � k, m < n).\nA mushroom picker is at spot number k on the road and should perform m moves. In\none move she moves to an adjacent spot. She collects all the mushrooms growing on spots\nshe visits. The goal is to calculate the maximum number of mushrooms that the mushroom\npicker can collect in m moves.\nFor example, consider array A such that:\n''' \ndef count_totals(p,x,y):\n return p[y+1] - p[x]\ndef mushroom(A,k,m):\n # A - is the array \n # k- is there position -4\n # m - number of moves they can make -6 \n n = len(A)\n result = 0 \n pref = [0] * n \n pref[0] = A[0]\n for i in range(1,n):\n pref[i] = pref[i-1] + A[i]\n \n for p in range(min(m,k) + 1):\n # p----> 0,1,2,3,4\n # k ----> 4 ,k-p ->4,3,2,1,0\n \n left_pos = k-p\n right_pos = min(n-1,max(k,k+m-2 *p))\n result = max(result,count_totals(pref,left_pos,right_pos))\n for p in range(min(m+1,n-k)):\n right_pos = k + p \n left_pos = max(0,min(k,k-(m-2 * p)))\n result = max(result,count_totals(pref,left_pos,right_pos))\n print(re) \n # print(left_pos)\n\nmushroom([2,3,7,5,1,3,9],4,6) ","sub_path":".history/mushroomPicker_20200729131120.py","file_name":"mushroomPicker_20200729131120.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"118118534","text":"import itertools\nimport time\n\nimport colors\nimport random\nimport presets\nfrom presets import attributes\n\n\nRGBA = colors.RGBA\n\n\ndef rainbow_color(n, alpha=1):\n n = int(n)\n if n < 256: return RGBA(255, n, 0, alpha)\n if n < 512: return RGBA(255 - (n - 256), 255, 0, alpha)\n if n < 768: return RGBA(0, 255, (n - 512), alpha)\n if n < 1024: return RGBA(0, 255 - (n - 768), 255, alpha)\n if n < 1280: return RGBA((n - 1024),0 , 255, alpha)\n if n < 1536: return RGBA(255, 0, 255 - (n - 1280), alpha)\n return rainbow_color(n % 1536, alpha)\n\n\nclass Car(object):\n def __init__(self, x, xv, color):\n self.x = x % 1.0\n self.xv = xv\n self.color = color\n\n def iterate(self, seconds_past):\n self.x += self.xv * seconds_past\n if self.x < 0:\n self.x *= -1\n self.xv *= -1\n elif self.x > 1:\n self.x = 2 - self.x\n self.xv *= -1\n self.color = (self.color + int(self.xv * 1000 * seconds_past)) % 1536\n\n\nclass Cars(presets.Preset):\n def __init__(self, name='Cars'):\n super(Cars, self).__init__(name)\n self.cars = []\n self.num_cars = attributes.IntAttribute('num_cars', 10)\n self.attributes['num_cars'] = self.num_cars\n self.speed = attributes.FloatAttribute('speed', 1.0)\n self.attributes['speed'] = self.speed\n\n def draw(self, pixels, seconds_past):\n seconds_past *= self.speed.val\n num_cars = self.num_cars.val\n self.cars.extend(\n Car(random.random() * len(pixels), 0.01 + random.random() * 0.01, random.randint(0, 1535))\n for _ in xrange(num_cars - len(self.cars)))\n for car in itertools.islice(self.cars, 0, num_cars):\n car.iterate(seconds_past)\n x = car.x * len(pixels)\n pixels.draw_line(x - 1, x + 1, rainbow_color(car.color))\n\npresets.PRESETS.append(Cars())\n\n\nclass ExplosionBit(object):\n def __init__(self, x, xv, color, ttl):\n self.x = x\n self.xv = xv\n self.color = color\n self.ttl = ttl\n\n def iterate(self, seconds_past):\n self.x += self.xv * seconds_past\n if self.x < 0:\n self.x *= -1\n self.xv *= -1\n elif self.x > 1:\n self.x = 2 - self.x\n self.xv *= -1\n self.color = (self.color + int(1000 * seconds_past)) % 1536\n\n\nclass ExplodingCars(presets.Preset):\n def __init__(self, name='Exploding Cars'):\n super(ExplodingCars, self).__init__(name)\n self.cars = []\n self.explosion_bits = []\n self.num_exploding_cars = attributes.IntAttribute('num_exploding_cars', 5)\n self.attributes['num_exploding_cars'] = self.num_exploding_cars\n\n def draw(self, pixels, seconds_past):\n num_cars = self.num_exploding_cars.val\n now = time.time()\n self.cars.extend(\n Car(0, 0.01 + random.random() * 0.01, random.randint(0, 1535))\n for _ in xrange(num_cars - len(self.cars)))\n if len(self.cars) > num_cars:\n self.cars = self.cars[:num_cars]\n\n for j, car_j in enumerate(self.cars):\n for k, car_k in enumerate(itertools.islice(self.cars, j + 1, num_cars), j + 1):\n # if there is a collision with cars coming from opposite directions:\n if (car_j.x - car_k.x) * (car_j.x + seconds_past * car_j.xv - car_k.x - seconds_past * car_k.xv) < 0 and car_j.xv * car_k.xv < 0:\n # Optionally swap cars there's a chance of either car exploding.\n if random.random() < 0.1:\n self.cars[j], self.cars[k] = self.cars[k], self.cars[j]\n self.explosion_bits.extend(ExplosionBit(car_k.x, 0.05 * (-1 + 2 * random.random()), car_k.color, now + 0.1 + random.random()) for _ in xrange(5))\n self.cars[k] = self.cars[-1]\n self.cars.pop()\n break\n\n for car in self.cars:\n car.iterate(seconds_past)\n x = car.x * len(pixels)\n pixels.draw_line(x - 1, x + 1, rainbow_color(car.color))\n j = 0\n while j < len(self.explosion_bits):\n if self.explosion_bits[j].ttl < now:\n self.explosion_bits[j] = self.explosion_bits[-1]\n self.explosion_bits.pop()\n else:\n j += 1\n for bit in self.explosion_bits:\n bit.iterate(seconds_past)\n x = bit.x * len(pixels)\n pixels.draw_line(x - 0.4, x + 0.4, rainbow_color(bit.color, 0.5))\n\n\npresets.PRESETS.append(ExplodingCars())\n","sub_path":"server/presets/cars_presets.py","file_name":"cars_presets.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"88790298","text":"#!/usr/bin/python3\n\nopen_file = open('./dest/comp3.fasta', 'r')\nwrit_file = open('./dest/data.txt', 'w')\n\n\n#Gets the Covid Name\ndef get_name(line):\n s_line = line.lstrip('>')\n a_list = s_line.split()\n the_name = a_list[0]\n return the_name\n \n###########################################################################\n\n#Takes the list and Covid Name and writes to data.txt\ndef process_it(inserted_list, inserted_name):\n poly_a_length = 0\n the_string = ''\n break_out = False\n while True:\n last_line = inserted_list.pop()\n s_line = last_line.strip()\n the_string = s_line + the_string\n for letter in the_string:\n if letter != 'A':\n break_out = True\n break\n \n if break_out:\n break\n \n flip_line = the_string[::-1]\n \n for letter in flip_line:\n if letter == 'A':\n poly_a_length += 1\n\n else:\n break\n \n writ_file.write(inserted_name)\n writ_file.write(\": Poly_a_tail_length = \")\n \n the_tail_length = str(poly_a_length)\n \n writ_file.write(the_tail_length)\n writ_file.write('\\n')\n\n###########################################################################\n\nthe_list = []\nfirst_line = True\n\nfor line in open_file:\n if first_line and line.startswith('>'):\n covid_name = get_name(line)\n first_line = False\n \n elif line.startswith('>'):\n process_it(the_list, covid_name)\n covid_name = get_name(line)\n the_list = []\n \n else:\n the_list.append(line)\n \n#process the final list when end of file \nprocess_it(the_list, covid_name)\n\n\nopen_file.close()\nwrit_file.close()\n\n","sub_path":"pyauto/poly_a_tail.py","file_name":"poly_a_tail.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"283426836","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 25 15:54:33 2020\n\n@author: loris\n\nFaça um programa que peça um número inteiro e determine se ele é ou não um número primo. \nUm número primo é aquele que é divisível somente por ele mesmo e por 1.\n\n\n\"\"\"\n\nentrada = int(input(\"Insira o numero para verificar se é primo: \"))\n\ndivisores = 1\nfor n in range(1, entrada):\n if entrada % n == 0:\n divisores += 1\n \nif divisores > 2:\n print(\"Não é primo! \")\nif divisores <= 2:\n print(\"O número é primo!\")","sub_path":"3 - Estrutura de Repetição/21.py","file_name":"21.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"305445505","text":"import numpy as np\nimport collections\nfrom scipy import stats\nimport itertools\nimport pandas\nfrom scipy.integrate import quad\nfrom scipy.interpolate import interp1d\nfrom astropy.cosmology import FlatLambdaCDM\nfrom sklearn.linear_model import LinearRegression\n\nfrom colossus.cosmology import cosmology\nfrom colossus.lss import peaks\n\n\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'serif'\nrcParams['mathtext.fontset'] = 'dejavuserif'\nrcParams['mathtext.rm'] = 'serif'\nrcParams['mathtext.it'] = 'serif:italic'\nrcParams['mathtext.bf'] = 'serif:bold'\nrcParams['axes.titlepad'] = 12\nrcParams['axes.labelsize'] = 20\nrcParams['axes.titlesize'] = 25\nrcParams['figure.dpi'] = 80\nrcParams['figure.figsize'] = [8, 6]\nrcParams['figure.titlesize'] = 25\nrcParams['font.size'] = 20.0\nrcParams['legend.fontsize'] = 20\nrcParams['legend.frameon'] = False\nrcParams['savefig.pad_inches'] = 0\nrcParams['xtick.labelsize'] = 18\nrcParams['ytick.labelsize'] = 18\n\n#############################\n# Cosmological calculations #\n#############################\n\nh = 0.688\nomega_m = 0.295\nomega_L = 1 - omega_m\ncosmo = FlatLambdaCDM(H0 = h * 100, Om0 = omega_m)\nconst1 = 0.102271217 # 100km/s/Mpc = const1 Gyr^-1, H0 = h * const1 Gyr^-1\nconst2 = 3.2407793E-18 # 100km/s/Mpc = const2 s^-1, H0 = h * const2 s^-1\nG = 4.5170908E-48 # grav. constant in s^-2/(Msun/Mpc^3)\n\ndef E2(z):\n return omega_m * (1 + z) ** 3 + omega_L\n\ndef Delta_c(z):\n x = - omega_L / E2(z)\n return 18 * np.pi * np.pi + 82 * x - 39 * x * x\n\ndef rho_c(z): # physical in Msun / Mpc^3\n return 3 * h * h * const2 * const2 * E2(z) / 8 / np.pi / G\n\ndef age(a): # in Gyr\n z = 1 / a - 1\n return cosmo.age(z)\n\nparams = {'flat': True, 'H0': 68.8, 'Om0': 0.295, 'Ob0': 0.0468, 'sigma8': 0.834, 'ns': 0.968}\ncosmology.setCosmology('myCosmo', params)\ndef peak_height(M, a):\n z = 1 / a - 1\n return peaks.peakHeight(M, z)\n\n#############################\n###### Halo properties ######\n#############################\n\ndef Rvir(Mvir, a): # Mvir at a in Msun/h, Rvir comoving in kpc/h\n z = 1 / a - 1\n return np.power(3 * Mvir / h / 4 / np.pi / Delta_c(z) / rho_c(z),\n 1 / 3) * 1000 * h / a\n\ndef Vvir(Mvir, a): # Mvir at a in Msun/h, Vvir physical in km/s\n return np.sqrt(G * Mvir / Rvir(Mvir, a) / a * 1000) * 3.08567758E19\n\ndef cv(Mvir, Vmax, a): # Vmax / Vvir\n return Vmax / Vvir(Mvir, a)\n\n#############################\n###### Dynamical times ######\n#############################\n\ndef tdyn(a): # in Gyr\n z = 1 / a - 1\n return np.pi / h / const1 / np.sqrt(E2(z) * 2 * Delta_c(z))\n\ndef ntdyn(a, ai = 0.06): # number of tdyn's at a since ai\n z = 1 / a - 1\n zi = 1 / ai - 1\n return quad(lambda x: 1 / (1 + x) / tdyn(1 / (1 + x)) / np.sqrt(E2(x)),\n z, zi)[0] / h / const1\n\na_interp = np.linspace(0.06, 1, 1000)\nn_interp = np.array([ntdyn(a) for a in a_interp])\nntau_a = interp1d(a_interp, n_interp)\na_ntau = interp1d(n_interp, a_interp)\n\n#############################\n#### Time steps in tree #####\n#############################\n\na_list = np.hstack((np.linspace(6, 10, 9), np.linspace(11, 100, 90))) / 100\nz_list = 1 / a_list - 1\nn_list = ntau_a(a_list)\n\n#############################\n###### History and mark #####\n#############################\n\nptclmass_b = 2.44e9\nptclmass_i = 7.63E7\n\ndef load_history(table, namestr): # Nhalo * Nstep\n key = []\n for a in a_list:\n key.append(namestr + str(a))\n key[-1] = namestr + '1'\n history = []\n for k in key:\n history.append(np.array(table[k]))\n return np.array(history).T\n\ndef diff_history(history): # Nhalo * Nstep\n return np.diff(history, axis = 1, prepend = 0)\n\n# Mass bins for calculating mark values for each sample.\nmbins_h12 = 10.0 ** (12 + np.linspace(0, np.log10(1.1), 21))\nmbins_h13 = 10.0 ** (13 + np.linspace(0, np.log10(2), 21))\nmbins_h14 = 10.0 ** (14 + np.linspace(0, 1, 31) ** 2 \\\n * (np.log10(37.783) + 0.00001))\n\ndef calculate_mark(prop, Mvir, Mbin, discrete = False, interval = None):\n prop_mark = np.zeros_like(prop)\n for i in range(len(Mbin) - 1):\n mask = np.logical_and(Mvir >= Mbin[i], Mvir < Mbin[i + 1])\n prop_bin = prop[mask].astype(float)\n if discrete:\n prop_bin += np.random.rand(len(prop_bin)) * interval\n argsort = np.argsort(prop_bin)\n mark = np.zeros_like(prop_bin)\n mark[argsort] = np.arange(1, len(prop_bin) + 1) / len(prop_bin)\n prop_mark[mask] = mark\n return prop_mark\n\n#############################\n### Step-wise correlation ###\n#############################\n\ndef spearmanr_mark(history, prop, Mvir, Mbin,\n discrete_hist = False, interval_hist = None,\n discrete_prop = False, interval_prop = None):\n prop_mark = calculate_mark(prop, Mvir, Mbin, discrete_prop, interval_prop)\n spearmanr = []\n for step in history.T:\n step_mark = calculate_mark(step, Mvir, Mbin,\n discrete_hist, interval_hist)\n spearmanr.append(stats.spearmanr(prop_mark, step_mark).correlation)\n return spearmanr\n\n#############################\n##### Linear regression #####\n#############################\n\ndef reg_mark_spearmanr(history, prop, Mvir, Mbin,\n discrete_hist = False, interval_hist = None,\n discrete_prop = False, interval_prop = None):\n prop_mark = calculate_mark(prop, Mvir, Mbin, discrete_prop, interval_prop)\n hist_mark = []\n for step in history.T:\n hist_mark.append(calculate_mark(step, Mvir, Mbin,\n discrete_hist, interval_hist))\n hist_mark = np.array(hist_mark)\n coef = LinearRegression().fit(hist_mark.T, prop_mark).coef_\n return coef, stats.spearmanr(\n calculate_mark(np.dot(coef, hist_mark), Mvir, Mbin),\n prop_mark).correlation\n\ndef reg_spearmanr(history, prop, Mvir, Mbin,\n discrete_hist = False, interval_hist = None,\n discrete_prop = False, interval_prop = None):\n prop_mark = calculate_mark(prop, Mvir, Mbin, discrete_prop, interval_prop)\n coef = LinearRegression().fit(history, prop_mark).coef_\n return coef, stats.spearmanr(\n calculate_mark(np.dot(coef, history.T), Mvir, Mbin),\n prop_mark).correlation\n\n#############################\n####### Major mergers #######\n#############################\n\ndef a_before_mm(a_mm, n_back = 1):\n n_mm = ntau_a(a_mm)\n n_before = n_mm - 1\n assert n_before >= 0\n return a_nt(n_before)\n\ndef a_after_mm(a_mm, n_forth = 1):\n n_mm = ntau_a(a_mm)\n n_after = n_mm + 1\n assert n_after <= ntau_a(1)\n return a_nt(n_after)\n\ndef dM_ratio_mm(mfrac, a_mm, n_back = 1, n_forth = 1):\n m_a = interp1d(a_list, mfrac)\n m_before = m_a(a_before_mm(a_mm, n_back = n_back))\n m_after = m_a(a_after_mm(a_mm, n_forth = n_forth))\n return m_after - m_before, (m_after - m_before) / m_before\n\n#############################\n####### Miscellaneous #######\n#############################\n\n# return mask of values in a given bin\ndef in_bin(array, lower, upper):\n return np.logical_and(array >= lower, array <= upper)\ndef in_bin_2d(prop1, prop2, low1, up1, low2, up2):\n return np.logical_and(in_bin(prop1, low1, up1), in_bin(prop2, low2, up2))\n\n# calculate trimmed mean with NaNs excluded\ndef nan_trimmed_mean(array, axis = None, trim = 0.):\n return np.nanmean(\n stats.trimboth(np.array(array), trim, axis = axis),\n axis = axis)\n\n# calculate trimmed mean in log space with NaNs excluded\ndef nan_trimmed_mean_log(array, axis = None, trim = 0.):\n return np.power(10, np.nanmean(np.log10(\n stats.trimboth(np.array(array), trim, axis = axis)),\n axis = axis))\n\n# calculate trimmed std with NaNs excluded\ndef nan_trimmed_std(array, axis = None, trim = 0.):\n return np.nanstd(\n stats.trimboth(np.array(array), trim, axis = axis),\n axis = axis)\n\n# calculate trimmed std in log space with NaNs excluded\ndef nan_trimmed_std_log(array, axis = None, trim = 0.):\n return np.power(10, np.nanstd(np.log10(\n stats.trimboth(np.array(array), trim, axis = axis)),\n axis = axis))\n\n# calculates p-value for a given sample size and spearman rho\ndef pvalue_spearman(sample_size, corrcoeff):\n t = corrcoeff * \\\n np.sqrt((sample_size - 2) / ((corrcoeff + 1) * (1 - corrcoeff)))\n return 2 * stats.distributions.t.sf(np.abs(t), sample_size - 2)\n\n# returns indices for njk jackknife subsamples\ndef jackknife_idx(length, njk):\n indices = np.arange(length)\n np.random.shuffle(indices)\n return [np.setdiff1d(indices, arr) for arr in np.array_split(indices, njk)]\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"419818696","text":"#!/usr/bin/env python3\n\"\"\"\nCreator: Linji Wang (wang1278)\nDate of Creation: 02/28/20\nFile Name: wang1278_assignment06.py\nDiscription:\n This script takes multiple file names as command line argument, reads data,\n plots data, and saves the plots into .pdf files for each file.\n\"\"\"\n\n# Import numply for reading data from files and matplotlib.pyplot for ploting\nimport numpy as np\nimport matplotlib.pyplot as plt\n# Import argv from sys for parsing command line options\nimport sys\n# Import os for removing file extensions\nimport os\n\n# import data from files and use the first line as header\nfor i in range(len(sys.argv)):\n if i>0:\n data=np.genfromtxt(sys.argv[i],names=True,delimiter='\\t')\n\n # Configure plot settings\n plt.figure(figsize=(15,15))\n plt.subplots_adjust(hspace=0.5)\n\n # Generate plots\n plt.subplot(311)\n plt.plot(data['Year'],data['Mean'], 'k',data['Year'],data['Max'], 'r',\n data['Year'],data['Min'], 'b')\n plt.legend([\"Mean\",\"Max\",\"Min\"], loc='best',edgecolor='k')\n plt.xlabel(\"Year\")\n plt.ylabel(\"Streamflow (cfs)\")\n plt.subplot(312)\n plt.plot(data['Year'],data['Tqmean']*100, 'g^')\n plt.xlabel(\"Year\")\n plt.ylabel(\"Tqmean (%)\")\n plt.subplot(313)\n plt.bar(data['Year'],data['RBindex'])\n plt.xlabel(\"Year\")\n plt.ylabel(\"R-B Index (ratio)\")\n \n # Save plots in pdf\n savename=os.path.splitext(sys.argv[i])\n plt.savefig(savename[0]+'.pdf')\n plt.close()\nprint('Data Plotting Complete!')","sub_path":"wang1278_assignment06.py","file_name":"wang1278_assignment06.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"586570389","text":"# -*- coding: utf-8 -*-\nimport os,random\nimport codecs\nfrom subprocess import call\nimport random\n\nhiragana = {\n \"name\" : \"hiragana\",\n \"base\" : [\n [\"a\", u\"あ\"], [\"i\", u\"い\"], [\"u\", u\"う\"], [\"e\", u\"え\"], [\"o\", u\"お\"], \n [\"ka\", u\"か\"], [\"ki\", u\"き\"], [\"ku\", u\"く\"], [\"ke\", u\"け\"], [\"ko\", u\"こ\"], \n [\"sa\", u\"さ\"], [\"shi\", u\"し\"], [\"su\", u\"す\"], [\"se\", u\"せ\"], [\"so\", u\"そ\"], \n [\"ta\", u\"た\"], [\"chi\", u\"ち\"], [\"tsu\", u\"つ\"], [\"te\", u\"て\"], [\"to\", u\"と\"], \n [\"na\", u\"な\"], [\"ni\", u\"に\"], [\"nu\", u\"ぬ\"], [\"ne\", u\"ね\"], [\"no\", u\"の\"], \n [\"ha\", u\"は\"], [\"hi\", u\"ひ\"], [\"fu\", u\"ふ\"], [\"he\", u\"へ\"], [\"ho\", u\"ほ\"], \n [\"ma\", u\"ま\"], [\"mi\", u\"み\"], [\"mu\", u\"む\"], [\"me\", u\"め\"], [\"mo\", u\"も\"], \n [\"ya\", u\"や\"], [\"yu\", u\"ゆ\"], [\"yo\", u\"よ\"], \n [\"ra\", u\"ら\"], [\"ri\", u\"り\"], [\"ru\", u\"る\"], [\"re\", u\"れ\"], [\"ro\", u\"ろ\"], \n [\"wa\", u\"わ\"], [\"wo\", u\"を\"], \n [\"n\", u\"ん\"]\n ],\n \"combo\" : [\n [\"kya\", u\"きゃ\"], [\"kyu\", u\"きゅ\"], [\"kyo\", u\"きょ\"], \n [\"sya\", u\"しゃ\"], [\"syu\", u\"しゅ\"], [\"syo\", u\"しょ\"], \n [\"tya\", u\"ちゃ\"], [\"tyu\", u\"ちゅ\"], [\"tyo\", u\"ちょ\"], \n [\"nya\", u\"にゃ\"], [\"nyu\", u\"にゅ\"], [\"nyo\", u\"にょ\"], \n [\"mya\", u\"みゃ\"], [\"myu\", u\"みゅ\"], [\"myo\", u\"みょ\"], \n [\"rya\", u\"りゃ\"], [\"ryu\", u\"りゅ\"], [\"ryo\", u\"りょ\"], \n [\"gya\", u\"ぎゃ\"], [\"gyu\", u\"ぎゅ\"], [\"gyo\", u\"ぎょ\"], \n [\"jya\", u\"じゃ\"], [\"jyu\", u\"じゅ\"], [\"jyo\", u\"じょ\"], \n [\"dzya\", u\"ぢゃ\"], [\"dzyu\", u\"ぢゅ\"], [\"dzyo\", u\"ぢょ\"], \n [\"bya\", u\"びゃ\"], [\"byu\", u\"びゅ\"], [\"byo\", u\"びょ\"], \n [\"pya\", u\"ぴゃ\"], [\"pyu\", u\"ぴゅ\"], [\"pyo\", u\"ぴょ\"]\n ],\n \"dakuten\" : [\n [\"ga\", u\"が\"], [\"gi\", u\"ぎ\"], [\"gu\", u\"ぐ\"], [\"ge\", u\"げ\"], [\"go\", u\"ご\"],\n [\"za\", u\"ざ\"], [\"ji\", u\"じ\"], [\"zu\", u\"ず\"], [\"ze\", u\"ぜ\"], [\"zo\", u\"ぞ\"],\n [\"da\", u\"だ\"], [\"dzi\", u\"ぢ\"], [\"dzu\", u\"づ\"], [\"de\", u\"で\"], [\"do\", u\"ど\"],\n [\"ba\", u\"ば\"], [\"bi\", u\"び\"], [\"bu\", u\"ぶ\"], [\"be\", u\"べ\"], [\"bo\", u\"ぼ\"],\n [\"pa\", u\"ぱ\"], [\"pi\", u\"ぴ\"], [\"pu\", u\"ぷ\"], [\"pe\", u\"ぺ\"], [\"po\", u\"ぽ\"]\n ]\n}\n\nkatakana = {\n \"name\" : \"katakana\",\n \"base\" : [\n [\"a\", u\"ア\"], [\"i\", u\"イ\"], [\"u\", u\"ウ\"], [\"e\", u\"エ\"], [\"o\", u\"オ\"], \n [\"ka\", u\"カ\"], [\"ki\", u\"キ\"], [\"ku\", u\"ク\"], [\"ke\", u\"ケ\"], [\"ko\", u\"コ\"], \n [\"sa\", u\"サ\"], [\"shi\", u\"シ\"], [\"su\", u\"ス\"], [\"se\", u\"セ\"], [\"so\", u\"ソ\"], \n [\"ta\", u\"タ\"], [\"chi\", u\"チ\"], [\"tsu\", u\"ツ\"], [\"te\", u\"テ\"], [\"to\", u\"ト\"], \n [\"na\", u\"ナ\"], [\"ni\", u\"ニ\"], [\"nu\", u\"ヌ\"], [\"ne\", u\"ネ\"], [\"no\", u\"ノ\"], \n [\"ha\", u\"ハ\"], [\"hi\", u\"ヒ\"], [\"fu\", u\"フ\"], [\"he\", u\"ヘ\"], [\"ho\", u\"ホ\"], \n [\"ma\", u\"マ\"], [\"mi\", u\"ミ\"], [\"mu\", u\"ム\"], [\"me\", u\"メ\"], [\"mo\", u\"モ\"], \n [\"ya\", u\"ヤ\"], [\"yu\", u\"ユ\"], [\"yo\", u\"ヨ\"], \n [\"ra\", u\"ラ\"], [\"ri\", u\"リ\"], [\"ru\", u\"ル\"], [\"re\", u\"レ\"], [\"ro\", u\"ロ\"], \n [\"wa\", u\"ワ\"], [\"wo\", u\"ヲ\"], \n [\"n\", u\"ン\"]\n ],\n \"combo\" : [\n [\"kya\", u\"キャ\"], [\"kyu\", u\"キュ\"], [\"kyo\", u\"キョ\"], \n [\"sya\", u\"シャ\"], [\"syu\", u\"シュ\"], [\"syo\", u\"ショ\"], \n [\"tya\", u\"���ャ\"], [\"tyu\", u\"チュ\"], [\"tyo\", u\"チョ\"], \n [\"nya\", u\"ニャ\"], [\"nyu\", u\"ニュ\"], [\"nyo\", u\"ニョ\"], \n [\"mya\", u\"ミャ\"], [\"myu\", u\"ミュ\"], [\"myo\", u\"ミョ\"], \n [\"rya\", u\"リャ\"], [\"ryu\", u\"リュ\"], [\"ryo\", u\"リョ\"], \n [\"gya\", u\"ギャ\"], [\"gyu\", u\"ギュ\"], [\"gyo\", u\"ギョ\"], \n [\"jya\", u\"ジャ\"], [\"jyu\", u\"ジュ\"], [\"jyo\", u\"ジョ\"], \n [\"dzya\", u\"ヂャ\"], [\"dzyu\", u\"ヂュ\"], [\"dzyo\", u\"ヂョ\"], \n [\"bya\", u\"ビャ\"], [\"byu\", u\"ビュ\"], [\"byo\", u\"ビョ\"], \n [\"pya\", u\"ピャ\"], [\"pyu\", u\"ピュ\"], [\"pyo\", u\"ピョ\"]\n ],\n \"dakuten\" : [\n [\"ga\", u\"ガ\"], [\"gi\", u\"キ\"], [\"gu\", u\"ぐ\"], [\"ge\", u\"げ\"], [\"go\", u\"ご\"],\n [\"za\", u\"ザ\"], [\"ji\", u\"ジ\"], [\"zu\", u\"ズ\"], [\"ze\", u\"ゼ\"], [\"zo\", u\"ゾ\"],\n [\"da\", u\"ダ\"], [\"dzi\", u\"ヅ\"], [\"dzu\", u\"ヅ\"], [\"de\", u\"デ\"], [\"do\", u\"ド\"],\n [\"ba\", u\"バ\"], [\"bi\", u\"ビ\"], [\"bu\", u\"ブ\"], [\"be\", u\"ベ\"], [\"bo\", u\"ボ\"],\n [\"pa\", u\"パ\"], [\"pi\", u\"ピ\"], [\"pu\", u\"プ\"], [\"pe\", u\"ペ\"], [\"po\", u\"ポ\"]\n ]\n}\n\nINDICES = {\n \"hiragana\" : {\n \"base\" : len(hiragana[\"base\"])-1,\n \"combo\" : len(hiragana[\"combo\"])-1,\n \"dakuten\" : len(hiragana[\"dakuten\"])-1\n }, \n \"katakana\" : {\n \"base\" : len(katakana[\"base\"])-1,\n \"combo\" : len(katakana[\"combo\"])-1,\n \"dakuten\" : len(katakana[\"dakuten\"])-1\n }\n}\n\ndef generateRandomIndices( dictionary, base_cnt=8, combo_cnt=2, dakuten_cnt=2 ):\n return {\n \"base\" : [random.randrange(INDICES[dictionary[\"name\"]][\"base\"]) for idx in range(base_cnt*8)],\n \"combo\" : [random.randrange(INDICES[dictionary[\"name\"]][\"combo\"]) for idx in range(combo_cnt*8)],\n \"dakuten\" : [random.randrange(INDICES[dictionary[\"name\"]][\"dakuten\"]) for idx in range(dakuten_cnt*8)]\n }\n\ndef generateTable( indices, dictionary, isJapanese = False, tableSet = [8,2,2], totalRowCount = 12 ):\n baseIdx = 0\n comboIdx = 0\n dakutenIdx = 0\n\n baseRowCount = min(totalRowCount,tableSet[0])\n comboRowCount = min(totalRowCount-baseRowCount,tableSet[1])\n dakutenRowCount = min(totalRowCount-baseRowCount-comboRowCount,tableSet[2])\n\n rows = [\"\\\\begin{tabular}{|c|c|c|c|c|c|c|c|}\"]\n for rIdx in xrange(totalRowCount):\n row = '\\\\taRows' if isJapanese else '\\\\atRows'\n for cIdx in xrange(8):\n if rIdx < baseRowCount:\n ii = indices[\"base\"][baseIdx]\n char = dictionary[\"base\"][ii][isJapanese]\n baseIdx += 1\n elif rIdx < (baseRowCount + comboRowCount):\n ii = indices[\"combo\"][comboIdx]\n char = dictionary[\"combo\"][ii][isJapanese]\n comboIdx += 1\n else :\n ii = indices[\"dakuten\"][dakutenIdx]\n char = dictionary[\"dakuten\"][ii][isJapanese]\n dakutenIdx += 1\n row += \"{%s}\" % char\n rows.append(row)\n rows.append(\"\\\\end{tabular}\")\n return \"\\n\".join(rows)\n\ndef buildPDF(pages = 20, baseCount = 8, comboCount = 2, dakutenCount = 2):\n templateStr = \"\"\n\n tableSet = [baseCount, comboCount, dakutenCount]\n\n tables = []\n for pIdx in xrange(pages):\n \"\"\" Ten pages of practice grids\"\"\"\n if pIdx % 2:\n characterset = hiragana\n else:\n characterset = katakana\n index = generateRandomIndices(characterset, baseCount, comboCount, dakutenCount)\n\n if pIdx:\n tables.append('\\n\\\\clearpage\\n')\n tables.append('\\n\\\\raggedright\\n')\n tables.append(generateTable(index, characterset, True, tableSet))\n tables.append('\\n\\\\raggedleft\\n')\n tables.append(generateTable(index, characterset, False, tableSet))\n\n with codecs.open(\"sheet.tex\", encoding=\"utf-8\", mode=\"r\") as template:\n print(\"Opened template\")\n templateStr = template.read()\n templateStr = templateStr.replace(u'%%%%%TABLES%%%%%', \"\\n\".join(tables))\n\n with codecs.open(\"tempsheet.tex\",encoding=\"utf-8\", mode=\"w\") as template:\n print(\"Writing template\")\n template.write(templateStr)\n \n print(\"Generating PDF\")\n # call([\"latexmk\", \"-e\", \"$pdflatex = 'pdflatex -interaction=nonstopmode'\", \"-f\", \"-pdf\", \"tempsheet.tex\"])\n call([\"latexmk\", \"-e\", \"$pdflatex = 'pdflatex -interaction=batchmode'\", \"-f\", \"-pdf\", \"tempsheet.tex\"])\n call([\"latexmk\", \"-c\"])\n\n os.remove(\"tempsheet.tex\")\n\nif __name__ == '__main__':\n buildPDF(2)\n print(\"Finished Script\")\n\n exit(0)","sub_path":"Python/gensheet.py","file_name":"gensheet.py","file_ext":"py","file_size_in_byte":7839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"394766675","text":"from django.conf.urls import url\nfrom control_modules import views\n\n\napp_name = 'control_modules'\nurlpatterns = [\n url(r'^webcam/$', views.webcam, name='webcam'),\n url(r'^lights/$', views.lights, name='lights'),\n url(r'^set-lights-ajax/$', views.set_lights_ajax, name=\"set_lights_ajax\"),\n url(r'^move-motor-ajax/$', views.move_motor_ajax, name=\"move_motor_ajax\"),\n url(r'^change-camera-options-ajax/$', views.change_camera_options_ajax,\n name=\"change_camera_options_ajax\"),\n url(r'^measurements/$', views.measurements, name=\"measurements\"),\n url(r'^make-measurement-ajax/$', views.make_measurement_ajax, name=\"make_measurement_ajax\"),\n url(r'^get-measurement-logs-ajax/$', views.get_measurement_logs_ajax, \n name=\"get_measurement_logs_ajax\"),\n url(r'^measure-temperature-ajax/$', views.measure_temperature_ajax, \n name=\"measure_temperature_ajax\"),\n url(r'^measure-humidity-ajax/$', views.measure_humidity_ajax,\n name=\"measure_humidity_ajax\"),\n]\n","sub_path":"mysite/control_modules/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"392576760","text":"from enum import Enum\n\n\nclass AccountType(Enum):\n STANDARD = 1\n STAFF = 2\n EMPLOYER = 3\n\n\nACCOUNT_TYPE_CHOICES = [\n (AccountType.STANDARD.value, 'standard'),\n (AccountType.STAFF.value, 'staff'),\n (AccountType.EMPLOYER.value, 'employer')\n]\n\nTYPE_CHOICES_VERBOSE = [\n ('standard', 'standard'),\n ('staff', 'staff'),\n ('employer', 'employer')\n]\n\nTYPE_TO_INT_MAP = {\n 'standard': 1,\n 'staff': 2,\n 'employer': 3\n}\n\nclass StaffGroupType(Enum):\n STAFF_GUEST = 'staff_guest'\n STAFF_VERIFICATION = 'staff_verification'\n STAFF_CV = 'staff_cv'\n STAFF_JOBS = 'staff_jobs'\n STAFF_BLOG_CREATOR = 'staff_blog_creator'\n STAFF_BLOG_MODERATOR = 'staff_blog_moderator'\n STAFF_CHAT_ACCESS = 'staff_chat_access'\n\n @staticmethod\n def get_all_types():\n return [e.value for e in StaffGroupType]\n\n\nSTAFF_GROUP_CHOICES = [\n (StaffGroupType.STAFF_GUEST.value, 'staff_guest'),\n (StaffGroupType.STAFF_VERIFICATION.value, 'staff_verification'),\n (StaffGroupType.STAFF_CV.value, 'staff_cv'),\n (StaffGroupType.STAFF_JOBS.value, 'staff_jobs'),\n (StaffGroupType.STAFF_BLOG_CREATOR.value, 'staff_blog_creator'),\n (StaffGroupType.STAFF_BLOG_MODERATOR.value, 'staff_blog_moderator'),\n (StaffGroupType.STAFF_CHAT_ACCESS.value, 'staff_chat_access')\n]\n","sub_path":"src/account/account_type.py","file_name":"account_type.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"18423503","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 23 15:28:32 2018\n\n@author: stephaneblondellarougery\n\"\"\"\n\n\n\n\n# Initialisation et finalisation du fichier\ninit_sql = \"\"\"\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\nSET AUTOCOMMIT = 0;\nSTART TRANSACTION;\nSET time_zone = \"+00:00\";\n\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\n/*!40101 SET NAMES utf8mb4 */;\n\n\"\"\"\n\n\n\nend_sql = \"\"\"\nCOMMIT;\n\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n\"\"\"\n\n\nimport os\n\n\ndef create_col(col_name, col_type, col_dim, col_special):\n \n special = {}\n special[\"PK\"] = \"PRIMARY KEY\"\n special[\"PK - AI\"] = \"PRIMARY KEY\"\n special[\"FK\"] = \"DEFAULT NULL\" # Les FK ne sont pas encore prises en compte\n special[\"\"] = \"DEFAULT NULL\"\n \n if col_type == \"TINYINT\":\n col_dim = \"1\"\n \n line = \"\\n `\"+col_name+\"` \"+col_type.lower()+\"(\"+col_dim+\")\"+\" \"+special[col_special]+\",\"\n return line\n \n \ndef init_table(table_name, arguments):\n request = \"CREATE TABLE `\"+table_name+\"` (\"\n data_insert = \"INSERT INTO `\"+table_name+\"` (\"\n \n if len(arguments) % 4 == 0:\n N = len(arguments)//4\n \n for n in range(0,N):\n col_name = str(arguments[0+4*n])\n col_type = str(arguments[1+4*n])\n col_dim = str(arguments[2+4*n])\n col_special = str(arguments[3+4*n])\n \n request += create_col(col_name, col_type, col_dim, col_special)\n data_insert+= \"`\"+col_name+\"`, \"\n \n else:\n print(\"Error : Invalid number of argumets.\\nPlease specify : col_name | col_type | col_dim | col_special.\")\n \n request = request[:-1] # Suppression de la dernière virgule\n request += \"\\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\" \n \n data_insert = data_insert[:-2]\n data_insert += \") VALUES\"\n \n request += \"\\n\\n\"\n request += data_insert\n return request\n\ndef is_string(item):\n try:\n int(item)\n return False\n except:\n return True\n\ndef quotable(item):\n quotable_item = \"\"\n for ch in item:\n if ch == \"'\" :\n quotable_item += \"\\\\\"\n quotable_item += \"'\"\n else:\n quotable_item += ch\n return quotable_item\n \n \ndef add_data(row): \n s = \"\\n(\"\n for item in row:\n if is_string(item):\n s += \"'\"\n s += quotable(item)\n s += \"'\"\n else:\n s += item\n s += \", \"\n s = s[:-2] \n s += \"),\"\n return s\n \ndef create_table(table_name, matrix):\n arguments = []\n \n for i in range(0,len(matrix[0])):\n arguments.append(matrix[0][i])\n arguments.append(matrix[2][i])\n arguments.append(matrix[3][i])\n arguments.append(matrix[1][i])\n \n request = init_table(table_name, arguments)\n \n for i in range(4,len(matrix)):\n request += str(add_data(matrix[i]))\n \n request = request[:-1]\n request += \";\"\n \n return(request)\n\ndef count_tables(db):\n # Le dernier -1 correspond au worksheet 'SQL' à ne pas prendre en compte\n try:\n count = int(str(db)[len(str(db))-3:len(str(db))-1])-1 \n return count\n except:\n return int(str(db)[len(str(db))-2])-1 \n\ndef create_file_request(db):\n request = init_sql\n \n N = count_tables(db)\n for n in range(0,N):\n table = db.worksheet('index',n)\n print(str(table.title)+\" --> SQL\")\n matrix = table.get_all_values()\n request += create_table(str(table.title), matrix)\n request += \"\\n\\n\"\n \n request += end_sql\n return(request)\n\n\ndef create_file(db, file_name):\n \n relative = \"sql/\" + file_name + \".sql\"\n dirname = os.path.dirname(__file__)\n path = os.path.join(dirname, relative)\n \n with open(path, \"w\") as file:\n sql = create_file_request(db)\n file.write(sql)","sub_path":"python-utils/update_db/v1/sql_methods.py","file_name":"sql_methods.py","file_ext":"py","file_size_in_byte":4140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"26803002","text":"#!/usr/bin/python\n\nimport os, sys\nimport time, datetime, getopt, pid\nfrom typing import List, Dict\nimport asyncio\n# import argparse, re\nimport aioblescan as aiobs\nimport logging\n\n# done before importing django app as it does setup\nimport tilt_monitor_utils\n\nfrom django.core.wsgi import get_wsgi_application\napplication = get_wsgi_application()\n\nfrom gravity.tilt.TiltHydrometer import TiltHydrometer\nimport gravity.models\n\n# import django.core.exceptions\n\ntilt_monitor_utils.process_monitor_options()\n\nverbose = tilt_monitor_utils.verbose\nmydev = tilt_monitor_utils.bluetooth_device\n\nLOG = logging.getLogger(\"tilt\")\nLOG.setLevel(logging.INFO)\n\n#### The main loop\n\n# Create a list of TiltHydrometer objects for us to use\ntilts = {x: TiltHydrometer(x) for x in TiltHydrometer.tilt_colors} # type: Dict[str, TiltHydrometer]\n\n# Create the default\nreload_objects_at = datetime.datetime.now() + datetime.timedelta(seconds=15)\n\n\ndef processBLEBeacon(data):\n # While I'm not a fan of globals, not sure how else we can store state here easily\n global verbose\n global reload_objects_at\n global tilts\n\n ev = aiobs.HCI_Event()\n xx = ev.decode(data)\n\n # To make things easier, let's convert the byte string to a hex string first\n if ev.raw_data is None:\n if verbose:\n print(\"Event has no raw_data\\r\\n\")\n LOG.error(\"Event has no raw data\")\n return False\n\n raw_data_hex = ev.raw_data.hex()\n\n if len(raw_data_hex) < 80: # Very quick filter to determine if this is a valid Tilt device\n if verbose:\n print(\"Small raw_data_hex: {}\\r\\n\".format(raw_data_hex))\n return False\n if \"1370f02d74de\" not in raw_data_hex: # Another very quick filter (honestly, might not be faster than just looking at uuid below)\n if verbose:\n print(\"Missing key in raw_data_hex: {}\\r\\n\".format(raw_data_hex))\n return False\n\n # For testing/viewing raw announcements, uncomment the following\n # print(\"Raw data (hex) {}: {}\".format(len(raw_data_hex), raw_data_hex))\n # ev.show(0)\n\n try:\n # Let's use some of the functions of aioblesscan to tease out the mfg_specific_data payload\n\n data = ev.retrieve(\"Manufacturer Specific Data\")\n payload = data[0].payload\n payload = payload[1].val.hex()\n\n # ...and then dissect said payload into a UUID, temp, gravity, and rssi (which isn't actually rssi)\n uuid = payload[4:36]\n temp = int.from_bytes(bytes.fromhex(payload[36:40]), byteorder='big')\n gravity = int.from_bytes(bytes.fromhex(payload[40:44]), byteorder='big')\n # tx_pwr = int.from_bytes(bytes.fromhex(payload[48:49]), byteorder='big')\n # rssi = int.from_bytes(bytes.fromhex(payload[49:50]), byteorder='big')\n rssi = 0 # TODO - Fix this\n except Exception as e:\n LOG.error(e)\n return\n\n if verbose:\n print(\"Tilt Payload (hex): {}\\r\\n\".format(payload))\n\n color = TiltHydrometer.color_lookup(uuid) # Map the uuid back to our TiltHydrometer object\n tilts[color].process_decoded_values(gravity, temp, rssi) # Process the data sent from the Tilt\n\n # The Fermentrack specific stuff:\n reload = False\n if datetime.datetime.now() > reload_objects_at:\n # Doing this so that as time passes while we're polling objects, we still end up reloading everything\n reload = True\n reload_objects_at = datetime.datetime.now() + datetime.timedelta(seconds=30)\n\n for this_tilt in tilts:\n if tilts[this_tilt].should_save():\n tilts[this_tilt].save_value_to_fermentrack(verbose=verbose)\n\n if reload: # Users editing/changing objects in Fermentrack doesn't signal this process so reload on a timer\n tilts[this_tilt].load_obj_from_fermentrack()\n\n\nevent_loop = asyncio.get_event_loop()\n\n# First create and configure a raw socket\nmysocket = aiobs.create_bt_socket(mydev)\n\n# create a connection with the raw socket (Uses _create_connection_transport instead of create_connection as this now\n# requires a STREAM socket) - previously was fac=event_loop.create_connection(aiobs.BLEScanRequester,sock=mysocket)\nfac = event_loop._create_connection_transport(mysocket, aiobs.BLEScanRequester, None, None)\nconn, btctrl = event_loop.run_until_complete(fac) # Start the bluetooth control loop\nbtctrl.process=processBLEBeacon # Attach the handler to the bluetooth control loop\n\n# Begin probing\nbtctrl.send_scan_request()\ntry:\n event_loop.run_forever()\nexcept KeyboardInterrupt:\n if verbose:\n print('Keyboard interrupt\\r\\n')\nfinally:\n if verbose:\n print('Closing event loop\\r\\n')\n btctrl.stop_scan_request()\n command = aiobs.HCI_Cmd_LE_Advertise(enable=False)\n btctrl.send_command(command)\n conn.close()\n event_loop.close()\n","sub_path":"gravity/tilt/tilt_monitor_aio.py","file_name":"tilt_monitor_aio.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"340798637","text":"#!/usr/bin/env python\n\nfrom waflib.TaskGen import before_method, after_method, feature\n\ntop = \"..\"\n\n@feature(\"proto_module\")\n@before_method('propagate_uselib_vars', 'apply_link')\n@after_method('apply_bundle')\ndef proto_module(self):\n\t\"\"\"\n\tremoves 'lib' from cshlib_PATTERN if it's there.\n\t\"\"\"\n\n\tpat = self.env[\"cshlib_PATTERN\"]\n\tif pat[:3] == \"lib\":\n\t\tpat = pat[3:]\n\t\tself.env['cshlib_PATTERN'] = self.env['cxxshlib_PATTERN'] = pat\n\n@feature(\"force_lib_prefix\")\n@before_method('propagate_uselib_vars', 'apply_link')\n@after_method('apply_bundle')\ndef force_lib_prefix(self):\n\t\"\"\"\n\tadds 'lib' to cshlib_PATTERN if it's not there.\n\t\"\"\"\n\n\tpat = self.env[\"cshlib_PATTERN\"]\n\tif pat[:3] != \"lib\":\n\t\tpat = \"lib{0}\".format(pat)\n\t\tself.env['cshlib_PATTERN'] = self.env['cxxshlib_PATTERN'] = pat\n\ndef build(bld):\n\t# \"..\" includes the build directory (for config.h)\n\tbld(export_includes=\".. ../public private\", name=\"lm_inc\")\n\n\tobjs = []\n\tobj = lambda src: objs.append(src)\n\n\t#\n\t# platform\n\t#\n\n\tif bld.env.DEST_OS == \"linux\":\n\t\tif bld.env.LIB_UDEV:\n\t\t\tobj(\"platform/linux_libudev.c\")\n\t\telse:\n\t\t\tobj(\"platform/linux_sysfs.c\")\n\n\t\tobj(\"platform/linux.c\")\n\t\tobj(\"platform/posix.c\")\n\n\telif bld.env.DEST_OS == \"darwin\":\n\t\tobj(\"platform/darwin.c\")\n\t\tobj(\"platform/posix.c\")\n\n\telif bld.env.DEST_OS == \"win32\":\n\t\tobj(\"platform/windows.c\")\n\n\t#\n\t# protocols\n\t#\n\n\tfor p in bld.env.PROTOCOLS:\n\t\tbld.shlib(\n\t\t\tsource=\"proto/{0}.c\".format(p),\n\t\t\tfeatures=\"proto_module\",\n\t\t\tuse=\"lm_inc libmonome\",\n\n\t\t\ttarget=\"protocol_{0}\".format(p),\n\t\t\tinstall_path=\"${LIBDIR}/monome\")\n\n\tif bld.env.LIB_LO:\n\t\tbld.shlib(\n\t\t\tsource=\"proto/osc.c\",\n\t\t\tfeatures=\"proto_module\",\n\t\t\tuse=\"lm_inc libmonome LO\",\n\n\t\t\ttarget=\"protocol_osc\",\n\t\t\tinstall_path=\"${LIBDIR}/monome\")\n\n\t#\n\t# common\n\t#\n\n\tobj(\"rotation.c\")\n\tobj(\"libmonome.c\")\n\n\tif bld.env.DEST_OS == \"win32\":\n\t\tbld.shlib(\n\t\t\tsource=objs,\n\t\t\tfeatures=\"force_lib_prefix\",\n\t\t\tuse=\"lm_inc\",\n\n\t\t\tname=\"libmonome\",\n\t\t\ttarget=\"monome\")\n\telse:\n\t\t# the UDEV use is ignored if it is not defined\n\t\tbld.shlib(\n\t\t\tsource=objs,\n\t\t\tuse=\"lm_inc UDEV DL\",\n\n\t\t\tname=\"libmonome\",\n\t\t\ttarget=\"monome\",\n\t\t\tvnum=bld.env.VERSION)\n\n\tif bld.env.LIB_LO:\n\t\tbld.program(\n\t\t\tsource=\"monomeserial.c\",\n\t\t\tuse=\"lm_inc libmonome LO\",\n\n\t\t\ttarget=\"monomeserial\")\n","sub_path":"src/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"606244333","text":"\"\"\"\nfully_connected_feed.py trains the built MNIST model against the downloaded dataset using a feed dictionary. It is written to be run from the command line\n\n$ python fully_connected_feed.py\n\n$ python3 fully_connected_feed.py --help\nusage: fully_connected_feed.py [-h] [--learning_rate LEARNING_RATE]\n [--max_steps MAX_STEPS] [--hidden1 HIDDEN1]\n [--hidden2 HIDDEN2] [--batch_size BATCH_SIZE]\n [--input_data_dir INPUT_DATA_DIR]\n [--log_dir LOG_DIR] [--fake_data]\n\noptional arguments:\n -h, --help show this help message and exit\n --learning_rate LEARNING_RATE\n Initial learning rate.\n --max_steps MAX_STEPS\n Number of steps to run trainer.\n --hidden1 HIDDEN1 Number of units in hidden layer 1.\n --hidden2 HIDDEN2 Number of units in hidden layer 2.\n --batch_size BATCH_SIZE\n Batch size. Must divide evenly into the dataset sizes.\n --input_data_dir INPUT_DATA_DIR\n Directory to put the input data.\n --log_dir LOG_DIR Directory to put the log data.\n --fake_data If true, uses fake data for unit testing.\n\n\"\"\"\n\n# These 3 lines provides backward compatibility with older Python versions from Python 3 code\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n# six is a package that helps in writing code that is compatible with both Python 2 and Python 3.\nfrom six.moves import xrange # pylint: disable=redefined-builtin\n\nimport argparse\nimport os.path\nimport sys\nimport time\nimport math\nimport tensorflow as tf\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nfrom tensorflow.examples.tutorials.mnist import mnist\n\n# Basic model parameters as external flags.\nFLAGS = None\n\ndef run_training():\n \"\"\"Train MNIST for a number of steps.\"\"\"\n\n # Get the sets of images and labels for training, validation, and test on MNIST.\n data_sets = input_data.read_data_sets(FLAGS.input_data_dir, FLAGS.fake_data)\n\n # We start building the computation graph for the model here. Tell Tensorflow that\n # the model will be built into the default graph. \n with tf.Graph().as_default():\n\n # Generate placeholders for the images and labels.\n images_placeholder = tf.placeholder(tf.float32, shape=(FLAGS.batch_size, mnist.IMAGE_PIXELS))\n labels_placeholder = tf.placeholder(tf.int32, shape=(FLAGS.batch_size))\n \n # Debug mode - print out some stuffs\n print (images_placeholder.get_shape())\n print (labels_placeholder.get_shape())\n\n '''\n The Inference Engine\n - Build a Graph that computes predictions from the inference model.\n '''\n # Hidden 1\n with tf.name_scope('FC1'):\n # Created under the hidden1 scope, the unique name given to the weights variable would be \"hidden1/weights\".\n weights = tf.Variable(tf.truncated_normal([mnist.IMAGE_PIXELS, FLAGS.hidden1],\n stddev=1.0 / math.sqrt(float(mnist.IMAGE_PIXELS))), name='weights')\n # Likewise, the unique name given to the biases variable would be \"hidden1/biases\".\n biases = tf.Variable(tf.zeros([FLAGS.hidden1]), name='biases')\n hidden1 = tf.nn.relu(tf.matmul(images_placeholder, weights) + biases)\n\n # Hidden 2\n with tf.name_scope('FC2'):\n # \"hidden2/weights\"\n weights = tf.Variable(\n tf.truncated_normal([FLAGS.hidden1, FLAGS.hidden2],stddev=1.0 / math.sqrt(float(FLAGS.hidden1))),\n name='weights')\n # \"hidden2/biases\"\n biases = tf.Variable(tf.zeros([FLAGS.hidden2]), name='biases')\n hidden2 = tf.nn.relu(tf.matmul(hidden1, weights) + biases)\n\n # Linear\n with tf.name_scope('softmax_linear'):\n # \"softmax_linear/weights\" \n weights = tf.Variable(tf.truncated_normal([FLAGS.hidden2, mnist.NUM_CLASSES],\n stddev=1.0 / math.sqrt(float(FLAGS.hidden2))), name='weights')\n # \"softmax_linear/biases\" \n biases = tf.Variable(tf.zeros([mnist.NUM_CLASSES]), name='biases')\n logits = tf.matmul(hidden2, weights) + biases\n \n '''\n Loss Function\n - Add to the Graph the Ops for loss calculation.\n '''\n with tf.name_scope('softmax'):\n labels = tf.to_int64(labels_placeholder) #typecasting in int64\n \n # This op produces 1-hot labels from the labels_placeholder and compare them against logits from the\n # inference engine\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits, name='xentropy')\n\n # This op averages the cross entropy values across the batch dimension (the first dimension) as the total loss.\n loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')\n\n '''\n The Training Op\n - Add to the Graph the Ops that calculate and apply gradients.\n '''\n with tf.name_scope('adam_optimizer'):\n\n # tf.summary.scalar is an op for generating summary values into the events file when used with a \n # tf.summary.FileWriter. In this case, it will emit the snapshot value of the loss every time the\n # summaries are written out.\n tf.summary.scalar('loss', loss)\n\n # Create the gradient descent optimizer with the given learning rate.\n optimizer = tf.train.AdamOptimizer(FLAGS.learning_rate)\n # Create a variable to track the global step.\n global_step = tf.Variable(0, name='global_step', trainable=False)\n # Use the optimizer to apply the gradients that minimize the loss\n # (and also increment the global step counter) as a single training step.\n train_op = optimizer.minimize(loss, global_step=global_step, name='minimize')\n\n '''\n The Evaluation Op\n - Add the Op to compare the logits to the labels during evaluation.\n '''\n with tf.name_scope('eval'):\n # For a classifier model, we can use the in_top_k Op. It returns a bool tensor with shape [batch_size] \n # that is true for the examples where the label is in the top k (here k=1) of all logits for that example.\n correct = tf.nn.in_top_k(logits, labels, 1, name = 'top_k')\n # Return the number of true entries.\n eval_correct = tf.reduce_sum(tf.cast(correct, tf.int32), name = 'reduce_sum')\n\n # Build the summary Tensor based on the TF collection of Summaries.\n summary = tf.summary.merge_all() \n \n # Add the variable initializer Op.\n init = tf.global_variables_initializer() # Create a saver for writing training checkpoints.\n\n # Create a session for running Ops on the Graph.\n sess = tf.Session()\n \n # Instantiate a SummaryWriter to output summaries and the Graph.\n summary_writer = tf.summary.FileWriter(FLAGS.log_dir, sess.graph)\n \n # And then after everything is built:\n\n # Run the Op to initialize the variables.\n sess.run(init)\n \n # Start the training loop.\n\n # Fill a feed dictionary with the actual set of images and labels\n # for this particular training step.\n\n # Run one step of the model. The return values are the activations\n # from the `train_op` (which is discarded) and the `loss` Op. To\n # inspect the values of your Ops or variables, you may include them\n # in the list passed to sess.run() and the value tensors will be\n # returned in the tuple from the call.\n \n # Write the summaries and print an overview fairly often.\n # Print status to stdout.\n # Update the events file.\n \n # Save a checkpoint and evaluate the model periodically.\n # Evaluate against the training set.\n # Evaluate against the validation set.\n # Evaluate against the test set.\n summary_writer.close()\n \ndef main(_):\n \n # Deal with the Log file \n if tf.gfile.Exists(FLAGS.log_dir):\n tf.gfile.DeleteRecursively(FLAGS.log_dir) # Delete everything in the log directory if it already exists\n \n tf.gfile.MakeDirs(FLAGS.log_dir) # Create the directory if it does not exist already\n \n run_training() # Start training the model\n\n\nif __name__ == '__main__':\n\n # The argparse module makes it easy to write user-friendly command-line interfaces.\n # Running provides useful help messages describing\n # the optional arguments outlined below.\n parser = argparse.ArgumentParser() # Without a program name, ArgumentParser determine the command-line arguments from sys.argv\n \n parser.add_argument(\n '--learning_rate',\n type=float,\n default=0.01,\n help='Initial learning rate.'\n )\n\n parser.add_argument(\n '--max_steps',\n type=int,\n default=10000,\n help='Number of steps to run trainer.'\n )\n \n parser.add_argument(\n '--hidden1',\n type=int,\n default=128,\n help='Number of units in hidden layer 1.'\n )\n\n parser.add_argument(\n '--hidden2',\n type=int,\n default=32,\n help='Number of units in hidden layer 2.'\n )\n \n parser.add_argument(\n '--batch_size',\n type=int,\n default=100,\n help='Batch size. Must divide evenly into the dataset sizes.'\n )\n\n parser.add_argument(\n '--input_data_dir',\n type=str,\n default='/tmp/tensorflow/mnist/input_data',\n help='Directory to put the input data.'\n )\n \n parser.add_argument(\n '--log_dir',\n type=str,\n default='/home/lukeliem/TensorFlow/logs/fully_connected_feed',\n help='Directory to put the log data.'\n )\n\n parser.add_argument(\n '--fake_data',\n default=False,\n help='If true, uses fake data for unit testing.',\n action='store_true'\n )\n \n # Sometimes a script may only parse a few of the command-line arguments, passing the remaining arguments on to another \n # script or program. parse_known_args() returns a two item tuple containing the populated namespace (into FLAG) and the\n # list of remaining argument strings.\n FLAGS, unparsed = parser.parse_known_args()\n\n # Runs the program with an optional 'main' function and 'argv' list.\n tf.app.run(main=main, argv=[sys.argv[0]] + unparsed) # sys.argv is the list of command line arguments passed to the Python script\n","sub_path":"mechanics/fully_connected_feed-v02.py","file_name":"fully_connected_feed-v02.py","file_ext":"py","file_size_in_byte":10221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"467470881","text":"import json\n\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views.generic import CreateView\nfrom django.views.generic import ListView\n\nfrom mysite.views import LoginRequiredMixin\nfrom naver.models import NaverApiApp\n\n\ndef retrieve_naver_api(query_text=\"\", client_id=None, client_secret=None):\n # naver api test\n import requests\n\n if client_id is None:\n client_id = 'QdLGm_fLiirkonf0kWCR'\n if client_secret is None:\n client_secret = 'yt62pXbTvs'\n\n api_blog_url = \"https://openapi.naver.com/v1/search/blog.json\"\n api_shop_url = \"https://openapi.naver.com/v1/search/shop.json\"\n\n display = 10 # sd\n start = 1 # d\n sort = 'date' # sim : 유사도순, date : 날짜순\n\n payload = {\n 'query': query_text,\n 'display': display,\n 'start': start,\n 'sort': sort\n }\n\n headers = {\n 'X-Naver-Client-Id': client_id,\n 'X-Naver-Client-Secret': client_secret,\n }\n\n response = requests.get(api_blog_url, params=payload, headers=headers, timeout=1.0)\n if response.status_code == 200:\n blog_info = json.loads(response.text)\n else:\n blog_info = None\n\n response = requests.get(api_shop_url, params=payload, headers=headers, timeout=1.0)\n if response.status_code == 200:\n shop_info = json.loads(response.text)\n else:\n shop_info = None\n\n return blog_info, shop_info\n\n\nclass NaverApiAppLV(ListView):\n model = NaverApiApp\n template_name = \"naver/index.html\"\n context_object_name = 'apikeylist'\n paginate_by = 2\n\n def get_context_data(self, **kwargs):\n context = super(NaverApiAppLV, self).get_context_data(**kwargs)\n context['blog_info'], context['shop_info'] = retrieve_naver_api()\n return context\n\n\nclass NaverApiAppCreateView(LoginRequiredMixin, CreateView):\n model = NaverApiApp\n fields = ['app_name', 'client_id', 'client_secret', 'limit']\n success_url = reverse_lazy('naver:index')\n\n def form_valid(self, form):\n form.instance.account = self.request.user\n return super(NaverApiAppCreateView, self).form_valid(form)","sub_path":"naver/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"420506403","text":"## Twisted: @inlineCallbacks \n## \n## @inlineCallbacks around 2006 \n## (ab)uses yield to wait \n## \n\nfrom twisted.internet.defer import Deferred, inlineCallbacks\nfrom twisted.internet.task import react\n\n@inlineCallbacks\ndef main(reactor):\n\n d = Deferred()\n\n reactor.callLater(1, d.callback, \"the result\")\n print(\"scheduled callback\")\n result = yield d\n print(\"done: {}\".format(result))\n\n\nif __name__ == '__main__':\n react(main)\n\n## show-output\n","sub_path":"code-slides/40-twisted-inlinecallbacks.py","file_name":"40-twisted-inlinecallbacks.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"279357937","text":"import dataclasses\nimport abc\nimport typing as typ\nimport numpy as np\nimport astropy.units as u\n\nfrom . import Aperture, decenterable\n\n__all__ = ['Spider']\n\n\n@dataclasses.dataclass\nclass Spider(decenterable.Decenterable, Aperture):\n\n arm_half_width: u.Quantity = 0 * u.mm\n num_arms: int = 2\n radius: u.Quantity = 0 * u.mm\n\n @property\n def config_broadcast(self):\n return np.broadcast(\n super().config_broadcast,\n self.arm_half_width,\n self.num_arms,\n )\n\n @property\n def wire(self) -> u.Quantity:\n a = np.linspace(0 * u.deg, 360 * u.deg, self.num_arms, endpoint=False)\n a = np.expand_dims(a, ~0)\n\n x = u.Quantity([0 * u.m, self.radius, self.radius, 0 * u.m])\n y = u.Quantity([-self.arm_half_width, -self.arm_half_width, self.arm_half_width, self.arm_half_width])\n\n xp = x * np.cos(a) - y * np.sin(a)\n yp = x * np.sin(a) + y * np.cos(a)\n\n pts = u.Quantity([xp, yp])\n pts = np.moveaxis(pts, 0, ~0)\n return pts\n","sub_path":"kgpy/optics/aperture/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"115029802","text":"import logging\nimport re\nfrom datetime import datetime, timedelta, timezone\nfrom pathlib import Path\nfrom typing import Dict, Tuple, List, Any\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom pandas._testing import assert_dict_equal, assert_frame_equal\n\nimport tfs\nfrom generic_parser import EntryPoint\nfrom generic_parser.dict_parser import ArgumentError\nfrom omc3 import knob_extractor\nfrom omc3.knob_extractor import (KNOB_CATEGORIES, _add_time_delta,\n _extract_and_gather, _parse_knobs_defintions,\n _parse_time, _write_knobsfile, lsa2name, main,\n get_params, Col, get_madx_command, Head,\n check_for_undefined_knobs, load_knobs_definitions, STATE_VARIABLES\n )\nfrom tests.conftest import cli_args\n\nINPUTS = Path(__file__).parent.parent / \"inputs\" / \"knob_extractor\"\n\n\nclass TestFullRun:\n @pytest.mark.basic\n @pytest.mark.parametrize(\"commandline\", [True, False], ids=[\"as function\", \"cli\"])\n def test_full(self, tmp_path, knob_definitions, monkeypatch, commandline):\n kobs_defs = _parse_knobs_defintions(knob_definitions)\n all_variables = [knob for category in KNOB_CATEGORIES.values() for knob in category]\n for knob in all_variables:\n value = np.random.random() * 10 - 5\n threshold = np.random.random() < 0.3\n kobs_defs.loc[knob, Col.value] = 0.0 if threshold else value\n\n start_time = datetime.now().timestamp()\n path = tmp_path / \"knobs.txt\"\n\n # Mock Pytimber ---\n class MyLDB:\n def __init__(self, *args, **kwargs):\n pass\n\n @staticmethod\n def get(key, time):\n now_time = datetime.now().timestamp()\n assert start_time <= time <= now_time\n name = \":\".join(key.split(\":\")[1:-1])\n return {key: [[739173129, 42398328], [-1, kobs_defs.loc[name, Col.value]]]}\n\n class MockTimber:\n LoggingDB = MyLDB\n\n monkeypatch.setattr(knob_extractor, \"pytimber\", MockTimber())\n\n # Main ---\n if commandline:\n with cli_args(\"--time\", \"now\",\n \"--output\", str(path),\n \"--knob_definitions\", str(knob_definitions),\n script=\"knob_extract.py\"):\n main()\n\n # Asserts ---\n parsed_output, _ = parse_output_file(path)\n assert len(all_variables) == len(parsed_output)\n for knob in all_variables:\n knob_entry = kobs_defs.loc[knob, :]\n assert parsed_output[knob_entry[Col.madx]] == knob_entry[Col.value] * knob_entry[Col.scaling]\n\n else:\n knobs_extracted = main(time=\"now\", output=path, knob_definitions=knob_definitions)\n\n # Asserts ---\n parsed_output, _ = parse_output_file(path)\n assert len(all_variables) == len(parsed_output)\n assert len(knobs_extracted) == len(parsed_output)\n for knob in all_variables:\n knob_entry = kobs_defs.loc[knob, :]\n assert knob_entry[Col.value] == knobs_extracted.loc[knob, Col.value]\n assert parsed_output[knob_entry[Col.madx]] == knob_entry[Col.value] * knob_entry[Col.scaling]\n\n @pytest.mark.basic\n @pytest.mark.parametrize(\"commandline\", [True, False], ids=[\"as function\", \"cli\"])\n def test_state(self, tmp_path, monkeypatch, caplog, commandline):\n returns = {v: np.random.random() for v in STATE_VARIABLES.keys()}\n\n # Mock Pytimber ---\n class MyLDB:\n def __init__(self, *args, **kwargs):\n pass\n \n @staticmethod\n def get(key, time):\n intro = \"LhcStateTracker:State:\"\n if key.startswith(intro):\n return {key: ([time], [returns[key[len(intro):]]])}\n else:\n raise ValueError(\"This test failed, probably because the StateKey changed. Update Test.\")\n\n class MockTimber:\n LoggingDB = MyLDB\n\n monkeypatch.setattr(knob_extractor, \"pytimber\", MockTimber())\n\n time = datetime.now()\n # Main ---\n with caplog.at_level(logging.INFO):\n if commandline:\n with cli_args(\"--time\", str(time), \"--state\",\n script=\"knob_extract.py\"):\n main()\n\n else:\n path = tmp_path / \"knobs.txt\"\n state_extracted = main(\n time=str(time), state=True,\n output=path, knobs=[\"fsf\"] # these should not matter, but if state is false\n )\n assert not path.is_file()\n assert len(state_extracted)\n for name in state_extracted.index:\n value = state_extracted.loc[name, Col.value]\n lsa_name = state_extracted.loc[name, Col.lsa]\n assert value == returns[lsa_name]\n assert len(re.findall(fr\"{name}:\\s*{str(value)}\", caplog.text)) == 1\n\n @pytest.mark.basic\n def test_knob_not_defined_run(self, knob_definitions, monkeypatch):\n # Mock Pytimber ---\n class MyLDB:\n def __init__(self, *args, **kwargs):\n pass\n\n @staticmethod\n def get(key, time):\n raise ArgumentError(\"Got past the KnobCheck!\")\n # return {key: [[478973], [343.343]]}\n\n class MockTimber:\n LoggingDB = MyLDB\n\n monkeypatch.setattr(knob_extractor, \"pytimber\", MockTimber())\n knob_definitions_df = load_knobs_definitions(knob_definitions)\n\n # run ------------------------------------------------------------------\n knobs_undefined = [\"non_existent_knob\", \"other_knob\"]\n knobs_defined = knob_definitions_df.index.tolist()\n\n # undefined only ---\n with pytest.raises(KeyError) as e:\n main(knob_definitions=knob_definitions, knobs=knobs_undefined)\n\n for knob in knobs_undefined:\n assert knob in str(e)\n\n # defined only ---\n with pytest.raises(ArgumentError) as e:\n main(knob_definitions=knob_definitions, knobs=knobs_defined)\n assert \"KnobCheck\" in str(e) # see mock Pytimber above\n\n # both ---\n with pytest.raises(KeyError) as e:\n main(knob_definitions=knob_definitions, knobs=knobs_undefined+knobs_defined)\n\n for knob in knobs_undefined:\n assert knob in str(e)\n\n\nclass TestKnobExtraction:\n @pytest.mark.basic\n def test_extraction(self):\n knobs_dict = pd.DataFrame({\n \"LHCBEAM1:LANDAU_DAMPING\": knob_def(madx=\"landau1\", lsa=\"LHCBEAM1/LANDAU_DAMPING\", scaling=-1),\n \"LHCBEAM2:LANDAU_DAMPING\": knob_def(madx=\"landau2\", lsa=\"LHCBEAM1/LANDAU_DAMPING\", scaling=-1),\n \"other\": knob_def(madx=\"other_knob\", lsa=\"other/knob\", scaling=1),\n }).transpose()\n values = [8904238, 34.323904, 3489.23409]\n time = datetime.now()\n timestamp = time.timestamp()*1e9 # java format\n\n fake_ldb = {\n f\"LhcStateTracker:{key}:target\": {f\"LhcStateTracker:{key}:target\": [[timestamp, timestamp], [-1, value]]}\n for key, value in zip(knobs_dict.index, values)\n }\n\n extracted = _extract_and_gather(fake_ldb, knobs_definitions=knobs_dict, knob_categories=[\"mo\", \"other\"], time=time)\n\n assert len(extracted) == len(knobs_dict)\n for idx, (key, entry) in enumerate(extracted.iterrows()):\n assert entry[Col.value] == values[idx] # depends on the order of \"mo\" in the file\n\n\nclass TestIO:\n @pytest.mark.basic\n def test_parse_knobdefs_from_file(self, knob_definitions):\n knob_defs = _parse_knobs_defintions(knob_definitions)\n for knobs in KNOB_CATEGORIES.values():\n for knob in knobs:\n assert knob in knob_defs.index\n knob_entry = knob_defs.loc[knob, :].copy()\n\n assert abs(knob_entry[Col.scaling]) == 1\n assert lsa2name(knob_entry[Col.lsa]) == knob\n assert len(knob_entry[Col.madx])\n\n with pytest.raises(KeyError) as e:\n get_madx_command(knob_entry)\n assert \"Value entry not found\" in str(e)\n\n knob_entry[Col.value] = pd.NA\n madx_command = get_madx_command(knob_entry)\n assert knob_entry[Col.madx] in madx_command\n assert madx_command.strip().startswith(\"!\")\n\n knob_entry[Col.value] = 10\n madx_command = get_madx_command(knob_entry)\n assert str(10) in madx_command\n\n @pytest.mark.basic\n def test_parse_knobdict_from_dataframe(self, tmp_path):\n df = pd.DataFrame(data=[[\"madx_name\", \"lsa_name\", 1., \"something\"]], columns=[\"madx\", \"lsa\", \"scaling\", \"other\"])\n\n path = tmp_path / \"knob_defs.tfs\"\n tfs.write(path, df)\n\n knob_defs = _parse_knobs_defintions(path)\n assert len(knob_defs) == 1\n assert \"lsa_name\" in knob_defs.index\n knob_entry = knob_defs.loc[\"lsa_name\", :]\n assert knob_entry[Col.lsa] == \"lsa_name\"\n assert knob_entry[Col.madx] == \"madx_name\"\n assert knob_entry[Col.scaling] == 1\n\n @pytest.mark.basic\n def test_write_file(self, tmp_path):\n knobs_defs = pd.DataFrame({\n \"LHCBEAM1:LANDAU_DAMPING\": knob_def(madx=\"moknob1\", lsa=\"moknob1.lsa\", scaling=-1, value=-4783),\n \"LHCBEAM2:LANDAU_DAMPING\": knob_def(madx=\"moknob2\", lsa=\"moknob2.lsa\", scaling=1, value=0.0), # one should be 0.0 to test this case\n \"knob1\": knob_def(madx=\"knob1.madx\", lsa=\"knob1.lsa\", scaling=-1, value=12.43383),\n \"knob2\": knob_def(madx=\"knob2.madx\", lsa=\"knob2.lsa\", scaling=1, value=-3.0231),\n \"knob3\": knob_def(madx=\"knob3.madx\", lsa=\"knob3.lsa\", scaling=-1, value=-9.7492),\n }).transpose()\n path = tmp_path / \"knobs.txt\"\n time = datetime.now()\n knobs_defs = tfs.TfsDataFrame(knobs_defs, headers={Head.time: time})\n _write_knobsfile(path, knobs_defs)\n read_as_dict, full_text = parse_output_file(path)\n assert str(time) in full_text\n assert \" mo \" in full_text\n assert \" Other Knobs \" in full_text\n assert len(read_as_dict) == len(knobs_defs)\n for _, entry in knobs_defs.iterrows():\n assert read_as_dict[entry.madx] == entry[Col.value] * entry[Col.scaling]\n\n @pytest.mark.basic\n def test_knob_not_defined(self, knob_definitions, monkeypatch):\n knob_definitions_df = load_knobs_definitions(knob_definitions)\n\n # run ------------------------------------------------------------------\n knobs_undefined = [\"this_knob_does_not_exist\", \"Knobby_McKnobface\"]\n knobs_defined = knob_definitions_df.index.tolist()\n knob_categories = list(KNOB_CATEGORIES.keys())\n\n # undefined only ---\n with pytest.raises(KeyError) as e:\n check_for_undefined_knobs(knob_definitions_df, knobs_undefined)\n\n for knob in knobs_undefined:\n assert knob in str(e)\n\n # defined only ---\n check_for_undefined_knobs(knob_definitions_df, knobs_defined)\n check_for_undefined_knobs(knob_definitions_df, knob_categories)\n check_for_undefined_knobs(knob_definitions_df, knobs_defined + knob_categories)\n\n # all ---\n with pytest.raises(KeyError) as e:\n check_for_undefined_knobs(knob_definitions_df,\n knob_categories + knobs_undefined + knobs_defined)\n\n for knob in knobs_undefined:\n assert knob in str(e)\n\n @pytest.mark.basic\n def test_load_knobdefinitions_with_any_number_entries(self, tmp_path):\n definition_file = tmp_path / \"knob_defs_tmp.txt\"\n values = [18.8, 12.0, 10, 108.8]\n definition_file.write_text(\n f\"knob1_madx, knob1/lsa, {values[0]}, 19.8, 38\\n\"\n f\"knob2_madx, knob2/lsa, {values[1]}, 483.8\\n\"\n f\"knob3_madx, knob3/lsa, {values[2]}\\n\"\n f\"knob4_madx, knob4/lsa, {values[3]}, 19.8, other stuff\\n\"\n )\n\n df = load_knobs_definitions(definition_file)\n assert len(df) == len(values)\n\n for idx, value in enumerate(values, start=1):\n name = f\"knob{idx}:lsa\"\n assert name in df.index\n assert df.loc[name, Col.scaling] == value\n assert df.loc[name, Col.madx] == f\"knob{idx}_madx\"\n assert df.loc[name, Col.lsa] == f\"knob{idx}/lsa\"\n\n @pytest.mark.basic\n def test_load_knobdefinitions_fail_no_scaling(self, tmp_path):\n definition_file = tmp_path / \"knob_defs_tmp.txt\"\n definition_file.write_text(\n f\"knob1_madx, knob1/lsa\\n\"\n f\"knob2_madx, knob2/lsa\\n\"\n )\n\n with pytest.raises(pd.errors.ParserError) as e:\n load_knobs_definitions(definition_file)\n assert \"expected 3 and found 2\" in str(e)\n\n @pytest.mark.basic\n def test_load_knobdefinitions_fail_wrong_scaling(self, tmp_path):\n definition_file = tmp_path / \"knob_defs_tmp.txt\"\n definition_file.write_text(\n f\"knob1_madx, knob1/lsa, wrong\\n\"\n )\n\n # with pytest.raises(pd.errors.ParserError):\n with pytest.raises(ValueError) as e:\n load_knobs_definitions(definition_file)\n assert \"could not convert string to float\" in str(e)\n\n\nclass TestTime:\n @pytest.mark.basic\n def test_time_and_delta(self):\n time_str = \"2022-06-26T03:00\"\n t1 = _parse_time(time_str)\n\n assert t1 == datetime(2022, 6, 26, 3, 0, 0)\n\n # 2 hours earlier\n t2 = _add_time_delta(t1, \"_2h\")\n assert t2 == datetime(2022, 6, 26, 1, 0, 0)\n\n # 1 week earlier\n t2 = _add_time_delta(t1, \"_1w\")\n assert t2 == datetime(2022, 6, 19, 3, 0, 0)\n\n # 1 week and 1 hour earlier\n t2 = _add_time_delta(t1, \"_1w1h\")\n assert t2 == datetime(2022, 6, 19, 2, 0, 0)\n\n # 1 month later\n t2 = _add_time_delta(t1, \"1M\")\n assert t2 == datetime(2022, 7, 26, 3, 0, 0)\n\n # 20 years later\n t2 = _add_time_delta(t1, \"20Y\")\n assert t2 == datetime(2042, 6, 26, 3, 0, 0)\n\n t3 = _parse_time(time_str, \"20Y\")\n assert t2 == t3\n\n @pytest.mark.basic\n def test_timezones(self):\n assert (\n _parse_time(\"2022-06-26T03:00+02:00\")\n ==\n datetime(2022, 6, 26, 3, 0, 0, tzinfo=timezone(timedelta(seconds=7200)))\n )\n\n\nclass TestParser:\n @pytest.mark.basic\n def test_defaults(self, main_entrypoint):\n opt = main_entrypoint.parse([])\n assert isinstance(opt.knobs, list)\n assert opt.time == \"now\"\n assert opt.timedelta is None\n assert opt.state is False\n assert opt.knob_definitions is None\n\n @pytest.mark.basic\n def test_cli_parsing(self, main_entrypoint):\n my_opts = dict(\n knobs=[\"knob1\", \"knob2\", \"knob3\"],\n time=\"2022-06-23T12:53:01\",\n timedelta=\"_27y\",\n output=\"help.txt\",\n knob_definitions=\"knob_def.txt\",\n )\n my_types = dict(\n knobs=list,\n time=str,\n timedelta=str,\n output=Path,\n knob_definitions=Path,\n )\n\n # run main\n with cli_args(*dict2args(my_opts)):\n opt = main_entrypoint.parse()\n\n # check all is correct\n assert all(k in opt.keys() for k in my_opts.keys())\n for k in my_opts.keys():\n assert str(my_opts[k]) == str(opt[k])\n assert isinstance(opt[k], my_types[k])\n\n @pytest.mark.basic\n def test_time_fail(self, main_entrypoint):\n # we should allow this somewhen in the future\n with pytest.raises(ArgumentError) as e:\n main_entrypoint.parse(time=datetime.now())\n assert \"time\" in str(e)\n\n @pytest.mark.basic\n def test_timedelta_fail(self, main_entrypoint):\n with pytest.raises(ArgumentError) as e:\n main_entrypoint.parse(timedelta=-2)\n assert \"timedelta\" in str(e)\n\n @pytest.mark.basic\n def test_knobs_fail(self, main_entrypoint):\n with pytest.raises(ArgumentError) as e:\n main_entrypoint.parse(knobs=\"knob1, knob2, knob3\")\n assert \"knobs\" in str(e)\n\n\n# CERN Tests -------------------------------------------------------------------\n\nclass TestInsideCERNNetwork:\n @pytest.mark.cern_network\n def test_extractor_in_cern_network(self, tmp_path, knob_definitions, saved_knobfile_and_time):\n path_saved, time_saved = saved_knobfile_and_time\n path = tmp_path / \"knobs.txt\"\n main(time=time_saved, output=path, knob_definitions=knob_definitions)\n\n parsed_output, _ = parse_output_file(path)\n parsed_saved, _ = parse_output_file(path_saved)\n\n assert len(parsed_saved) == len(parsed_output)\n for key in parsed_output.keys():\n assert parsed_output[key] == parsed_saved[key]\n\n @pytest.mark.cern_network\n def test_state_in_cern_network(self, state_tfs):\n # get recorded data\n old_df = tfs.read_tfs(state_tfs, index=\"NAME\")\n time = old_df.headers[Head.time]\n\n # run main\n state_df = main(time=time, state=True)\n\n # format a bit to make frames equal\n state_df = state_df.applymap(str)\n state_df.headers[Head.time] = str(state_df.headers[Head.time])\n state_df.index.name = \"NAME\"\n\n # check frames\n assert_dict_equal(state_df.headers, old_df.headers)\n assert_frame_equal(state_df, old_df)\n\n\n# Helper -----------------------------------------------------------------------\n\n\ndef knob_def(**kwargs):\n return pd.Series(dict(**kwargs))\n\n\ndef parse_output_file(file_path) -> Tuple[Dict[str, float], str]:\n txt = Path(file_path).read_text()\n d = {}\n pattern = re.compile(r\"\\s*(\\S+)\\s*:=\\s*([^;\\s*]+)\\s*;\")\n for line in txt.splitlines():\n line = line.strip()\n if not line or line.startswith(\"!\"):\n continue\n\n match = pattern.match(line)\n d[match.group(1)] = float(match.group(2))\n return d, txt\n\n\ndef dict2args(args_dict: Dict[str, Any]) -> List[str]:\n \"\"\" Convert a dictionary to an args-list.\n Keys are flags, values are their arguments. \"\"\"\n args = []\n for k, v in args_dict.items():\n args.append(f\"--{k}\")\n if isinstance(v, list):\n args += [str(item) for item in v]\n else:\n args.append(str(v))\n return args\n\n\n@pytest.fixture()\ndef knob_definitions() -> Path:\n return INPUTS / \"knob_definitions.txt\"\n\n\n@pytest.fixture()\ndef state_tfs() -> Path:\n return INPUTS / \"state_2022-06-25.tfs\"\n\n\n@pytest.fixture()\ndef saved_knobfile_and_time() -> Tuple[Path, str]:\n return INPUTS / \"knobs_2022-06-25.txt\", \"2022-06-25T00:20:00+00:00\"\n\n\n@pytest.fixture()\ndef main_entrypoint() -> EntryPoint:\n return EntryPoint(get_params(), strict=True)\n","sub_path":"tests/unit/test_knob_extractor.py","file_name":"test_knob_extractor.py","file_ext":"py","file_size_in_byte":19164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"388870114","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n# Copyright (C) 2008-2009 Ferraro Luciano (aka lux) \n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport wx\nimport wx.py\nimport wx.py.crust\nimport wx.html\ntry:\n from wx.lib.agw.buttonpanel import ButtonInfo\nexcept:\n try:\n from wx.lib.buttonpanel import ButtonInfo\n except:\n raise \"Update wxPython library to 2.8.9.2 or major\"\n\nimport os\nimport sys\nimport random\n\nimport utils\n\nclass HelpDialog (wx.Dialog):\n def __init__(self, parent, size, *args, **kwargs):\n wx.Dialog.__init__(self, parent, wx.NewId(), _(\"Help\"), size=size, *args, **kwargs)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n html = wx.html.HtmlWindow(self)\n if \"gtk2\" in wx.PlatformInfo:\n html.SetStandardFonts()\n if __language__ == \"ita\":\n html.LoadFile(gdir(\"help_ita.html\"))\n else:\n html.LoadFile(gdir(\"help.html\"))\n sizer.Add(html, 1, wx.EXPAND)\n self.SetSizer(sizer)\n\nclass MyButtonBox:\n def __init__ (self, parent, panel, *args, **kwargs):\n self.parent, self.panel = parent, panel\n \n def LoadItems (self, Items, BitmapSize):\n BitmapSizeName = \"x\".join(map(lambda x:str(x),BitmapSize))\n \n button = ButtonInfo(self.panel, wx.NewId(), text=_(\"Read on MangaEden.com !!!\"))\n self.panel.AddButton(button)\n self.parent.Bind(wx.EVT_BUTTON, utils.openMangaEden, button)\n self.panel.AddSeparator()\n \n for item in Items:\n if item == \"\":\n self.panel.AddSeparator()\n continue\n if len(item) == 3:\n style = wx.ALL|wx.CENTER|item[2]\n else:\n style = wx.ALL|wx.CENTER\n id = wx.NewId()\n \n bitmap = wx.Image(os.path.join(curdir, \"pixmaps\", BitmapSizeName, \n item[0].lower()+\".png\"), wx.BITMAP_TYPE_PNG).ConvertToBitmap()\n button = ButtonInfo(self.panel, id, bmp=bitmap)\n setattr(self, item[0], button)\n self.panel.AddButton(button)\n \n callback = getattr(self.parent, \"On\"+item[0].replace(\" \", \"\"))\n self.parent.Bind(wx.EVT_BUTTON, callback, button)\n\nclass MyMetaPopUp (object):\n def __init__(self, model, parent, zoom, CallBack, *args, **kwargs):\n self.model = model\n self.view = MyPopUp(model, parent, CallBack, *args, **kwargs)\n self.interactor = Interactor(self.model, self.view, self)\n self.view.setup(zoom)\n self.isListening = True\n \nclass Interactor (object):\n def __init__(self, model, view, presenter):\n self.model = model\n self.view = view\n self.presenter = presenter\n \n def install(self):\n pass\n \nclass MyPopUp (wx.PopupWindow):\n def __init__ (self, model, parent, CallBack, *args, **kwargs):\n wx.PopupWindow.__init__(self,parent, *args, **kwargs)\n self.CallBack = CallBack\n \n self.parent = parent\n self.model = model\n \n self.Bind(wx.EVT_CLOSE, self.OnClose)\n \n def OnClose (self, event):\n self.Hide()\n self.CallBack(self.slider.GetValue())\n def OnDone (self, event):\n self.Close()\n \n def setup (self, zoom):\n self.slider = wx.Slider(self, \n style=wx.SL_VERTICAL, \n size=(27, 120))\n self.slider.SetRange(10, 250)\n self.slider.SetValue(zoom)\n self.slider.SetTickFreq(50)\n self.slider.Bind(wx.EVT_SCROLL_CHANGED, self.OnDone)\n \n sizer = wx.BoxSizer(wx.VERTICAL)\n sizer.Add(self.slider, 1, wx.EXPAND)\n self.SetSizer(sizer)\n self.SetSize(self.slider.GetSize())\n self.SetAutoLayout(True)\n self.Layout()\n \ndef CreateMyComboBox (self, choices, values, orientation=0):\n panel = wx.Panel(self)\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n cb_ctrls = {}\n ctrl = None\n for id, choice in enumerate(choices):\n old_ctrl = ctrl\n cid = wx.NewId()\n ctrl = MyComboBox(self, panel, cid, id, \n ctrl, values[choice][0],\n wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER, choice,\n orientation=orientation)\n if old_ctrl:\n old_ctrl.nextctrl = ctrl\n cb_ctrls[choice] = ctrl\n # -- #\n ctrl.Connect(cid, -1, wx.wxEVT_COMMAND_COMBOBOX_SELECTED, \n getattr(self, \"OnComboBox_\"+choice))\n # -- #\n hbox.Add(ctrl, 1, wx.EXPAND)\n ctrl.nextctrl = cb_ctrls[\"manga\"]\n panel.SetSizer(hbox)\n return cb_ctrls, panel\nclass MyComboBox (wx.ComboBox):\n wentback = False\n LatestValue = \"\"\n typing = False\n def __init__ (self, childframe, parent, cid, id, prectrl, choices=None, \\\n style=None, name=None, orientation=0, *args, **kwargs):\n self.childframe, self.cid, self.id = childframe, cid, id\n self.orientation, self.prectrl = orientation, prectrl\n if not style:\n wx.ComboBox.__init__(self, parent, cid, choices=choices,\n name=name, *args, **kwargs)\n else:\n wx.ComboBox.__init__(self, parent, cid, choices=choices, \n style=style, name=name, *args, **kwargs)\n self.Bind(wx.EVT_TEXT, self.OnText)\n self.Bind(wx.EVT_TEXT_ENTER, self.OnTextEnter)\n self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)\n \n def OnText (self, event):\n if not self.Value:return\n pos = len(self.Value)\n if pos <= len(self.LatestValue):\n self.LatestValue = self.Value\n event.Skip()\n return\n self.LatestValue = self.Value\n if not self.typing:\n return\n for string in self.Strings:\n if string.lower().startswith(self.Value.lower()):\n wx.CallAfter(self.SetValue, string)\n wx.CallAfter(self.SetInsertionPoint, pos)\n wx.CallAfter(self.SetFocus)\n wx.CallAfter(self.SetMark, pos, len(string))\n event.Skip()\n return\n self.typing = False\n event.Skip()\n def OnTextEnter (self, event):\n self.SelectString(self.Value)\n event.Skip()\n def OnKeyDown (self, event):\n keycode = event.GetKeyCode()\n if keycode == wx.WXK_TAB:\n if self.nextctrl:\n self.nextctrl.SetFocus()\n self.typing = True\n event.Skip()\n \n def SelectString (self, Value):\n if Value not in self.Strings:\n wx.MessageBox(_(\"%s: doesn't exists\") % Value)\n return\n selection = self.Strings.index(Value)\n self.Select(selection)\n event = wx.CommandEvent(\n wx.wxEVT_COMMAND_COMBOBOX_SELECTED, self.GetId())\n event.SetEventObject(self)\n event.SetInt(selection)\n event.SetString(Value)\n event.SetClientData(self)\n event.SetClientObject(self)\n wx.PostEvent(self, event)\n def Forward (self):\n current_selection = self.GetSelection()#self.Strings.index(self.Value)\n \n if (current_selection == self.GetCount()-1) and (self.prectrl):\n if self.orientation:\n self.prectrl.Forward()\n else:\n self.prectrl.Previous()\n return\n selection = current_selection + 1\n \n self.SelectString(self.Strings[selection])\n def Previous (self):\n current_selection = self.GetSelection()#self.Strings.index(self.Value)\n \n if (current_selection == 0) and (self.prectrl):\n self.wentback = True\n if self.prectrl:\n if self.orientation:\n self.prectrl.Previous()\n else:\n self.prectrl.Forward()\n return\n selection = current_selection - 1\n \n self.SelectString(self.Strings[selection])\n \nclass DebuggingWindow (wx.Frame):\n def __init__ (self, workspace):\n wx.Frame.__init__(self, None, -1, _(\"Debugging Window\"), \n wx.DefaultPosition, size=(800,600))\n \n self.crust = wx.py.crust.Crust(self, locals=workspace)\n self.Show()\n \nclass GeneralDialog (wx.Dialog):\n def __init__ (self, parent, title, message, buttons, *args, **kwargs):\n wx.Dialog.__init__(self, parent, title=title, *args, **kwargs)\n \n sizer = wx.BoxSizer(wx.VERTICAL)\n msg_ctrl = wx.StaticText(self, label=message)\n sizer.Add(msg_ctrl, 1, wx.ALIGN_CENTER)\n for button in buttons:\n wxbutton = wx.Button(self, -1, button[0])\n wxbutton.Bind(wx.EVT_BUTTON, button[1])\n sizer.Add(wxbutton, 0, wx.ALIGN_CENTER_HORIZONTAL)\n \n self.SetSizer(sizer)\n \n def run (self):\n self.ShowModal()\n\nclass AdviserDialog (wx.Dialog):\n def __init__ (self, parent, manga, new_chapters, new_chapters_count, \n latest_chapter, old_latest_chapter, callback, *args, **kwargs):\n title = \"Adviser: %s\" % manga\n wx.Dialog.__init__(self, parent, title=title, *args, **kwargs)\n \n message = \"%s has been updated.\\n%s new chapters.\" % (manga, new_chapters_count)\n sizer = wx.BoxSizer(wx.VERTICAL)\n msg_ctrl = wx.StaticText(self, label=message)\n sizer.Add(msg_ctrl, 0)\n \n self.make_list(new_chapters)\n sizer.Add(self.list, 1, wx.EXPAND)\n \n buttons = (\n (_(\"Load\"), self.OnLoad),\n (_(\"Cancel\"), lambda e: self.Destroy())\n )\n for button in buttons:\n wxbutton = wx.Button(self, -1, button[0])\n wxbutton.Bind(wx.EVT_BUTTON, button[1])\n sizer.Add(wxbutton, 0, wx.ALIGN_CENTER_HORIZONTAL)\n \n self.SetSizer(sizer)\n \n self.callback = lambda index: callback(new_chapters[index])\n\n def OnLoad (self, event):\n selected = self.list.GetFirstSelected()\n if selected != -1:\n self.callback(selected)\n self.Destroy()\n \n def make_list (self, chapters):\n self.list = wx.ListCtrl(\n self, -1, style=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES)\n \n self.list.InsertColumn(0, _(\"Chapter\"))\n for count, item in enumerate(chapters):\n index = self.list.InsertStringItem(sys.maxint, item)\n self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)\n \n self.list.Select(0)","sub_path":"gmangas/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":11216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"271606347","text":"\"\"\"\r\nProblem:\r\nGiven a set of vertical lines of various heights that represent the walls of a rectangular return the maximum water that can be contained. \r\n\r\nAlgorithm: \r\nKey to solving this problem is understanding the problem right. Look at the example below \r\n | \r\n 5 | | 4\r\n | |\r\n | |\r\n 1 | | | | 1\r\n-----------------------------\r\n 0 1 2 3\r\n\r\nWhat we have above is four vertical lines of height 1, 5, 4, and 1. The maximum water that can be contained is between lines of height 5 and 4, since we can hold 4 * 1 amount of water between those two lines. On the other hand any other combination of lines can only hold 3 or less amount of water. For example, between line at index 0 of height 1 and line at index 3 of height 1 we can hold (3 - 0) * 1 of water. Similarly, amount of water between line at 2 (height 4) and line a 0 (height 1) is two. Meaning the amount of water than can be held between two lines is equal to distance between the two lines multiplied by height of the shorter line. \r\n\r\nSolution: \r\nArmed with this knowledge we can solve this problem. We start by picking the two lines at the end and work our way in. At every step we calculate the amount of water that can be held between those two lines (distance * min(line1, line2)). Update maximum if that value is greater than previous maximum. Next we decrement right side index if left line is taller and increment left side index otherwise. We continue doing this until indexes are equal \r\n\r\nTime Complexity: O(n) \r\nSpace Complexity: O(1) \r\n\r\nVARIATION: Also return indexes, height of those two lines \r\n\"\"\"\r\n\r\nprint(__doc__)\r\n\r\nclass SolutionWaterContainer(object):\r\n def maxArea(self, height): \r\n \"\"\"\r\n :type height: List[int]\r\n :rtype: int\r\n \"\"\"\r\n # Intialize starting points, max_water \r\n i, j, max_water = 0, len(height) - 1, 0\r\n \r\n # Loop till i and j are not equal \r\n while i < j:\r\n # distance between two lines \r\n width = j - i \r\n # update max_water if current water amount exceeds previously \r\n # calculated max_water \r\n max_water = max(max_water, width * min(height[i], height[j]))\r\n \r\n # Decrement right side index if left line is taller \r\n if height[i] > height[j]:\r\n j -= 1\r\n # Increment left side index otherwise \r\n else:\r\n i += 1\r\n \r\n # return result \r\n return max_water\r\n\r\nif __name__ == '__main__':\r\n print(\"Input:\")\r\n lines = [1, 2, 5, 3, 2, 8, 9]\r\n print(\"Lines: {}\".format(lines))\r\n s = SolutionWaterContainer()\r\n print(\"Answer: Max Water = {}\".format(s.maxArea(lines))) ","sub_path":"arrays/containerwithmostwater.py","file_name":"containerwithmostwater.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"196957208","text":"\nimport sys\n\n'''\nPRELABORATORIO Nº 5\n\nPrelab5ejercicio1.py\n\n\n\nDESCRIPCION: Implementacion de un Algoritmo en Python para calcular \\\n\tel monto total semanal de los jornadas diarias laboradas por los\\\n\templeados de una fabrica utilizando las funciones de try/ except\n\t\n\n\nAutores: \n\n\t12-11499 - Chaparro Orlando\n\t13-10299 - Colina Cesar\n\n Ultima modificacion: 17/10/2016'''\n\n\"\"\" VARIABLES: \n\n#\ttrabajador: int // Valor que el sistema pide para identificar el tipo de empleado\n\n#\tGERENTE: str // Palabra que denota si el empleado es un gerente de planta\n\n#\tSUPERVISOR: str // Palabra que denota si el empleado es un supervisor\n\n#\tTRABAJADOR: str // Palabra que denota si el empleado es un trabajador\n\n#\tTurnoG: int // Numero de horas trabajadas por el gerente\n\n#\tTurnoM: int // Numero de horas trabajadas en el turno matutino\n\n#\tTurnoV: int // Numero de horas trabajadas en el turno vespertino\n\n#\tTurnoN: int // Numero de horas trabajadas en el turno nocturno\n\n#\tTurnoMdelFDS: int // Numero de horas trabajadas en el fin de semana en horario matutino\n\n#\tTurnoVdelFDS: int // Numero de horas trabajadas en el fin de semana en horario vespertino\n\n#\tTurnoNdelFDS: int // Numero de horas trabajadas en el fin de semana en horario nocturno\n\t\n\n#\tGANANCIA: int // Pago que recibira el trabajador\n\n#\tBONO: float // Ganancia por trabajar en horario nocturno o fin de semana\n\n#\tPagoFDS: int // Pago que recibira el trabajador por trabajar un fin de semana\n\n# Fin: str // Indica si el trabajador laboro el fin de semana\n\n\"\"\"\n\n\n# VALORES INICIALES:\n\n\nBONO = 0\n\nTurnoG, TurnoM, TurnoV, TurnoN, TurnoMdelFDS, TurnoVdelFDS, TurnoNdelFDS = 0, 0, 0, 0, 0, 0, 0\n\n\n#VERIFICACION DE LA PRECONDICION:\n\nwhile True:\n\ttry:\n\t\ttrabajador = int(input(\"Indique con el numero especificado si el empleado es GERENTE (1) si es SUPERVISOR (2) o si es TRABAJADOR (3): \"))\n\t\t# PRECONDICION:\n\t\tassert(trabajador > 0 and trabajador < 4 and TurnoG >= 0 and TurnoM >= 0 and TurnoV >= 0 and TurnoN >= 0 and TurnoMdelFDS >= 0 and TurnoVdelFDS >= 0 and TurnoNdelFDS >= 0 ) \n\t\tbreak\n\texcept:\n\t\tprint(\"Ha introducido un valor NO valido al sistema.\")\n\t\tprint(\"Recuerde que para seleccionar el tipo de trabajador, debe ingresar un numero del 1 al 3\")\n\n# CALCULOS:\n\nif trabajador == 1:\t\t\t\t\t\t\t\t#EL SISTEMA PIDE QUE SE ESPECIFIQUE MEDIANTE UN NUMERO EL TIPO DE\n\ttrabajador = str(\"GERENTE\")\t\t\t\t\t#EMPLEADO A CONSIDERAR PARA CALCULAR SU SALARIO SEMANAL\nelif trabajador == 2:\n\ttrabajador = str(\"SUPERVISOR\")\nelif trabajador == 3:\n\ttrabajador = str(\"TRABAJADOR\")\n\t\nif trabajador == \"GERENTE\": \t\t\t\t\t\t\t\t\t\t\t\t\t\t#EL PAGO PARA EL GERENTE ES 950$ SEMANAL MAS 10$ POR CADA\n\tTurnoG = int(input(\"Indique el numero de horas extras trabajadas por el GERENTE: \"))\t#HORA TRABAJADA\n\tGANANCIA = 950 + TurnoG * 10\n\tprint(\"El pago correspondiente al gerente es: \" + str(GANANCIA) + \"$\")\n\nelif trabajador == \"SUPERVISOR\" or trabajador == \"TRABAJADOR\":\n\tTurnoM = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno MATUTINO: \")) #EL SISTEMA PIDE QUE EL USUARIO INGRESE\n\tTurnoV = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno VESPERTINO: \")) #EL NUMERO DE HORAS TRABAJADAS EN CADA\n\tTurnoN = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno NOCTURNO: \")) \t #HORARIO, POSTERIORMENTE SE PIDE QUE SE \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #ESPECIFIQUE SI EL EMPLEADO TRABAJO EL FIN\n\tif trabajador == \"SUPERVISOR\": \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t #DE SEMANA Y CUANTAS HORAS EN CADA HORARIO\n\t\tGANANCIA = (45 * TurnoM) + (50 * TurnoV) + (60 * TurnoN)\n\t\tFin = input(\"¿El \" + str(trabajador) + \" realizo turno laborable el fin de semana: ? (s/n) \")\n\t\tif Fin == \"s\" or Fin == \"S\":\n\t\t\tTurnoMdelFDS = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno MATUTINO del FIN DE SEMANA: \"))\n\t\t\tTurnoVdelFDS = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno VESPERTINO del FIN DE SEMANA: \"))\n\t\t\tTurnoNdelFDS = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno NOCTURNO del FIN DE SEMANA: \"))\n\t\t\tPagoFDS = TurnoMdelFDS * 45 + TurnoNdelFDS * 60 + TurnoVdelFDS * 50\n\t\t\tBONO = 30 * TurnoN * 60 / 100 + 50 * PagoFDS / 100\n\t\t\tprint(\"El pago correspondiente al \" + str(trabajador) + \" es de: \" + str(GANANCIA + PagoFDS) + \"$ + un bono de: \" + str(BONO) + \"$\")\n\t\telif Fin == \"n\" or Fin == \"N\":\n\t\t\tBONO = 30 * TurnoN * 60 / 100\n\t\t\tprint(\"El pago correspondiente al \" + str(trabajador) + \" es de: \" + str(GANANCIA) + \"$ + un bono de: \" + str(BONO) + \"$\")\n\t\t\t\n\telif trabajador == \"TRABAJADOR\":\n\t\tGANANCIA = (25 * TurnoM) + (30 * TurnoV) + (40 * TurnoN) \n\t\tFin = input(\"¿El \" + str(trabajador) + \" realizo turno laborable el fin de semana: ? (s/n) \")\n\t\tif Fin == \"s\" or Fin == \"S\":\n\t\t\tTurnoMdelFDS = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno MATUTINO del FIN DE SEMANA: \"))\n\t\t\tTurnoVdelFDS = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno VESPERTINO del FIN DE SEMANA: \"))\n\t\t\tTurnoNdelFDS = int(input(\"Indique el numero de horas trabajadas por el \" + str(trabajador) + \" en el turno NOCTURNO del FIN DE SEMANA: \"))\n\t\t\tPagoFDS = TurnoMdelFDS * 25 + TurnoNdelFDS * 40 + TurnoVdelFDS * 30\n\t\t\tBONO = 30 * TurnoN * 40 / 100 + 50 * PagoFDS / 100\n\t\t\tprint(\"El pago correspondiente al \" + str(trabajador) + \" es de: \" + str(GANANCIA + PagoFDS) + \"$ + un bono de: \" + str(BONO) + \"$\")\n\t\telif Fin == \"n\" or Fin == \"N\":\n\t\t\tBONO = 30 * TurnoN * 60 / 100\n\t\t\tprint(\"El pago correspondiente al \" + str(trabajador) + \" es de: \" + str(GANANCIA) + \"$ + un bono de: \" + str(BONO) + \"$\")\n\t\t\n\t\n# VERIFICACION DE LA POSTCONDICION:\n\ntry:\n\tassert(GANANCIA > 0 and GANANCIA >= BONO and TurnoG >= 0 and TurnoM >= 0 and TurnoV >= 0 and TurnoN >= 0)\n\t\nexcept:\n\tprint(\"No se cumple la postcondicion con los valores ingresados\")\n\tprint(\"Recuerde que los valores de las horas trabajadas por los empleados\")\n\tprint(\"deben ser numeros enteros positivos\")\n\tsys.exit()\n","sub_path":"PreLaboratorios/Prelab5/PreLab5ejercicio1.py","file_name":"PreLab5ejercicio1.py","file_ext":"py","file_size_in_byte":6069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"328703332","text":"import tkinter as tk\r\n\r\nlist_cal = []\r\nlist_total = []\r\n\r\ndef plusf():\r\n nu1 = float(num_box.get())\r\n list_cal.append(nu1)\r\n\r\n output_label2.configure(text = \"(plus)\")\r\n\r\ndef subf():\r\n nu1 = float(num_box.get())\r\n nu1 = 0 - nu1\r\n list_cal.append(nu1)\r\n\r\n output_label2.configure(text=\"(minus)\")\r\n\r\n\r\ndef multiplyf():\r\n nu1 = float(num_box.get())\r\n nu2 = list_cal[-1]*nu1\r\n list_cal.pop()\r\n list_cal.append(nu2)\r\n\r\n output_label2.configure(text=\"(multiply)\")\r\n \r\ndef dividef():\r\n nu1 = float(num_box.get())\r\n nu2 = list_cal[-1]/nu1\r\n list_cal.pop()\r\n list_cal.append(nu2)\r\n\r\n output_label2.configure(text=\"(divide)\")\r\n\r\ndef Calculate():\r\n result = 0\r\n for i in list_cal:\r\n result += i\r\n\r\n output1 = '' \r\n for i in list_cal:\r\n if i == list_cal[-1]:\r\n output1 += str(i)\r\n else :\r\n output1 += str(i) + '+' \r\n output1 += \" = \" + str(result) \r\n output_label.configure(text=output1)\r\n\r\n list_total.append(result) # เก็บข้อมูลผลลัพท์\r\n output2 = ''\r\n for m in list_total:\r\n output2 += \"result \" + \" : \" + str(m) + \"\\n\"\r\n re_label.configure(text=output2);list_cal.clear()\r\n\r\n\r\ndef plusresultf():\r\n plusresult = 0\r\n for sum in list_total:\r\n plusresult += sum\r\n\r\n output3 = ''\r\n for i in list_total:\r\n if i == list_total[-1]:\r\n output3 += str(i)\r\n else :\r\n output3 += str(i) + '+' \r\n output3 += \" = \" + str(plusresult) \r\n re_label.configure(text=output3)\r\n\r\n\r\n#ลบออก\r\ndef clear():\r\n list_cal.clear()\r\n\r\n output_label.configure(text=\"\")\r\n output_label2.configure(text='')\r\n\r\n#ลบประวัติออกหมด\r\ndef clearall():\r\n list_cal.clear()\r\n list_total.clear()\r\n\r\n output_label.configure(text=\"\")\r\n output_label2.configure(text='')\r\n re_label.configure(text=\"\")\r\n\r\n\r\nwindow = tk.Tk()\r\nwindow.title(\"Calculater\")\r\nwindow.minsize(350,600)\r\n\r\ntitle_label = tk.Label(master=window,text = \"input number\")\r\ntitle_label.pack()\r\n\r\noutput_label = tk.Label(master=window)\r\noutput_label.pack()\r\n\r\nnum_box = tk.Entry(master=window) #กล่องข้อความ # ใช่โปรแกรมป้องกันใส่ str\r\nnum_box.pack()\r\n\r\noutput_label2 = tk.Label(master=window)\r\noutput_label2.pack()\r\n\r\nsum_button = tk.Button(master=window,text=\"+\" , command = plusf,width =7,height = 1)\r\nsum_button.pack(pady=5)\r\n\r\nsub_button = tk.Button(master=window, text='-',command= subf,width =7,height = 1)\r\nsub_button.pack(pady=5)\r\n\r\nmultiply_button = tk.Button(master=window,text=\"x\",command=multiplyf,width =7,height = 1)\r\nmultiply_button.pack(pady=5)\r\n\r\ndivide_button = tk.Button(master=window,text = \"/\",command = dividef,width =7,height = 1)\r\ndivide_button.pack(pady=5)\r\n\r\nsumre_button = tk.Button(master=window,text=\"sum all result\",command=plusresultf)\r\nsumre_button.pack(pady=5)\r\n\r\nC_button = tk.Button(master=window,text=\"C\",command = clear,width =7,height = 1)\r\nC_button.pack(pady=5)\r\n\r\nCE_button = tk.Button(master=window,text=\"CE\",command = clearall,width =7,height = 1)\r\nCE_button.pack(pady=5)\r\n\r\nenter_button = tk.Button(master=window,text=\"Enter\", command = Calculate,width = 15,height = 2)\r\nenter_button.pack(pady=5)\r\n\r\nre_label = tk.Label(master=window)\r\nre_label.pack(pady=5)\r\n\r\nwindow.mainloop()\r\n\r\n#กดแล้วลบข้อมูลในกล่อง\r\n#กรณี input ข้อมูลที่ไม่ใช่ตัวเลข","sub_path":"cal2.py","file_name":"cal2.py","file_ext":"py","file_size_in_byte":3534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"294274078","text":"import timeseries\n\nclass Word:\n '''\n Class to add additional information to a keyword like timeseries of the news and Wikipedia, co-occurrences and the matched Wikipedia site.\n\n '''\n def __init__(self,keyword,ts_wiki=None,ts_articles=None,coocKeywords=[],wikipediaSite=\"\"):\n self.keyword = keyword\n self.ts_wiki = ts_wiki\n self.ts_articles = ts_articles\n self.coocKeywords = coocKeywords\n self.wikipediaSite = wikipediaSite","sub_path":"word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}
+{"seq_id":"628943916","text":"\"\"\"\n1. Write a function to calculate all possible assignment vectors of 2n users,\nwhere n users are assigned to group 0 (control) and n users are assigned to\ngroup 1 (treatment).\n\"\"\"\n\ndef backtrack(n, combo=\"\", num0=0):\n if len(combo) == 2 * n:\n soln.append(combo)\n else:\n if num0 < n:\n backtrack(n, combo+\"0\", num0+1)\n\n num1 = len(combo) - num0\n if num1 < n:\n backtrack(n, combo+\"1\", num0)\n\nsoln = []\nbacktrack(3)\nprint(soln)\nprint(len(soln))\n","sub_path":"data-prog/assignments.py","file_name":"assignments.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}